prompt
stringclasses 1
value | completions
listlengths 1
63.8k
| labels
listlengths 1
63.8k
| source
stringclasses 1
value | other_info
stringlengths 2.06k
101k
| index
int64 0
6.83k
|
|---|---|---|---|---|---|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n *\t\t\tGPAC - Multimedia Framework C SDK\n *\n *\t\t\tAuthors: Jean Le Feuvre, Romain Bouqueau, Cyril Concolato\n *\t\t\tCopyright (c) Telecom ParisTech 2000-2021\n *\t\t\t\t\tAll rights reserved\n *\n * This file is part of GPAC / Media Tools sub-project\n *\n * GPAC is free software; you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2, or (at your option)\n * any later version.\n *\n * GPAC is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; see the file COPYING. If not, write to\n * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.\n *\n */",
"#include <gpac/internal/media_dev.h>\n#include <gpac/constants.h>\n#include <gpac/mpeg4_odf.h>\n#include <gpac/maths.h>\n#include <gpac/avparse.h>",
"#ifndef GPAC_DISABLE_OGG\n#include <gpac/internal/ogg.h>\n#endif",
"//uncomment/define globally to remove all bitstream parsing logging from code (this will break inspect mode ananlyze=bs)\n//#define GPAC_DISABLE_AVPARSE_LOGS",
"#ifndef GPAC_DISABLE_AVPARSE_LOGS\nvoid gf_bs_log_idx(GF_BitStream *bs, u32 nBits, const char *fname, s64 val, s32 idx1, s32 idx2, s32 idx3);",
"#define gf_bs_log(_bs, _nBits, _fname, _val) gf_bs_log_idx(_bs, _nBits, _fname, _val, -1, -1, -1)",
"u32 gf_bs_read_int_log_idx3(GF_BitStream *bs, u32 nBits, const char *fname, s32 idx1, s32 idx2, s32 idx3)\n{\n\tu32 val = gf_bs_read_int(bs, nBits);\n\tgf_bs_log_idx(bs, nBits, fname, val, idx1, idx2, idx3);\n\treturn val;\n}",
"#define gf_bs_read_int_log(_bs, _nBits, _fname) gf_bs_read_int_log_idx3(_bs, _nBits, _fname, -1, -1, -1)\n#define gf_bs_read_int_log_idx(_bs, _nBits, _fname, _idx) gf_bs_read_int_log_idx3(_bs, _nBits, _fname, _idx, -1, -1)\n#define gf_bs_read_int_log_idx2(_bs, _nBits, _fname, _idx1, _idx2) gf_bs_read_int_log_idx3(_bs, _nBits, _fname, (s32) _idx1, (s32) _idx2, -1)",
"\n#else",
"#define gf_bs_log(_bs, _nBits, _fname, _val)\n#define gf_bs_log_idx(_bs, _nBits, _fname, _val, _idx1, _idx2, _idx3)",
"#define gf_bs_read_int_log(_bs, _nbb, _f) gf_bs_read_int(_bs, _nbb)\n#define gf_bs_read_int_log_idx(_bs, _nbb, _f, _idx) gf_bs_read_int(_bs, _nbb)\n#define gf_bs_read_int_log_idx2(_bs, _nbb, _f, _idx1, _idx2) gf_bs_read_int(_bs, _nbb)\n#define gf_bs_read_int_log_idx3(_bs, _nbb, _f, _idx1, _idx2, _idx3) gf_bs_read_int(_bs, _nbb)",
"#endif",
"",
"\nstatic const struct {\n\tu32 w, h;\n} std_par[] =\n{\n\t{ 4, 3}, {3, 2}, {16, 9}, {5, 3}, {5, 4}, {8, 5}, {2, 1}, {1, 1},\n\t{0, 0},\n};",
"GF_EXPORT\nvoid gf_media_reduce_aspect_ratio(u32 *width, u32 *height)\n{\n\tu32 i = 0;\n\tu32 w = *width;\n\tu32 h = *height;\n\twhile (std_par[i].w) {\n\t\tif (std_par[i].w * h == std_par[i].h * w) {\n\t\t\t*width = std_par[i].w;\n\t\t\t*height = std_par[i].h;\n\t\t\treturn;\n\t\t}\n\t\ti++;\n\t}\n\t//not standard one, reduce by power of 2\n\ti = 2;\n\twhile (1) {\n\t\tif (w <= i) return;\n\t\tif (h <= i) return;",
"\t\tif (w % i) return;\n\t\tif (h % i) return;\n\t\t*width = w / i;\n\t\t*height = h / i;\n\t\ti *= 2;\n\t}\n}",
"GF_EXPORT\nvoid gf_media_get_reduced_frame_rate(u32 *timescale, u32 *sample_dur)\n{\n\tu32 res;\n\tif (!*sample_dur) return;\n\tres = *timescale / *sample_dur;\n\tif (res * (*sample_dur) == *timescale) {\n\t\t*timescale = res;\n\t\t*sample_dur = 1;\n\t}\n\telse if ((double)(*timescale * 1001 - (res + 1) * *sample_dur * 1000) / ((res + 1) * *sample_dur * 1000) < 0.001) {\n\t\t*timescale = (res + 1) * 1000;\n\t\t*sample_dur = 1001;\n\t}\n}",
"struct __m4v_profile\n{\n\tu32 value;\n\tconst char *name;\n} M4VProfiles[] = {\n\t{0x00, \"Reserved (0x00) Profile\"},\n\t{0x01, \"Simple Profile @ Level 1\"},\n\t{0x02, \"Simple Profile @ Level 2\"},\n\t{0x03, \"Simple Profile @ Level 3\"},\n\t{0x08, \"Simple Profile @ Level 0\"},\n\t{0x10, \"Simple Scalable Profile @ Level 0\"},\n\t{0x11, \"Simple Scalable Profile @ Level 1\"},\n\t{0x12, \"Simple Scalable Profile @ Level 2\"},\n\t{0x21, \"Core Profile @ Level 1\"},\n\t{0x22, \"Core Profile @ Level 2\"},\n\t{0x32, \"Main Profile @ Level 2\"},\n\t{0x33, \"Main Profile @ Level 3\"},\n\t{0x34, \"Main Profile @ Level 4\"},\n\t{0x42, \"N-bit Profile @ Level 2\"},\n\t{0x51, \"Scalable Texture Profile @ Level 1\"},\n\t{0x61, \"Simple Face Animation Profile @ Level 1\"},\n\t{0x62, \"Simple Face Animation Profile @ Level 2\"},\n\t{0x63, \"Simple FBA Profile @ Level 1\"},\n\t{0x64, \"Simple FBA Profile @ Level 2\"},\n\t{0x71, \"Basic Animated Texture Profile @ Level 1\"},\n\t{0x72, \"Basic Animated Texture Profile @ Level 2\"},\n\t{0x7F, \"AVC/H264 Profile\"},\n\t{0x81, \"Hybrid Profile @ Level 1\"},\n\t{0x82, \"Hybrid Profile @ Level 2\"},\n\t{0x91, \"Advanced Real Time Simple Profile @ Level 1\"},\n\t{0x92, \"Advanced Real Time Simple Profile @ Level 2\"},\n\t{0x93, \"Advanced Real Time Simple Profile @ Level 3\"},\n\t{0x94, \"Advanced Real Time Simple Profile @ Level 4\"},\n\t{0xA1, \"Core Scalable Profile @ Level1\"},\n\t{0xA2, \"Core Scalable Profile @ Level2\"},\n\t{0xA3, \"Core Scalable Profile @ Level3\"},\n\t{0xB1, \"Advanced Coding Efficiency Profile @ Level 1\"},\n\t{0xB2, \"Advanced Coding Efficiency Profile @ Level 2\"},\n\t{0xB3, \"Advanced Coding Efficiency Profile @ Level 3\"},\n\t{0xB4, \"Advanced Coding Efficiency Profile @ Level 4\"},\n\t{0xC1, \"Advanced Core Profile @ Level 1\"},\n\t{0xC2, \"Advanced Core Profile @ Level 2\"},\n\t{0xD1, \"Advanced Scalable Texture @ Level1\"},\n\t{0xD2, \"Advanced Scalable Texture @ Level2\"},\n\t{0xE1, \"Simple Studio Profile @ Level 1\"},\n\t{0xE2, \"Simple Studio Profile @ Level 2\"},\n\t{0xE3, \"Simple Studio Profile @ Level 3\"},\n\t{0xE4, \"Simple Studio Profile @ Level 4\"},\n\t{0xE5, \"Core Studio Profile @ Level 1\"},\n\t{0xE6, \"Core Studio Profile @ Level 2\"},\n\t{0xE7, \"Core Studio Profile @ Level 3\"},\n\t{0xE8, \"Core Studio Profile @ Level 4\"},\n\t{0xF0, \"Advanced Simple Profile @ Level 0\"},\n\t{0xF1, \"Advanced Simple Profile @ Level 1\"},\n\t{0xF2, \"Advanced Simple Profile @ Level 2\"},\n\t{0xF3, \"Advanced Simple Profile @ Level 3\"},\n\t{0xF4, \"Advanced Simple Profile @ Level 4\"},\n\t{0xF5, \"Advanced Simple Profile @ Level 5\"},\n\t{0xF7, \"Advanced Simple Profile @ Level 3b\"},\n\t{0xF8, \"Fine Granularity Scalable Profile @ Level 0\"},\n\t{0xF9, \"Fine Granularity Scalable Profile @ Level 1\"},\n\t{0xFA, \"Fine Granularity Scalable Profile @ Level 2\"},\n\t{0xFB, \"Fine Granularity Scalable Profile @ Level 3\"},\n\t{0xFC, \"Fine Granularity Scalable Profile @ Level 4\"},\n\t{0xFD, \"Fine Granularity Scalable Profile @ Level 5\"},\n\t{0xFE, \"Not part of MPEG-4 Visual profiles\"},\n\t{0xFF, \"No visual capability required\"}\n};",
"GF_EXPORT\nconst char *gf_m4v_get_profile_name(u8 video_pl)\n{\n\tu32 i, count = GF_ARRAY_LENGTH(M4VProfiles);\n\tfor (i=0; i<count; i++) {\n\t\tif ((u32)video_pl == M4VProfiles[i].value)\n\t\t\treturn M4VProfiles[i].name;\n\t}\n\treturn \"ISO Reserved Profile\";\n}",
"\n#ifndef GPAC_DISABLE_AV_PARSERS",
"#define MPEG12_START_CODE_PREFIX\t\t0x000001\n#define MPEG12_PICTURE_START_CODE\t\t0x00000100\n#define MPEG12_SLICE_MIN_START\t\t\t0x00000101\n#define MPEG12_SLICE_MAX_START\t\t\t0x000001af\n#define MPEG12_USER_DATA_START_CODE\t\t0x000001b2\n#define MPEG12_SEQUENCE_START_CODE\t\t0x000001b3\n#define MPEG12_SEQUENCE_ERR_START_CODE\t0x000001b4\n#define MPEG12_EXT_START_CODE\t\t\t0x000001b5\n#define MPEG12_SEQUENCE_END_START_CODE\t0x000001b7\n#define MPEG12_GOP_START_CODE\t\t\t0x000001b8",
"s32 gf_mv12_next_start_code(unsigned char *pbuffer, u32 buflen, u32 *optr, u32 *scode)\n{\n\tu32 value;\n\tu32 offset;",
"\tif (buflen < 4) return -1;\n\tfor (offset = 0; offset < buflen - 3; offset++, pbuffer++) {\n#ifdef GPAC_BIG_ENDIAN\n\t\tvalue = *(u32 *)pbuffer >> 8;\n#else\n\t\tvalue = (pbuffer[0] << 16) | (pbuffer[1] << 8) | (pbuffer[2] << 0);\n#endif",
"\t\tif (value == MPEG12_START_CODE_PREFIX) {\n\t\t\t*optr = offset;\n\t\t\t*scode = (value << 8) | pbuffer[3];\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn -1;\n}",
"s32 gf_mv12_next_slice_start(unsigned char *pbuffer, u32 startoffset, u32 buflen, u32 *slice_offset)\n{\n\tu32 slicestart, code;\n\twhile (gf_mv12_next_start_code(pbuffer + startoffset, buflen - startoffset, &slicestart, &code) >= 0) {\n\t\tif ((code >= MPEG12_SLICE_MIN_START) && (code <= MPEG12_SLICE_MAX_START)) {\n\t\t\t*slice_offset = slicestart + startoffset;\n\t\t\treturn 0;\n\t\t}\n\t\tstartoffset += slicestart + 4;\n\t}\n\treturn -1;\n}",
"\n/*\n\tMPEG-4 video (14496-2)\n*/",
"struct __tag_m4v_parser\n{\n\tGF_BitStream *bs;\n\tBool mpeg12, step_mode;\n\tu32 current_object_type;\n\tu32 force_next_obj_type;\n\tu64 current_object_start;\n\tu32 tc_dec, prev_tc_dec, tc_disp, prev_tc_disp;\n};",
"GF_EXPORT\nGF_M4VParser *gf_m4v_parser_new(u8 *data, u64 data_size, Bool mpeg12video)\n{\n\tGF_M4VParser *tmp;\n\tif (!data || !data_size) return NULL;\n\tGF_SAFEALLOC(tmp, GF_M4VParser);\n\tif (!tmp) return NULL;\n\ttmp->bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);\n\ttmp->mpeg12 = mpeg12video;\n\treturn tmp;\n}",
"GF_M4VParser *gf_m4v_parser_bs_new(GF_BitStream *bs, Bool mpeg12video)\n{\n\tGF_M4VParser *tmp;\n\tGF_SAFEALLOC(tmp, GF_M4VParser);\n\tif (!tmp) return NULL;\n\ttmp->bs = bs;\n\ttmp->mpeg12 = mpeg12video;\n\treturn tmp;\n}",
"GF_EXPORT\nvoid gf_m4v_parser_del(GF_M4VParser *m4v)\n{\n\tgf_bs_del(m4v->bs);\n\tgf_free(m4v);\n}",
"GF_EXPORT\nvoid gf_m4v_parser_del_no_bs(GF_M4VParser *m4v)\n{\n\tgf_free(m4v);\n}",
"GF_EXPORT\nvoid gf_m4v_parser_set_inspect(GF_M4VParser *m4v)\n{\n\tif (m4v) m4v->step_mode = 1;\n}\nGF_EXPORT\nu32 gf_m4v_parser_get_obj_type(GF_M4VParser *m4v)\n{\n\tif (m4v) return m4v->current_object_type;\n\treturn 0;\n}",
"#define M4V_CACHE_SIZE\t\t4096\ns32 M4V_LoadObject(GF_M4VParser *m4v)\n{\n\tu32 v, bpos, found;\n\tchar m4v_cache[M4V_CACHE_SIZE];\n\tu64 end, cache_start, load_size;\n\tif (!m4v) return 0;\n\tif (m4v->force_next_obj_type) {\n\t\tm4v->current_object_type = m4v->force_next_obj_type - 1;\n\t\tm4v->force_next_obj_type = 0;\n\t\treturn (s32)m4v->current_object_type;\n\t}",
"\tbpos = 0;\n\tfound = 0;\n\tload_size = 0;\n\tend = 0;\n\tcache_start = 0;\n\tv = 0xffffffff;\n\twhile (!end) {\n\t\t/*refill cache*/\n\t\tif (bpos == (u32)load_size) {\n\t\t\tif (!gf_bs_available(m4v->bs)) break;\n\t\t\tload_size = gf_bs_available(m4v->bs);\n\t\t\tif (load_size > M4V_CACHE_SIZE) load_size = M4V_CACHE_SIZE;\n\t\t\tbpos = 0;\n\t\t\tcache_start = gf_bs_get_position(m4v->bs);\n\t\t\tgf_bs_read_data(m4v->bs, m4v_cache, (u32)load_size);\n\t\t}\n\t\tv = ((v << 8) & 0xFFFFFF00) | ((u8)m4v_cache[bpos]);\n\t\tbpos++;\n\t\tif ((v & 0xFFFFFF00) == 0x00000100) {\n\t\t\tend = cache_start + bpos - 4;\n\t\t\tfound = 1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!found) return -1;\n\tm4v->current_object_start = end;\n\tgf_bs_seek(m4v->bs, end + 3);\n\tm4v->current_object_type = gf_bs_read_u8(m4v->bs);\n\treturn (s32)m4v->current_object_type;\n}",
"\nGF_EXPORT\nvoid gf_m4v_rewrite_pl(u8 **o_data, u32 *o_dataLen, u8 PL)\n{\n\tu32 pos = 0;\n\tunsigned char *data = (unsigned char *)*o_data;\n\tu32 dataLen = *o_dataLen;",
"\twhile (pos + 4 < dataLen) {\n\t\tif (!data[pos] && !data[pos + 1] && (data[pos + 2] == 0x01) && (data[pos + 3] == M4V_VOS_START_CODE)) {\n\t\t\tdata[pos + 4] = PL;\n\t\t\treturn;\n\t\t}\n\t\tpos++;\n\t}\n\t/*emulate VOS at beggining*/\n\t(*o_data) = (char *)gf_malloc(sizeof(char)*(dataLen + 5));\n\t(*o_data)[0] = 0;\n\t(*o_data)[1] = 0;\n\t(*o_data)[2] = 1;\n\t(*o_data)[3] = (char)M4V_VOS_START_CODE;\n\t(*o_data)[4] = PL;\n\tmemcpy((*o_data + 5), data, sizeof(char)*dataLen);\n\tgf_free(data);\n\t(*o_dataLen) = dataLen + 5;\n}",
"static GF_Err M4V_Reset(GF_M4VParser *m4v, u64 start)\n{\n\tgf_bs_seek(m4v->bs, start);",
"\tassert(start < (u64)1<<31);\n\tm4v->current_object_start = (u32)start;\n\tm4v->current_object_type = 0;\n\treturn GF_OK;\n}",
"void gf_m4v_parser_reset(GF_M4VParser *m4v, u8 sc_type)\n{\n\tm4v->current_object_start = 0;\n\tm4v->current_object_type = 0;\n\tm4v->force_next_obj_type = sc_type;\n}\nstatic GF_Err gf_m4v_parse_config_mpeg12(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)\n{\n\tunsigned char p[4];\n\tu32 ext_type;\n\ts32 o_type;\n\tu8 go, par;",
"\tif (!m4v || !dsi) return GF_BAD_PARAM;",
"\tmemset(dsi, 0, sizeof(GF_M4VDecSpecInfo));\n\tdsi->VideoPL = 0;",
"\tgo = 1;\n\twhile (go) {\n\t\to_type = M4V_LoadObject(m4v);\n\t\tswitch (o_type) {\n\t\tcase M2V_SEQ_START_CODE:\n\t\t\tdsi->RAP_stream = 1;\n\t\t\tgf_bs_read_data(m4v->bs, (char *)p, 4);\n\t\t\tdsi->width = (p[0] << 4) | ((p[1] >> 4) & 0xf);\n\t\t\tdsi->height = ((p[1] & 0xf) << 8) | p[2];",
"\t\t\tdsi->VideoPL = GF_CODECID_MPEG1;\n\t\t\tpar = (p[3] >> 4) & 0xf;\n\t\t\tswitch (par) {\n\t\t\tcase 2:\n\t\t\t\tdsi->par_num = dsi->height / 3;\n\t\t\t\tdsi->par_den = dsi->width / 4;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tdsi->par_num = dsi->height / 9;\n\t\t\t\tdsi->par_den = dsi->width / 16;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tdsi->par_num = dsi->height / 2;\n\t\t\t\tdsi->par_den = dsi->width / 21;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tdsi->par_den = dsi->par_num = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tswitch (p[3] & 0xf) {\n\t\t\tcase 0:\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tdsi->fps = 24000.0 / 1001.0;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tdsi->fps = 24.0;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tdsi->fps = 25.0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tdsi->fps = 30000.0 / 1001.0;\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tdsi->fps = 30.0;\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\tdsi->fps = 50.0;\n\t\t\t\tbreak;\n\t\t\tcase 7:\n\t\t\t\tdsi->fps = ((60.0*1000.0) / 1001.0);\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\tdsi->fps = 60.0;\n\t\t\t\tbreak;\n\t\t\tcase 9:\n\t\t\t\tdsi->fps = 1;\n\t\t\t\tbreak;\n\t\t\tcase 10:\n\t\t\t\tdsi->fps = 5;\n\t\t\t\tbreak;\n\t\t\tcase 11:\n\t\t\t\tdsi->fps = 10;\n\t\t\t\tbreak;\n\t\t\tcase 12:\n\t\t\t\tdsi->fps = 12;\n\t\t\t\tbreak;\n\t\t\tcase 13:\n\t\t\t\tdsi->fps = 15;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase M2V_EXT_START_CODE:\n\t\t\tgf_bs_read_data(m4v->bs, (char *)p, 4);\n\t\t\text_type = ((p[0] >> 4) & 0xf);\n\t\t\tif (ext_type == 1) {\n\t\t\t\tdsi->VideoPL = 0x65;\n\t\t\t\tdsi->height = ((p[1] & 0x1) << 13) | ((p[2] & 0x80) << 5) | (dsi->height & 0x0fff);\n\t\t\t\tdsi->width = (((p[2] >> 5) & 0x3) << 12) | (dsi->width & 0x0fff);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase M2V_PIC_START_CODE:\n\t\t\tif (dsi->width) go = 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t\t/*EOS*/\n\t\tcase -1:\n\t\t\tgo = 0;\n\t\t\tm4v->current_object_start = gf_bs_get_position(m4v->bs);\n\t\t\tbreak;\n\t\t}\n\t}\n\tM4V_Reset(m4v, 0);\n\treturn GF_OK;\n}",
"\nstatic const struct {\n\tu32 w, h;\n} m4v_sar[6] = { { 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 }, { 40, 33 } };",
"static u8 m4v_get_sar_idx(u32 w, u32 h)\n{\n\tu32 i;\n\tfor (i = 0; i < 6; i++) {\n\t\tif ((m4v_sar[i].w == w) && (m4v_sar[i].h == h)) return i;\n\t}\n\treturn 0xF;\n}",
"static void gf_m4v_parse_vol(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)\n{\n\tu8 verid, par;\n\ts32 clock_rate;\n\tu8 vpl = dsi->VideoPL;",
"\tmemset(dsi, 0, sizeof(GF_M4VDecSpecInfo));\n\tdsi->VideoPL = vpl;",
"\tverid = 0;\n\tdsi->RAP_stream = gf_bs_read_int(m4v->bs, 1);\n\tdsi->objectType = gf_bs_read_int(m4v->bs, 8);\n\tif (gf_bs_read_int(m4v->bs, 1)) {\n\t\tverid = gf_bs_read_int(m4v->bs, 4);\n\t\tgf_bs_read_int(m4v->bs, 3);\n\t}\n\tpar = gf_bs_read_int(m4v->bs, 4);\n\tif (par == 0xF) {\n\t\tdsi->par_num = gf_bs_read_int(m4v->bs, 8);\n\t\tdsi->par_den = gf_bs_read_int(m4v->bs, 8);\n\t} else if (par<6) {\n\t\tdsi->par_num = m4v_sar[par].w;\n\t\tdsi->par_den = m4v_sar[par].h;\n\t}\n\tif (gf_bs_read_int(m4v->bs, 1)) {\n\t\tgf_bs_read_int(m4v->bs, 3);\n\t\tif (gf_bs_read_int(m4v->bs, 1)) gf_bs_read_int(m4v->bs, 79);\n\t}\n\tdsi->has_shape = gf_bs_read_int(m4v->bs, 2);\n\tif (dsi->has_shape && (verid!=1) ) gf_bs_read_int(m4v->bs, 4);\n\tgf_bs_read_int(m4v->bs, 1);\n\t/*clock rate*/\n\tdsi->clock_rate = gf_bs_read_int(m4v->bs, 16);\n\t/*marker*/\n\tgf_bs_read_int(m4v->bs, 1);",
"\tclock_rate = dsi->clock_rate-1;\n\tif (clock_rate >= 65536) clock_rate = 65535;\n\tif (clock_rate > 0) {\n\t\tfor (dsi->NumBitsTimeIncrement = 1; dsi->NumBitsTimeIncrement < 16; dsi->NumBitsTimeIncrement++)\t{\n\t\t\tif (clock_rate == 1) break;\n\t\t\tclock_rate = (clock_rate >> 1);\n\t\t}\n\t} else {\n\t\t/*fix from vivien for divX*/\n\t\tdsi->NumBitsTimeIncrement = 1;\n\t}\n\t/*fixed FPS stream*/\n\tdsi->time_increment = 0;\n\tif (gf_bs_read_int(m4v->bs, 1)) {\n\t\tdsi->time_increment = gf_bs_read_int(m4v->bs, dsi->NumBitsTimeIncrement);\n\t}\n\tif (!dsi->has_shape) {\n\t\tgf_bs_read_int(m4v->bs, 1);\n\t\tdsi->width = gf_bs_read_int(m4v->bs, 13);\n\t\tgf_bs_read_int(m4v->bs, 1);\n\t\tdsi->height = gf_bs_read_int(m4v->bs, 13);\n\t} else {\n\t\tdsi->width = dsi->height = 0;\n\t}\n\tgf_bs_align(m4v->bs);\n}",
"static GF_Err gf_m4v_parse_config_mpeg4(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)\n{\n\ts32 o_type;\n\tu8 go;",
"\tif (!m4v || !dsi) return GF_BAD_PARAM;",
"\tmemset(dsi, 0, sizeof(GF_M4VDecSpecInfo));",
"\tgo = 1;\n\twhile (go) {\n\t\to_type = M4V_LoadObject(m4v);\n\t\tswitch (o_type) {\n\t\t\t/*vosh*/\n\t\tcase M4V_VOS_START_CODE:\n\t\t\tdsi->VideoPL = (u8)gf_bs_read_u8(m4v->bs);\n\t\t\tbreak;",
"\t\tcase M4V_VOL_START_CODE:\n\t\t\tgf_m4v_parse_vol(m4v, dsi);\n\t\t\t/*shape will be done later*/\n\t\t\tgf_bs_align(m4v->bs);\n\t\t\tbreak;",
"\t\tcase M4V_VOP_START_CODE:\n\t\tcase M4V_GOV_START_CODE:\n\t\t\tgo = 0;\n\t\t\tbreak;\n\t\t\t/*EOS*/\n\t\tcase -1:\n\t\t\tm4v->current_object_start = gf_bs_get_position(m4v->bs);\n\t\t\treturn GF_EOS;\n\t\t\t/*don't interest us*/\n\t\tcase M4V_UDTA_START_CODE:\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4v_parse_config(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)\n{\n\tif (m4v->mpeg12) {\n\t\treturn gf_m4v_parse_config_mpeg12(m4v, dsi);\n\t}\n\telse {\n\t\treturn gf_m4v_parse_config_mpeg4(m4v, dsi);\n\t}\n}",
"static GF_Err gf_m4v_parse_frame_mpeg12(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)\n{\n\tu8 go, hasVOP, firstObj, val;\n\ts32 o_type;",
"\tif (!m4v || !size || !start || !frame_type) return GF_BAD_PARAM;",
"\t*size = 0;\n\tfirstObj = 1;\n\thasVOP = 0;\n\t*is_coded = GF_FALSE;\n\t*frame_type = 0;",
"\tif (!m4v->step_mode)\n\t\tM4V_Reset(m4v, m4v->current_object_start);",
"\tm4v->current_object_type = (u32)-1;\n\tgo = 1;\n\twhile (go) {\n\t\to_type = M4V_LoadObject(m4v);\n\t\tswitch (o_type) {\n\t\tcase M2V_PIC_START_CODE:\n\t\t\t/*done*/\n\t\t\tif (hasVOP) {\n\t\t\t\tgo = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\thasVOP = 1;\n\t\t\t*is_coded = 1;",
"\t\t\t/*val = */gf_bs_read_u8(m4v->bs);\n\t\t\tval = gf_bs_read_u8(m4v->bs);\n\t\t\t*frame_type = ((val >> 3) & 0x7) - 1;\n\t\t\tbreak;\n\t\tcase M2V_GOP_START_CODE:\n\t\t\tif (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\tif (hasVOP) go = 0;\n\t\t\tbreak;",
"\t\tcase M2V_SEQ_START_CODE:\n\t\t\tif (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\tif (hasVOP) {\n\t\t\t\tgo = 0;\n\t\t\t\tbreak;\n\t\t\t}",
"\t\t\t/**/\n\t\t\tbreak;",
"\t\tdefault:\n\t\t\tbreak;",
"\t\tcase -1:\n\t\t\t*size = gf_bs_get_position(m4v->bs) - *start;\n\t\t\treturn GF_EOS;\n\t\t}\n\t\tif (m4v->step_mode)\n\t\t\treturn GF_OK;\n\t}\n\t*size = m4v->current_object_start - *start;\n\treturn GF_OK;\n}",
"static GF_Err gf_m4v_parse_frame_mpeg4(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)\n{\n\tu8 go, hasVOP, firstObj, secs;\n\ts32 o_type;\n\tu32 vop_inc = 0;",
"\tif (!m4v || !size || !start || !frame_type) return GF_BAD_PARAM;",
"\t*size = 0;\n\tfirstObj = 1;\n\thasVOP = 0;\n\t*is_coded = 0;\n\tm4v->current_object_type = (u32)-1;\n\t*frame_type = 0;\n\t*start = 0;",
"\tif (!m4v->step_mode)\n\t\tM4V_Reset(m4v, m4v->current_object_start);",
"\tgo = 1;\n\twhile (go) {\n\t\to_type = M4V_LoadObject(m4v);\n\t\tswitch (o_type) {\n\t\tcase M4V_VOP_START_CODE:\n\t\t\t/*done*/\n\t\t\tif (hasVOP) {\n\t\t\t\tgo = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\thasVOP = 1;",
"\t\t\t/*coding type*/\n\t\t\t*frame_type = gf_bs_read_int(m4v->bs, 2);\n\t\t\t/*modulo time base*/\n\t\t\tsecs = 0;\n\t\t\twhile (gf_bs_read_int(m4v->bs, 1) != 0)\n\t\t\t\tsecs++;\n\t\t\t/*no support for B frames in parsing*/\n\t\t\tsecs += (dsi->enh_layer || *frame_type!=2) ? m4v->tc_dec : m4v->tc_disp;\n\t\t\t/*marker*/\n\t\t\tgf_bs_read_int(m4v->bs, 1);\n\t\t\t/*vop_time_inc*/\n\t\t\tif (dsi->NumBitsTimeIncrement)\n\t\t\t\tvop_inc = gf_bs_read_int(m4v->bs, dsi->NumBitsTimeIncrement);",
"\t\t\tm4v->prev_tc_dec = m4v->tc_dec;\n\t\t\tm4v->prev_tc_disp = m4v->tc_disp;\n\t\t\tif (dsi->enh_layer || *frame_type!=2) {\n\t\t\t\tm4v->tc_disp = m4v->tc_dec;\n\t\t\t\tm4v->tc_dec = secs;\n\t\t\t}\n\t\t\t*time_inc = secs * dsi->clock_rate + vop_inc;\n\t\t\t/*marker*/\n\t\t\tgf_bs_read_int(m4v->bs, 1);\n\t\t\t/*coded*/\n\t\t\t*is_coded = gf_bs_read_int(m4v->bs, 1);\n\t\t\tgf_bs_align(m4v->bs);\n\t\t\tbreak;\n\t\tcase M4V_GOV_START_CODE:\n\t\t\tif (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\tif (hasVOP) go = 0;\n\t\t\tbreak;",
"\t\tcase M4V_VOL_START_CODE:\n\t\t\tif (m4v->step_mode)\n\t\t\t\tgf_m4v_parse_vol(m4v, dsi);\n\t\tcase M4V_VOS_START_CODE:\n\t\t\tif (hasVOP) {\n\t\t\t\tgo = 0;\n\t\t\t}\n\t\t\telse if (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\tbreak;",
"\t\tcase M4V_VO_START_CODE:\n\t\tdefault:\n\t\t\tbreak;",
"\t\tcase -1:\n\t\t\t*size = gf_bs_get_position(m4v->bs) - *start;\n\t\t\treturn GF_EOS;\n\t\t}\n\t\tif (m4v->step_mode)\n\t\t\treturn GF_OK;\n\t}\n\tassert(m4v->current_object_start >= *start);\n\t*size = m4v->current_object_start - *start;\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4v_parse_frame(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)\n{\n\tif (m4v->mpeg12) {\n\t\treturn gf_m4v_parse_frame_mpeg12(m4v, dsi, frame_type, time_inc, size, start, is_coded);\n\t}\n\telse {\n\t\treturn gf_m4v_parse_frame_mpeg4(m4v, dsi, frame_type, time_inc, size, start, is_coded);\n\t}\n}",
"GF_Err gf_m4v_rewrite_par(u8 **o_data, u32 *o_dataLen, s32 par_n, s32 par_d)\n{\n\tu64 start, end, size;\n\tGF_BitStream *mod;\n\tGF_M4VParser *m4v;\n\tBool go = 1;",
"\tm4v = gf_m4v_parser_new(*o_data, *o_dataLen, 0);\n\tmod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);",
"\tstart = 0;\n\twhile (go) {\n\t\tu32 type = M4V_LoadObject(m4v);",
"\t\tend = gf_bs_get_position(m4v->bs) - 4;\n\t\tsize = end - start;\n\t\t/*store previous object*/\n\t\tif (size) {\n\t\t\tassert (size < (u64)1<<31);\n\t\t\tgf_bs_write_data(mod, *o_data + start, (u32)size);\n\t\t\tstart = end;\n\t\t}",
"\t\tswitch (type) {\n\t\tcase M4V_VOL_START_CODE:\n\t\t\tgf_bs_write_int(mod, 0, 8);\n\t\t\tgf_bs_write_int(mod, 0, 8);\n\t\t\tgf_bs_write_int(mod, 1, 8);\n\t\t\tgf_bs_write_int(mod, M4V_VOL_START_CODE, 8);\n\t\t\tgf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 1), 1);\n\t\t\tgf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 8), 8);\n\t\t\tstart = gf_bs_read_int(m4v->bs, 1);\n\t\t\tgf_bs_write_int(mod, (u32)start, 1);\n\t\t\tif (start) {\n\t\t\t\tgf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 7), 7);\n\t\t\t}\n\t\t\tstart = gf_bs_read_int(m4v->bs, 4);\n\t\t\tif (start == 0xF) {\n\t\t\t\tgf_bs_read_int(m4v->bs, 8);\n\t\t\t\tgf_bs_read_int(m4v->bs, 8);\n\t\t\t}\n\t\t\tif ((par_n >= 0) && (par_d >= 0)) {\n\t\t\t\tu8 par = m4v_get_sar_idx(par_n, par_d);\n\t\t\t\tgf_bs_write_int(mod, par, 4);\n\t\t\t\tif (par == 0xF) {\n\t\t\t\t\tgf_bs_write_int(mod, par_n, 8);\n\t\t\t\t\tgf_bs_write_int(mod, par_d, 8);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tgf_bs_write_int(mod, 0x0, 4);\n\t\t\t}\n\t\tcase -1:\n\t\t\tgo = 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\twhile (gf_bs_bits_available(m4v->bs)) {\n\t\tu32 b = gf_bs_read_int(m4v->bs, 1);\n\t\tgf_bs_write_int(mod, b, 1);\n\t}",
"\tgf_m4v_parser_del(m4v);\n\tgf_free(*o_data);\n\tgf_bs_get_content(mod, o_data, o_dataLen);\n\tgf_bs_del(mod);\n\treturn GF_OK;\n}",
"GF_EXPORT\nu64 gf_m4v_get_object_start(GF_M4VParser *m4v)\n{\n\treturn m4v->current_object_start;\n}",
"#if 0 //unused\nBool gf_m4v_is_valid_object_type(GF_M4VParser *m4v)\n{\n\treturn ((s32)m4v->current_object_type == -1) ? 0 : 1;\n}\n#endif",
"\nGF_EXPORT\nGF_Err gf_m4v_get_config(u8 *rawdsi, u32 rawdsi_size, GF_M4VDecSpecInfo *dsi)\n{\n\tGF_Err e;\n\tGF_M4VParser *vparse;\n\tif (!rawdsi || !rawdsi_size) return GF_NON_COMPLIANT_BITSTREAM;\n\tvparse = gf_m4v_parser_new(rawdsi, rawdsi_size, 0);\n\te = gf_m4v_parse_config(vparse, dsi);\n\tdsi->next_object_start = (u32)vparse->current_object_start;\n\tgf_m4v_parser_del(vparse);\n\treturn e < 0 ? e : GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_mpegv12_get_config(u8 *rawdsi, u32 rawdsi_size, GF_M4VDecSpecInfo *dsi)\n{\n\tGF_Err e;\n\tGF_M4VParser *vparse;\n\tif (!rawdsi || !rawdsi_size) return GF_NON_COMPLIANT_BITSTREAM;\n\tvparse = gf_m4v_parser_new(rawdsi, rawdsi_size, GF_TRUE);\n\te = gf_m4v_parse_config(vparse, dsi);\n\tdsi->next_object_start = (u32)vparse->current_object_start;\n\tgf_m4v_parser_del(vparse);\n\treturn e;\n}",
"#endif",
"\n/*\n\tAAC parser\n*/",
"struct __m4a_oti\n{\n\tu32 type;\n\tconst char *name;\n} M4AObjectTypes[] = {\n\t{0, \"MPEG-4 Audio Reserved\"},\n\t{1, \"MPEG-4 Audio AAC Main\"},\n\t{2, \"MPEG-4 Audio AAC LC\"},\n\t{3, \"MPEG-4 Audio AAC SSR\"},\n\t{4, \"MPEG-4 Audio AAC LTP\"},\n\t{5, \"MPEG-4 Audio SBR\"},\n\t{6, \"MPEG-4 Audio AAC Scalable\"},\n\t{7, \"MPEG-4 Audio TwinVQ\"},\n\t{8, \"MPEG-4 Audio CELP\"},\n\t{9, \"MPEG-4 Audio HVXC\"},\n\t{10, \"MPEG-4 Audio Reserved\"},\n\t{11, \"MPEG-4 Audio Reserved\"},\n\t{12, \"MPEG-4 Audio TTSI\"},\n\t{13, \"MPEG-4 Audio Main synthetic\"},\n\t{14, \"MPEG-4 Audio Wavetable synthesis\"},\n\t{15, \"MPEG-4 Audio General MIDI\"},\n\t{16, \"MPEG-4 Audio Algorithmic Synthesis and Audio FX\"},\n\t{17, \"MPEG-4 Audio ER AAC LC\"},\n\t{18, \"MPEG-4 Audio Reserved\"},\n\t{19, \"MPEG-4 Audio ER AAC LTP\"},\n\t{20, \"MPEG-4 Audio ER AAC scalable\"},\n\t{21, \"MPEG-4 Audio ER TwinVQ\"},\n\t{22, \"MPEG-4 Audio ER BSAC\"},\n\t{23, \"MPEG-4 Audio ER AAC LD\"},\n\t{24, \"MPEG-4 Audio ER CELP\"},\n\t{25, \"MPEG-4 Audio ER HVXC\"},\n\t{26, \"MPEG-4 Audio ER HILN\"},\n\t{27, \"MPEG-4 Audio ER Parametric\"},\n\t{28, \"MPEG-4 Audio SSC\"},\n\t{29, \"MPEG-4 Audio ParametricStereo\"},\n\t{30, \"MPEG-4 Audio Reserved\"},\n\t{31, \"MPEG-4 Audio Reserved\"},\n\t{32, \"MPEG-1 Audio Layer-1\"},\n\t{33, \"MPEG-1 Audio Layer-2\"},\n\t{34, \"MPEG-1 Audio Layer-3\"},\n\t{35, \"MPEG-4 Audio DST\"},\n\t{36, \"MPEG-4 Audio ALS\"},\n\t{37, \"MPEG-4 Audio SLS\"},\n\t{42, \"MPEG Audio xHE-AAC\"},\n};",
"GF_EXPORT\nconst char *gf_m4a_object_type_name(u32 objectType)\n{\n\tu32 i, count = GF_ARRAY_LENGTH(M4AObjectTypes);\n\tfor (i=0; i<count; i++) {\n\t\tif (objectType==M4AObjectTypes[i].type)\n\t\t\treturn M4AObjectTypes[i].name;\n\t}\n\treturn \"MPEG-4 Audio Unknown\";\n}",
"struct __m4a_profile\n{\n\tu32 value;\n\tconst char *name;\n} M4AProfiles[] = {\n\t{0x00, \"ISO Reserved (0x00)\"},\n\t{0x01, \"Main Audio Profile @ Level 1\"},\n\t{0x02, \"Main Audio Profile @ Level 2\"},\n\t{0x03, \"Main Audio Profile @ Level 3\"},\n\t{0x04, \"Main Audio Profile @ Level 4\"},\n\t{0x05, \"Scalable Audio Profile @ Level 1\"},\n\t{0x06, \"Scalable Audio Profile @ Level 2\"},\n\t{0x07, \"Scalable Audio Profile @ Level 3\"},\n\t{0x08, \"Scalable Audio Profile @ Level 4\"},\n\t{0x09, \"Speech Audio Profile @ Level 1\"},\n\t{0x0A, \"Speech Audio Profile @ Level 2\"},\n\t{0x0B, \"Synthetic Audio Profile @ Level 1\"},\n\t{0x0C, \"Synthetic Audio Profile @ Level 2\"},\n\t{0x0D, \"Synthetic Audio Profile @ Level 3\"},\n\t{0x0E, \"High Quality Audio Profile @ Level 1\"},\n\t{0x0F, \"High Quality Audio Profile @ Level 2\"},\n\t{0x10, \"High Quality Audio Profile @ Level 3\"},\n\t{0x11, \"High Quality Audio Profile @ Level 4\"},\n\t{0x12, \"High Quality Audio Profile @ Level 5\"},\n\t{0x13, \"High Quality Audio Profile @ Level 6\"},\n\t{0x14, \"High Quality Audio Profile @ Level 7\"},\n\t{0x15, \"High Quality Audio Profile @ Level 8\"},\n\t{0x16, \"Low Delay Audio Profile @ Level 1\"},\n\t{0x17, \"Low Delay Audio Profile @ Level 2\"},\n\t{0x18, \"Low Delay Audio Profile @ Level 3\"},\n\t{0x19, \"Low Delay Audio Profile @ Level 4\"},\n\t{0x1A, \"Low Delay Audio Profile @ Level 5\"},\n\t{0x1B, \"Low Delay Audio Profile @ Level 6\"},\n\t{0x1C, \"Low Delay Audio Profile @ Level 7\"},\n\t{0x1D, \"Low Delay Audio Profile @ Level 8\"},\n\t{0x1E, \"Natural Audio Profile @ Level 1\"},\n\t{0x1F, \"Natural Audio Profile @ Level 2\"},\n\t{0x20, \"Natural Audio Profile @ Level 3\"},\n\t{0x21, \"Natural Audio Profile @ Level 4\"},\n\t{0x22, \"Mobile Audio Internetworking Profile @ Level 1\"},\n\t{0x23, \"Mobile Audio Internetworking Profile @ Level 2\"},\n\t{0x24, \"Mobile Audio Internetworking Profile @ Level 3\"},\n\t{0x25, \"Mobile Audio Internetworking Profile @ Level 4\"},\n\t{0x26, \"Mobile Audio Internetworking Profile @ Level 5\"},\n\t{0x27, \"Mobile Audio Internetworking Profile @ Level 6\"},\n\t{0x28, \"AAC Profile @ Level 1\"},\n\t{0x29, \"AAC Profile @ Level 2\"},\n\t{0x2A, \"AAC Profile @ Level 4\"},\n\t{0x2B, \"AAC Profile @ Level 5\"},\n\t{0x2C, \"High Efficiency AAC Profile @ Level 2\"},\n\t{0x2D, \"High Efficiency AAC Profile @ Level 3\"},\n\t{0x2E, \"High Efficiency AAC Profile @ Level 4\"},\n\t{0x2F, \"High Efficiency AAC Profile @ Level 5\"},\n\t{0x30, \"High Efficiency AAC v2 Profile @ Level 2\"},\n\t{0x31, \"High Efficiency AAC v2 Profile @ Level 3\"},\n\t{0x32, \"High Efficiency AAC v2 Profile @ Level 4\"},\n\t{0x33, \"High Efficiency AAC v2 Profile @ Level 5\"},\n\t{0x34, \"Low Delay AAC Profile\"},\n\t{0x35, \"Baseline MPEG Surround Profile @ Level 1\"},\n\t{0x36, \"Baseline MPEG Surround Profile @ Level 2\"},\n\t{0x37, \"Baseline MPEG Surround Profile @ Level 3\"},\n\t{0x38, \"Baseline MPEG Surround Profile @ Level 4\"},\n\t{0x39, \"Baseline MPEG Surround Profile @ Level 5\"},\n\t{0x3A, \"Baseline MPEG Surround Profile @ Level 6\"},\n\t{0x3B, \"High Definition AAC Profile @ Level 1\"},\n\t{0x3C, \"ALS Simple Profile @ Level 1\"},\n\t{0x50, \"AAC Profile @ Level 6\"},\n\t{0x51, \"AAC Profile @ Level 7\"},\n\t{0x52, \"High Efficiency AAC Profile @ Level 6\"},\n\t{0x53, \"High Efficiency AAC Profile @ Level 7\"},\n\t{0x54, \"High Efficiency AAC v2 Profile @ Level 6\"},\n\t{0x55, \"High Efficiency AAC v2 Profile @ Level 7\"},\n\t{0x56, \"Extended High Efficiency AAC Profile @ Level 6\"},\n\t{0x57, \"Extended High Efficiency AAC Profile @ Level 7\"},\n\t{0xFE, \"Not part of MPEG-4 audio profiles\"},\n\t{0xFF, \"No audio capability required\"}\n};",
"GF_EXPORT\nconst char *gf_m4a_get_profile_name(u8 audio_pl)\n{\n\tu32 i, count = GF_ARRAY_LENGTH(M4AProfiles);\n\tfor (i=0; i<count; i++) {\n\t\tif ((u32) audio_pl==M4AProfiles[i].value)\n\t\t\treturn M4AProfiles[i].name;\n\t}\n\treturn \"ISO Reserved / User Private\";\n}",
"#ifndef GPAC_DISABLE_AV_PARSERS",
"GF_EXPORT\nu32 gf_m4a_get_profile(GF_M4ADecSpecInfo *cfg)\n{\n\tswitch (cfg->base_object_type) {\n\tcase 2: /*AAC LC*/\n\t\tif (cfg->nb_chan <= 2)\n\t\t\treturn (cfg->base_sr <= 24000) ? 0x28 : 0x29; /*LC@L1 or LC@L2*/\n\t\tif (cfg->nb_chan <= 5)\n\t\t\treturn (cfg->base_sr <= 48000) ? 0x2A : 0x2B; /*LC@L4 or LC@L5*/\n\t\treturn (cfg->base_sr <= 48000) ? 0x50 : 0x51; /*LC@L4 or LC@L5*/\n\tcase 5: /*HE-AAC - SBR*/\n\t\tif (cfg->nb_chan <= 2)\n\t\t\treturn (cfg->base_sr <= 24000) ? 0x2C : 0x2D; /*HE@L2 or HE@L3*/\n\t\tif (cfg->nb_chan <= 5)\n\t\t\treturn (cfg->base_sr <= 48000) ? 0x2E : 0x2F; /*HE@L4 or HE@L5*/\n\t\treturn (cfg->base_sr <= 48000) ? 0x52 : 0x53; /*HE@L6 or HE@L7*/\n\tcase 29: /*HE-AACv2 - SBR+PS*/\n\t\tif (cfg->nb_chan <= 2)\n\t\t\treturn (cfg->base_sr <= 24000) ? 0x30 : 0x31; /*HE-AACv2@L2 or HE-AACv2@L3*/\n\t\tif (cfg->nb_chan <= 5)\n\t\t\treturn (cfg->base_sr <= 48000) ? 0x32 : 0x33; /*HE-AACv2@L4 or HE-AACv2@L5*/\n\t\treturn (cfg->base_sr <= 48000) ? 0x54 : 0x55; /*HE-AACv2@L6 or HE-AACv2@L7*/\n\t/*default to HQ*/\n\tdefault:\n\t\tif (cfg->nb_chan <= 2) return (cfg->base_sr < 24000) ? 0x0E : 0x0F; /*HQ@L1 or HQ@L2*/\n\t\treturn 0x10; /*HQ@L3*/\n\t}\n}",
"GF_EXPORT\nGF_Err gf_m4a_parse_program_config_element(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg)\n{\n\tu32 i;",
"\tcfg->program_config_element_present = 1;\n\tcfg->cpe_channels = 0;",
"\tcfg->element_instance_tag = gf_bs_read_int_log(bs, 4, \"element_instance_tag\");\n\tcfg->object_type = gf_bs_read_int_log(bs, 2, \"object_type\");\n\tcfg->sampling_frequency_index = gf_bs_read_int_log(bs, 4, \"sampling_frequency_index\");\n\tcfg->num_front_channel_elements = gf_bs_read_int_log(bs, 4, \"num_front_channel_elements\");\n\tcfg->num_side_channel_elements = gf_bs_read_int_log(bs, 4, \"num_side_channel_elements\");\n\tcfg->num_back_channel_elements = gf_bs_read_int_log(bs, 4, \"num_back_channel_elements\");\n\tcfg->num_lfe_channel_elements = gf_bs_read_int_log(bs, 2, \"num_lfe_channel_elements\");\n\tcfg->num_assoc_data_elements = gf_bs_read_int_log(bs, 3, \"num_assoc_data_elements\");\n\tcfg->num_valid_cc_elements = gf_bs_read_int_log(bs, 4, \"num_valid_cc_elements\");\n\tcfg->mono_mixdown_present = (Bool)gf_bs_read_int_log(bs, 1, \"mono_mixdown_present\");\n\tif (cfg->mono_mixdown_present) {\n\t\tcfg->mono_mixdown_element_number = gf_bs_read_int_log(bs, 4, \"mono_mixdown_element_number\");\n\t}\n\tcfg->stereo_mixdown_present = gf_bs_read_int_log(bs, 1, \"stereo_mixdown_present\");\n\tif (cfg->stereo_mixdown_present) {\n\t\tcfg->stereo_mixdown_element_number = gf_bs_read_int_log(bs, 4, \"stereo_mixdown_element_number\");\n\t}\n\tcfg->matrix_mixdown_idx_present = gf_bs_read_int_log(bs, 1, \"matrix_mixdown_idx_present\");\n\tif (cfg->matrix_mixdown_idx_present) {\n\t\tcfg->matrix_mixdown_idx = gf_bs_read_int_log(bs, 2, \"matrix_mixdown_idx\");\n\t\tcfg->pseudo_surround_enable = gf_bs_read_int_log(bs, 1, \"pseudo_surround_enable\");\n\t}\n\tfor (i = 0; i < cfg->num_front_channel_elements; i++) {\n\t\tcfg->front_element_is_cpe[i] = gf_bs_read_int_log_idx(bs, 1, \"front_element_is_cpe\", i);\n\t\tcfg->front_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"front_element_tag_select\", i);\n\t\tif (cfg->front_element_is_cpe[i]) cfg->cpe_channels++;\n\t}\n\tfor (i = 0; i < cfg->num_side_channel_elements; i++) {\n\t\tcfg->side_element_is_cpe[i] = gf_bs_read_int_log_idx(bs, 1, \"side_element_is_cpe\", i);\n\t\tcfg->side_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"side_element_tag_select\", i);\n\t\tif (cfg->side_element_is_cpe[i]) cfg->cpe_channels++;\n\t}\n\tfor (i = 0; i < cfg->num_back_channel_elements; i++) {\n\t\tcfg->back_element_is_cpe[i] = gf_bs_read_int_log_idx(bs, 1, \"back_element_is_cpe\", i);\n\t\tcfg->back_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"back_element_tag_select\", i);\n\t\tif (cfg->back_element_is_cpe[i]) cfg->cpe_channels++;\n\t}\n\tfor (i = 0; i < cfg->num_lfe_channel_elements; i++) {\n\t\tcfg->lfe_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"lfe_element_tag_select\", i);\n\t}\n\tfor (i = 0; i < cfg->num_assoc_data_elements; i++) {\n\t\tcfg->assoc_data_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"assoc_data_element_tag_select\", i);\n\t}",
"\tfor (i = 0; i < cfg->num_valid_cc_elements; i++) {\n\t\tcfg->cc_element_is_ind_sw[i] = gf_bs_read_int_log_idx(bs, 1, \"cc_element_is_ind_sw\", i);\n\t\tcfg->valid_cc_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"valid_cc_element_tag_select\", i);\n\t}\n\tgf_bs_align(bs);\n\tcfg->comment_field_bytes = gf_bs_read_int_log(bs, 8, \"comment_field_bytes\");\n\tgf_bs_read_data(bs, (char *)cfg->comments, cfg->comment_field_bytes);",
"\tcfg->nb_chan = cfg->num_front_channel_elements + cfg->num_back_channel_elements + cfg->num_side_channel_elements + cfg->num_lfe_channel_elements;\n\tcfg->nb_chan += cfg->cpe_channels;",
"\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4a_parse_config(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg, Bool size_known)\n{\n\tu32 audio_obj_type;\n\tmemset(cfg, 0, sizeof(GF_M4ADecSpecInfo));\n\tcfg->base_object_type = gf_bs_read_int_log(bs, 5, \"base_object_type\");\n\t/*extended object type*/\n\tif (cfg->base_object_type == 31) {\n\t\tcfg->base_object_type = 32 + gf_bs_read_int_log(bs, 6, \"extended_base_object_type\");\n\t}\n\tcfg->base_sr_index = gf_bs_read_int_log(bs, 4, \"base_samplerate_index\");\n\tif (cfg->base_sr_index == 0x0F) {\n\t\tcfg->base_sr = gf_bs_read_int_log(bs, 24, \"base_samplerate\");\n\t}\n\telse {\n\t\tcfg->base_sr = GF_M4ASampleRates[cfg->base_sr_index];\n\t}",
"\tcfg->chan_cfg = gf_bs_read_int_log(bs, 4, \"channel_configuration\");\n\tif (cfg->chan_cfg) {\n\t\tcfg->nb_chan = GF_M4ANumChannels[cfg->chan_cfg - 1];\n\t}",
"\taudio_obj_type = cfg->base_object_type;\n\tif (cfg->base_object_type == 5 || cfg->base_object_type == 29) {\n\t\tif (cfg->base_object_type == 29) {\n\t\t\tcfg->has_ps = 1;\n\t\t\tcfg->nb_chan = 1;\n\t\t}\n\t\tcfg->has_sbr = GF_TRUE;\n\t\tcfg->sbr_sr_index = gf_bs_read_int_log(bs, 4, \"sbr_samplerate_index\");\n\t\tif (cfg->sbr_sr_index == 0x0F) {\n\t\t\tcfg->sbr_sr = gf_bs_read_int_log(bs, 24, \"sbr_samplerate\");\n\t\t}\n\t\telse {\n\t\t\tcfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];\n\t\t}\n\t\tcfg->sbr_object_type = gf_bs_read_int_log(bs, 5, \"sbr_object_type\");\n\t\tif (cfg->sbr_object_type==31)\n\t\t\tcfg->sbr_object_type = 32 + gf_bs_read_int_log(bs, 6, \"audioObjectTypeExt\");\n\t\taudio_obj_type = cfg->sbr_object_type;\n\t\tif (cfg->sbr_object_type==22) {\n\t\t\t/*ext_chan_cfg = */gf_bs_read_int_log(bs, 4, \"channel_configuration\");\n\t\t}\n\t}",
"\t/*object cfg*/\n\tswitch (audio_obj_type) {\n\tcase 1:\n\tcase 2:\n\tcase 3:\n\tcase 4:\n\tcase 6:\n\tcase 7:\n\tcase 17:\n\tcase 19:\n\tcase 20:\n\tcase 21:\n\tcase 22:\n\tcase 23:\n\tcase 42:\n\t{\n\t\tBool ext_flag;\n\t\tgf_bs_read_int_log(bs, 1, \"frame_length_flag\");\n\t\tif (gf_bs_read_int_log(bs, 1, \"depends_on_core_coder\"))\n\t\t\tgf_bs_read_int_log(bs, 14, \"delay\");\n\t\text_flag = gf_bs_read_int_log(bs, 1, \"extension_flag\");",
"\t\tif (!cfg->chan_cfg) {\n\t\t\tgf_m4a_parse_program_config_element(bs, cfg);\n\t\t}",
"\t\tif ((cfg->base_object_type == 6) || (cfg->base_object_type == 20)) {\n\t\t\tgf_bs_read_int_log(bs, 3, \"layerN\");\n\t\t}\n\t\tif (ext_flag) {\n\t\t\tif (cfg->base_object_type == 22) {\n\t\t\t\tgf_bs_read_int_log(bs, 5, \"numOfSubFrame\");\n\t\t\t\tgf_bs_read_int_log(bs, 11, \"layer_length\");\n\t\t\t}\n\t\t\tif ((cfg->base_object_type == 17)\n\t\t\t\t|| (cfg->base_object_type == 19)\n\t\t\t\t|| (cfg->base_object_type == 20)\n\t\t\t\t|| (cfg->base_object_type == 23)\n\t\t\t) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"aacSectionDataResilienceFlag\");\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"aacScalefactorDataResilienceFlag\");\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"aacSpectralDataResilienceFlag\");\n\t\t\t}\n\t\t\tgf_bs_read_int_log(bs, 1, \"extensionFlag3\");\n\t\t}\n\t}\n\tbreak;\n\t}\n\t/*ER cfg*/\n\tswitch (audio_obj_type) {\n\tcase 17:\n\tcase 19:\n\tcase 20:\n\tcase 21:\n\tcase 22:\n\tcase 23:\n\tcase 24:\n\tcase 25:\n\tcase 26:\n\tcase 27:\n\t{\n\t\tu32 epConfig = gf_bs_read_int_log(bs, 2, \"epConfig\");\n\t\tif ((epConfig == 2) || (epConfig == 3)) {\n\t\t}\n\t\tif (epConfig == 3) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"directMapping\");\n\t\t}\n\t}\n\tbreak;\n\t}",
"\tif (size_known && (cfg->base_object_type != 5) && (cfg->base_object_type != 29)) {\n\t\twhile (gf_bs_available(bs) >= 2) {\n\t\t\tu32 sync = gf_bs_peek_bits(bs, 11, 0);\n\t\t\tif (sync == 0x2b7) {\n\t\t\t\tgf_bs_read_int_log(bs, 11, \"syncExtensionType\");\n\t\t\t\tcfg->sbr_object_type = gf_bs_read_int_log(bs, 5, \"extensionAudioObjectType \");\n\t\t\t\tcfg->has_sbr = gf_bs_read_int_log(bs, 1, \"sbrPresentFlag\");\n\t\t\t\tif (cfg->has_sbr) {\n\t\t\t\t\tcfg->sbr_sr_index = gf_bs_read_int_log(bs, 4, \"extensionSamplingFrequencyIndex\");\n\t\t\t\t\tif (cfg->sbr_sr_index == 0x0F) {\n\t\t\t\t\t\tcfg->sbr_sr = gf_bs_read_int_log(bs, 24, \"extensionSamplingFrequency\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tcfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (sync == 0x548) {\n\t\t\t\tgf_bs_read_int_log(bs, 11, \"syncExtensionType\");\n\t\t\t\tcfg->has_ps = gf_bs_read_int_log(bs, 1, \"hasParametricStereo\");\n\t\t\t\tif (cfg->has_ps)\n\t\t\t\t\tcfg->nb_chan = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tcfg->audioPL = gf_m4a_get_profile(cfg);\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4a_get_config(u8 *dsi, u32 dsi_size, GF_M4ADecSpecInfo *cfg)\n{\n\tGF_BitStream *bs;\n\tif (!dsi || !dsi_size || (dsi_size < 2)) return GF_NON_COMPLIANT_BITSTREAM;\n\tbs = gf_bs_new(dsi, dsi_size, GF_BITSTREAM_READ);\n\tgf_m4a_parse_config(bs, cfg, GF_TRUE);\n\tgf_bs_del(bs);\n\treturn GF_OK;\n}",
"u32 gf_latm_get_value(GF_BitStream *bs)\n{\n\tu32 i, tmp, value = 0;\n\tu32 bytesForValue = gf_bs_read_int(bs, 2);\n\tfor (i = 0; i <= bytesForValue; i++) {\n\t\tvalue <<= 8;\n\t\ttmp = gf_bs_read_int(bs, 8);\n\t\tvalue += tmp;\n\t}\n\treturn value;\n}",
"GF_EXPORT\nu32 gf_m4a_get_channel_cfg(u32 nb_chan)\n{\n\tu32 i, count = sizeof(GF_M4ANumChannels) / sizeof(u32);\n\tfor (i = 0; i < count; i++) {\n\t\tif (GF_M4ANumChannels[i] == nb_chan) return i + 1;\n\t}\n\treturn 0;\n}",
"GF_EXPORT\nGF_Err gf_m4a_write_program_config_element_bs(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg)\n{\n\tu32 i;\n\tgf_bs_write_int(bs, cfg->element_instance_tag, 4);\n\tgf_bs_write_int(bs, cfg->object_type, 2);\n\tgf_bs_write_int(bs, cfg->sampling_frequency_index, 4);\n\tgf_bs_write_int(bs, cfg->num_front_channel_elements, 4);\n\tgf_bs_write_int(bs, cfg->num_side_channel_elements, 4);\n\tgf_bs_write_int(bs, cfg->num_back_channel_elements, 4);\n\tgf_bs_write_int(bs, cfg->num_lfe_channel_elements, 2);\n\tgf_bs_write_int(bs, cfg->num_assoc_data_elements, 3);\n\tgf_bs_write_int(bs, cfg->num_valid_cc_elements, 4);\n\tgf_bs_write_int(bs, cfg->mono_mixdown_present, 1);\n\tif (cfg->mono_mixdown_present) {\n\t\tgf_bs_write_int(bs, cfg->mono_mixdown_element_number, 4);\n\t}\n\tgf_bs_write_int(bs, cfg->stereo_mixdown_present, 1);\n\tif (cfg->stereo_mixdown_present) {\n\t\tgf_bs_write_int(bs, cfg->stereo_mixdown_element_number, 4);\n\t}\n\tgf_bs_write_int(bs, cfg->matrix_mixdown_idx_present, 1);\n\tif (cfg->matrix_mixdown_idx_present) {\n\t\tgf_bs_write_int(bs, cfg->matrix_mixdown_idx, 2);\n\t\tgf_bs_write_int(bs, cfg->pseudo_surround_enable, 1);\n\t}\n\tfor (i = 0; i < cfg->num_front_channel_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->front_element_is_cpe[i], 1);\n\t\tgf_bs_write_int(bs, cfg->front_element_tag_select[i], 4);\n\t}\n\tfor (i = 0; i < cfg->num_side_channel_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->side_element_is_cpe[i], 1);\n\t\tgf_bs_write_int(bs, cfg->side_element_tag_select[i], 4);\n\t}\n\tfor (i = 0; i < cfg->num_back_channel_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->back_element_is_cpe[i], 1);\n\t\tgf_bs_write_int(bs, cfg->back_element_tag_select[i], 4);\n\t}\n\tfor (i = 0; i < cfg->num_lfe_channel_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->lfe_element_tag_select[i], 4);\n\t}\n\tfor (i = 0; i < cfg->num_assoc_data_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->assoc_data_element_tag_select[i], 4);\n\t}",
"\tfor (i = 0; i < cfg->num_valid_cc_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->cc_element_is_ind_sw[i], 1);\n\t\tgf_bs_write_int(bs, cfg->valid_cc_element_tag_select[i], 4);\n\t}\n\tgf_bs_align(bs);\n\tgf_bs_write_int(bs, cfg->comment_field_bytes, 8);\n\tgf_bs_write_data(bs, (char *)cfg->comments, cfg->comment_field_bytes);\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4a_write_config_bs(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg)\n{\n\tif (!cfg->base_sr_index) {\n\t\tif (!cfg->base_sr) return GF_BAD_PARAM;\n\t\twhile (GF_M4ASampleRates[cfg->base_sr_index]) {\n\t\t\tif (GF_M4ASampleRates[cfg->base_sr_index] == cfg->base_sr)\n\t\t\t\tbreak;\n\t\t\tcfg->base_sr_index++;\n\t\t}\n\t}\n\tif (cfg->sbr_sr && !cfg->sbr_sr_index) {\n\t\twhile (GF_M4ASampleRates[cfg->sbr_sr_index]) {\n\t\t\tif (GF_M4ASampleRates[cfg->sbr_sr_index] == cfg->sbr_sr)\n\t\t\t\tbreak;\n\t\t\tcfg->sbr_sr_index++;\n\t\t}\n\t}\n\t/*extended object type*/\n\tif (cfg->base_object_type >= 32) {\n\t\tgf_bs_write_int(bs, 31, 5);\n\t\tgf_bs_write_int(bs, cfg->base_object_type - 32, 6);\n\t}\n\telse {\n\t\tgf_bs_write_int(bs, cfg->base_object_type, 5);\n\t}\n\tgf_bs_write_int(bs, cfg->base_sr_index, 4);\n\tif (cfg->base_sr_index == 0x0F) {\n\t\tgf_bs_write_int(bs, cfg->base_sr, 24);\n\t}",
"\tif (cfg->program_config_element_present) {\n\t\tgf_bs_write_int(bs, 0, 4);\n\t} else {\n\t\tcfg->chan_cfg = gf_m4a_get_channel_cfg(cfg->nb_chan);\n\t\tif (!cfg->chan_cfg) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AAC] Cannot write decoder config, ProgramConfigElement is missing and channel configuration is not a predefined one !\\n\"));\n\t\t\treturn GF_BAD_PARAM;\n\t\t}\n\t\tgf_bs_write_int(bs, cfg->chan_cfg, 4);\n\t}",
"\tif (cfg->base_object_type == 5 || cfg->base_object_type == 29) {\n\t\tif (cfg->base_object_type == 29) {\n\t\t\tcfg->has_ps = 1;\n\t\t\tcfg->nb_chan = 1;\n\t\t}\n\t\tcfg->has_sbr = 1;\n\t\tgf_bs_write_int(bs, cfg->sbr_sr_index, 4);\n\t\tif (cfg->sbr_sr_index == 0x0F) {\n\t\t\tgf_bs_write_int(bs, cfg->sbr_sr, 24);\n\t\t}\n\t\tgf_bs_write_int(bs, cfg->sbr_object_type, 5);\n\t}",
"\t/*object cfg*/\n\tswitch (cfg->base_object_type) {\n\tcase 1:\n\tcase 2:\n\tcase 3:\n\tcase 4:\n\tcase 6:\n\tcase 7:\n\tcase 17:\n\tcase 19:\n\tcase 20:\n\tcase 21:\n\tcase 22:\n\tcase 23:\n\tcase 42:\n\t{\n\t\t/*frame length flag*/\n\t\tgf_bs_write_int(bs, 0, 1);\n\t\t/*depends on core coder*/\n\t\tgf_bs_write_int(bs, 0, 1);\n\t\t/*ext flag*/\n\t\tgf_bs_write_int(bs, 0, 1);",
"\t\tif (cfg->program_config_element_present) {\n\t\t\tgf_m4a_write_program_config_element_bs(bs, cfg);\n\t\t}",
"\t\tif ((cfg->base_object_type == 6) || (cfg->base_object_type == 20)) {\n\t\t\tgf_bs_write_int(bs, 0, 3);\n\t\t}\n\t}\n\tbreak;\n\t}\n\t/*ER cfg - not supported*/",
"\t/*implicit sbr/ps signaling not written here, cf reframe_adts*/\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4a_write_config(GF_M4ADecSpecInfo *cfg, u8 **dsi, u32 *dsi_size)\n{\n\tGF_BitStream *bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\tgf_m4a_write_config_bs(bs, cfg);\n\tgf_bs_get_content(bs, dsi, dsi_size);\n\tgf_bs_del(bs);\n\treturn GF_OK;\n}",
"\n/*AV1 parsing*/",
"static u32 av1_read_ns(GF_BitStream *bs, u32 n, const char *fname)\n{\n\tu32 v, res;\n\tBool extra_bit;\n\tint w = (u32)(log(n) / log(2)) + 1;\n\tu32 m = (1 << w) - n;\n\tassert(w < 32);\n\tv = gf_bs_read_int(bs, w - 1);\n\tif (v < m) {\n\t\tif (fname) {\n\t\t\tgf_bs_log(bs, w-1, fname, v);\n\t\t}\n\t\treturn v;\n\t}\n\textra_bit = gf_bs_read_int(bs, 1);\n\tres = (v << 1) - m + extra_bit;\n\tif (fname) {\n\t\tgf_bs_log(bs, w, fname, res);\n\t}\n\treturn res;\n}",
"static void av1_color_config(GF_BitStream *bs, AV1State *state)\n{\n\tstate->config->high_bitdepth = gf_bs_read_int_log(bs, 1, \"high_bitdepth\");\n\tstate->bit_depth = 8;\n\tif (state->config->seq_profile == 2 && state->config->high_bitdepth) {\n\t\tstate->config->twelve_bit = gf_bs_read_int_log(bs, 1, \"twelve_bit\");\n\t\tstate->bit_depth = state->config->twelve_bit ? 12 : 10;\n\t}\n\telse if (state->config->seq_profile <= 2) {\n\t\tstate->bit_depth = state->config->high_bitdepth ? 10 : 8;\n\t}",
"\tstate->config->monochrome = GF_FALSE;\n\tif (state->config->seq_profile == 1) {\n\t\tstate->config->monochrome = GF_FALSE;\n\t}\n\telse {\n\t\tstate->config->monochrome = gf_bs_read_int_log(bs, 1, \"monochrome\");\n\t}\n\t/*NumPlanes = mono_chrome ? 1 : 3;*/\n\tstate->color_description_present_flag = gf_bs_read_int_log(bs, 1, \"color_description_present_flag\");\n\tif (state->color_description_present_flag) {\n\t\tstate->color_primaries = gf_bs_read_int_log(bs, 8, \"color_primaries\");\n\t\tstate->transfer_characteristics = gf_bs_read_int_log(bs, 8, \"transfer_characteristics\");\n\t\tstate->matrix_coefficients = gf_bs_read_int_log(bs, 8, \"matrix_coefficients\");\n\t}\n\telse {\n\t\tstate->color_primaries = 2/*CP_UNSPECIFIED*/;\n\t\tstate->transfer_characteristics = 2/*TC_UNSPECIFIED*/;\n\t\tstate->matrix_coefficients = 2/*MC_UNSPECIFIED*/;\n\t}\n\tif (state->config->monochrome) {\n\t\tstate->color_range = gf_bs_read_int_log(bs, 1, \"color_range\");\n\t\tstate->config->chroma_subsampling_x = GF_TRUE;\n\t\tstate->config->chroma_subsampling_y = GF_TRUE;\n\t\tstate->config->chroma_sample_position = 0/*CSP_UNKNOWN*/;\n\t\tstate->separate_uv_delta_q = 0;\n\t\treturn;\n\t}\n\telse if (state->color_primaries == 0/*CP_BT_709*/ &&\n\t\tstate->transfer_characteristics == 13/*TC_SRGB*/ &&\n\t\tstate->matrix_coefficients == 0/*MC_IDENTITY*/) {\n\t\tstate->color_range = GF_TRUE;\n\t\tstate->config->chroma_subsampling_x = GF_FALSE;\n\t\tstate->config->chroma_subsampling_y = GF_FALSE;\n\t}\n\telse {\n\t\tstate->config->chroma_subsampling_x = GF_FALSE;\n\t\tstate->config->chroma_subsampling_y = GF_FALSE;",
"\t\tstate->color_range = gf_bs_read_int_log(bs, 1, \"color_range\");\n\t\tif (state->config->seq_profile == 0) {\n\t\t\tstate->config->chroma_subsampling_x = GF_TRUE;\n\t\t\tstate->config->chroma_subsampling_y = GF_TRUE;\n\t\t}\n\t\telse if (state->config->seq_profile == 1) {\n\t\t\tstate->config->chroma_subsampling_x = GF_FALSE;\n\t\t\tstate->config->chroma_subsampling_y = GF_FALSE;\n\t\t}\n\t\telse {\n\t\t\tif (state->bit_depth == 12) {\n\t\t\t\tstate->config->chroma_subsampling_x = gf_bs_read_int_log(bs, 1, \"chroma_subsampling_x\");\n\t\t\t\tif (state->config->chroma_subsampling_x)\n\t\t\t\t\tstate->config->chroma_subsampling_y = gf_bs_read_int_log(bs, 1, \"chroma_subsampling_y\");\n\t\t\t\telse\n\t\t\t\t\tstate->config->chroma_subsampling_y = GF_FALSE;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate->config->chroma_subsampling_x = GF_TRUE;\n\t\t\t\tstate->config->chroma_subsampling_y = GF_FALSE;\n\t\t\t}\n\t\t}\n\t\tif (state->config->chroma_subsampling_x && state->config->chroma_subsampling_y) {\n\t\t\tstate->config->chroma_sample_position = gf_bs_read_int_log(bs, 2, \"chroma_sample_position\");\n\t\t}\n\t}\n\tstate->separate_uv_delta_q = gf_bs_read_int_log(bs, 1, \"separate_uv_delta_q\");\n}",
"\nstatic u32 av1_uvlc(GF_BitStream *bs, const char *fname)\n{\n\tu32 res;\n\tu8 leadingZeros = 0;\n\twhile (1) {\n\t\tBool done = gf_bs_read_int(bs, 1);\n\t\tif (done)\n\t\t\tbreak;\n\t\tleadingZeros++;\n\t}\n\tif (leadingZeros >= 32) {\n\t\treturn 0xFFFFFFFF;\n\t}\n\tres = gf_bs_read_int(bs, leadingZeros) + (1 << leadingZeros) - 1;\n\tgf_bs_log(bs, 2*leadingZeros, fname, res);\n\treturn res;\n}",
"static void timing_info(GF_BitStream *bs, AV1State *state) {\n\tu32 time_scale = 0;\n\tu32 num_units_in_display_tick = gf_bs_read_int_log(bs, 32, \"num_units_in_display_tick\");\n\tif (num_units_in_display_tick == 0) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] num_units_in_display_tick must be greater than 0.\\n\"));\n\t}\n\ttime_scale = gf_bs_read_int_log(bs, 32, \"time_scale\");\n\tif (time_scale == 0) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] time_scale must be greater than 0.\\n\"));\n\t}\n\tstate->equal_picture_interval = gf_bs_read_int_log(bs, 1, \"equal_picture_interval\");\n\tif (state->equal_picture_interval) {\n\t\tu32 num_ticks_per_picture_minus_1 = av1_uvlc(bs, \"num_ticks_per_picture_minus_1\");\n\t\tstate->tb_num = time_scale;\n\t\tstate->tb_den = (num_ticks_per_picture_minus_1 + 1)*num_units_in_display_tick;\n\t}\n\telse {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] VFR not supported.\\n\"));\n\t\t//TODO: upload num_units_in_display_tick (eq. to the POC in H264), compute delta between frames, set it as dts_inc in gf_import_aom_av1()\n\t}\n}",
"static void decoder_model_info(AV1State *state, GF_BitStream *bs) {\n\tstate->buffer_delay_length = 1 + gf_bs_read_int_log(bs, 5, \"buffer_delay_length_minus1\");\n\tgf_bs_read_int_log(bs, 32, \"num_units_in_decoding_tick\");\n\tstate->buffer_removal_time_length = gf_bs_read_int_log(bs, 5, \"buffer_removal_time_length\");\n\tstate->frame_presentation_time_length = 1 + gf_bs_read_int_log(bs, 5, \"frame_presentation_time_length_minus1\");\n}",
"static void operating_parameters_info(GF_BitStream *bs, const u8 idx, const u8 buffer_delay_length_minus_1) {\n\tconst u8 n = buffer_delay_length_minus_1 + 1;\n\tgf_bs_read_int_log(bs, n, \"decoder_buffer_delay\");\n\tgf_bs_read_int_log(bs, n, \"encoder_buffer_delay\");\n\tgf_bs_read_int_log(bs, 1, \"low_delay_mode_flag\");\n}",
"static void av1_parse_sequence_header_obu(GF_BitStream *bs, AV1State *state)\n{\n\tu8 buffer_delay_length_minus_1 = 0;\n\tstate->frame_state.seen_seq_header = GF_TRUE;\n\tstate->config->seq_profile = gf_bs_read_int_log(bs, 3, \"seq_profile\");\n\tstate->still_picture = gf_bs_read_int_log(bs, 1, \"still_picture\");\n\tstate->reduced_still_picture_header = gf_bs_read_int_log(bs, 1, \"reduced_still_picture_header\");\n\tif (state->reduced_still_picture_header) {\n\t\t//timing_info_present_flag = GF_FALSE;\n\t\t//initial_display_delay_present_flag = GF_FALSE;\n\t\tstate->operating_points_count = 1;\n\t\tstate->config->seq_level_idx_0 = gf_bs_read_int_log(bs, 5, \"seq_level_idx_0\");\n\t}\n\telse {\n\t\tu8 i = 0;\n\t\tBool initial_display_delay_present_flag;\n\t\tBool timing_info_present_flag = gf_bs_read_int_log(bs, 1, \"timing_info_present_flag\");\n\t\tif (timing_info_present_flag) {\n\t\t\ttiming_info(bs, state);\n\t\t\tstate->decoder_model_info_present_flag = gf_bs_read_int_log(bs, 1, \"decoder_model_info_present_flag\");\n\t\t\tif (state->decoder_model_info_present_flag) {\n\t\t\t\tdecoder_model_info(state, bs);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tstate->decoder_model_info_present_flag = GF_FALSE;\n\t\t}\n\t\tinitial_display_delay_present_flag = gf_bs_read_int_log(bs, 1, \"initial_display_delay_present_flag\");\n\t\tstate->operating_points_count = 1 + gf_bs_read_int_log(bs, 5, \"operating_points_count_minus1\");\n\t\tfor (i = 0; i < state->operating_points_count; i++) {\n\t\t\tu8 seq_level_idx_i, seq_tier = 0;",
"\t\t\tstate->operating_point_idc[i] = gf_bs_read_int_log_idx(bs, 12, \"operating_point_idc\", i);",
"\t\t\tseq_level_idx_i = gf_bs_read_int_log_idx(bs, 5, \"seq_level_idx\", i);\n\t\t\tif (i == 0) state->config->seq_level_idx_0 = seq_level_idx_i;",
"\t\t\tif (seq_level_idx_i > 7) {\n\t\t\t\tseq_tier = gf_bs_read_int_log_idx(bs, 1, \"seq_tier\", i);\n\t\t\t}\n\t\t\tif (i == 0) state->config->seq_tier_0 = seq_tier;",
"\t\t\tif (state->decoder_model_info_present_flag) {\n\t\t\t\tstate->decoder_model_present_for_this_op[i] = gf_bs_read_int_log_idx(bs, 1, \"decoder_model_present_for_this_op\", i);\n\t\t\t\tif (state->decoder_model_present_for_this_op[i]) {\n\t\t\t\t\toperating_parameters_info(bs, i, buffer_delay_length_minus_1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate->decoder_model_present_for_this_op[i] = 0;\n\t\t\t}\n\t\t\tif (initial_display_delay_present_flag) {\n\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"initial_display_delay_present_for_this_op\", i) ) {\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 4, \"initial_display_delay_minus1\", i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\t//operatingPoint = av1_choose_operating_point(bs);\n\tstate->OperatingPointIdc = 0;//TODO: operating_point_idc[operatingPoint];",
"\tstate->frame_width_bits_minus_1 = gf_bs_read_int_log(bs, 4, \"frame_width_bits_minus1\");\n\tstate->frame_height_bits_minus_1 = gf_bs_read_int_log(bs, 4, \"frame_height_bits_minus1\");\n\tstate->width = gf_bs_read_int_log(bs, state->frame_width_bits_minus_1 + 1, \"width_minus1\") + 1;\n\tstate->height = gf_bs_read_int_log(bs, state->frame_height_bits_minus_1 + 1, \"height_minus1\") + 1;\n\tstate->sequence_width = state->width;\n\tstate->sequence_height = state->height;\n\tstate->frame_id_numbers_present_flag = GF_FALSE;\n\tif (!state->reduced_still_picture_header) {\n\t\tstate->frame_id_numbers_present_flag = gf_bs_read_int_log(bs, 1, \"frame_id_numbers_present_flag\");\n\t}\n\tif (state->frame_id_numbers_present_flag) {\n\t\tstate->delta_frame_id_length_minus_2 = gf_bs_read_int_log(bs, 4, \"delta_frame_id_length_minus2\");\n\t\tstate->additional_frame_id_length_minus_1 = gf_bs_read_int_log(bs, 3, \"additional_frame_id_length_minus1\");\n\t}\n\tstate->use_128x128_superblock = gf_bs_read_int_log(bs, 1, \"use_128x128_superblock\");\n\tgf_bs_read_int_log(bs, 1, \"enable_filter_intra\");\n\tgf_bs_read_int_log(bs, 1, \"enable_intra_edge_filter\");\n\tif (state->reduced_still_picture_header) {\n\t\t/*enable_interintra_compound = 0;\n\t\tenable_masked_compound = 0;\n\t\tenable_dual_filter = 0;\n\t\tenable_jnt_comp = 0;\n\t\tenable_ref_frame_mvs = 0;*/\n\t\tstate->enable_warped_motion = 0;\n\t\tstate->enable_order_hint = GF_FALSE;\n\t\tstate->OrderHintBits = 0;\n\t\tstate->seq_force_integer_mv = 2/*SELECT_INTEGER_MV*/;\n\t\tstate->seq_force_screen_content_tools = 2/*SELECT_SCREEN_CONTENT_TOOLS*/;\n\t}\n\telse {\n\t\tBool seq_choose_screen_content_tools;\n\t\tgf_bs_read_int_log(bs, 1, \"enable_interintra_compound\");\n\t\tgf_bs_read_int_log(bs, 1, \"enable_masked_compound\");\n\t\tstate->enable_warped_motion = gf_bs_read_int_log(bs, 1, \"enable_warped_motion\");\n\t\tgf_bs_read_int_log(bs, 1, \"enable_dual_filter\");\n\t\tstate->enable_order_hint = gf_bs_read_int_log(bs, 1, \"enable_order_hint\");\n\t\tif (state->enable_order_hint) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"enable_jnt_comp\");\n\t\t\tstate->enable_ref_frame_mvs = gf_bs_read_int_log(bs, 1, \"enable_ref_frame_mvs\");\n\t\t}\n\t\telse {\n\t\t\t/*enable_jnt_comp = 0*/;\n\t\t\t/*enable_ref_frame_mvs = 0*/;\n\t\t}\n\t\tseq_choose_screen_content_tools = gf_bs_read_int_log(bs, 1, \"seq_choose_screen_content_tools\");\n\t\tstate->seq_force_screen_content_tools = 0;\n\t\tif (seq_choose_screen_content_tools) {\n\t\t\tstate->seq_force_screen_content_tools = 2/*SELECT_SCREEN_CONTENT_TOOLS*/;\n\t\t}\n\t\telse {\n\t\t\tstate->seq_force_screen_content_tools = gf_bs_read_int_log(bs, 1, \"seq_force_screen_content_tools\");\n\t\t}",
"\t\tstate->seq_force_integer_mv = 0;\n\t\tif (state->seq_force_screen_content_tools > 0) {\n\t\t\tconst Bool seq_choose_integer_mv = gf_bs_read_int_log(bs, 1, \"seq_choose_integer_mv\");\n\t\t\tif (seq_choose_integer_mv) {\n\t\t\t\tstate->seq_force_integer_mv = 2/*SELECT_INTEGER_MV*/;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate->seq_force_integer_mv = gf_bs_read_int_log(bs, 1, \"seq_force_integer_mv\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tstate->seq_force_integer_mv = 2/*SELECT_INTEGER_MV*/;\n\t\t}\n\t\tif (state->enable_order_hint) {\n\t\t\tu8 order_hint_bits_minus_1 = gf_bs_read_int_log(bs, 3, \"order_hint_bits_minus1\");\n\t\t\tstate->OrderHintBits = order_hint_bits_minus_1 + 1;\n\t\t}\n\t\telse {\n\t\t\tstate->OrderHintBits = 0;\n\t\t}\n\t}",
"\tstate->enable_superres = gf_bs_read_int_log(bs, 1, \"enable_superres\");\n\tstate->enable_cdef = gf_bs_read_int_log(bs, 1, \"enable_cdef\");\n\tstate->enable_restoration = gf_bs_read_int_log(bs, 1, \"enable_restoration\");\n\tav1_color_config(bs, state);\n\tstate->film_grain_params_present = gf_bs_read_int_log(bs, 1, \"film_grain_params_present\");\n}",
"",
"#define IVF_FILE_HEADER_SIZE 32",
"Bool gf_media_probe_ivf(GF_BitStream *bs)\n{\n\tu32 dw = 0;\n\tif (gf_bs_available(bs) < IVF_FILE_HEADER_SIZE) return GF_FALSE;",
"\tdw = gf_bs_peek_bits(bs, 32, 0);\n\tif (dw != GF_4CC('D', 'K', 'I', 'F')) {\n\t\treturn GF_FALSE;\n\t}\n\treturn GF_TRUE;\n}",
"GF_Err gf_media_parse_ivf_file_header(GF_BitStream *bs, u32 *width, u32 *height, u32 *codec_fourcc, u32 *timebase_num, u32 *timebase_den, u32 *num_frames)\n{\n\tu32 dw = 0;",
"\tif (!width || !height || !codec_fourcc || !timebase_den || !timebase_num || !num_frames) {\n\t\tassert(0);\n\t\treturn GF_BAD_PARAM;\n\t}",
"\tif (gf_bs_available(bs) < IVF_FILE_HEADER_SIZE) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[IVF] Not enough bytes available (\"LLU\").\\n\", gf_bs_available(bs)));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\tdw = gf_bs_read_u32(bs);\n\tif (dw != GF_4CC('D', 'K', 'I', 'F')) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CODING, (\"[IVF] Invalid signature\\n\"));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\tdw = gf_bs_read_u16_le(bs);\n\tif (dw != 0) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[IVF] Wrong IVF version. 0 expected, got %u\\n\", dw));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\tdw = gf_bs_read_u16_le(bs); //length of header in bytes\n\tif (dw != IVF_FILE_HEADER_SIZE) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[IVF] Wrong IVF header length. Expected 32 bytes, got %u\\n\", dw));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\t*codec_fourcc = gf_bs_read_u32(bs);",
"\t*width = gf_bs_read_u16_le(bs);\n\t*height = gf_bs_read_u16_le(bs);",
"\t*timebase_num = gf_bs_read_u32_le(bs);\n\t*timebase_den = gf_bs_read_u32_le(bs);",
"\t*num_frames = gf_bs_read_u32_le(bs);\n\tgf_bs_read_u32_le(bs); //skip unused",
"\treturn GF_OK;\n}",
"GF_Err gf_media_parse_ivf_frame_header(GF_BitStream *bs, u64 *frame_size, u64 *pts)\n{\n\tif (!frame_size) return GF_BAD_PARAM;\n\tif (gf_bs_available(bs) < 12)\n\t\treturn GF_BUFFER_TOO_SMALL;",
"\t*frame_size = gf_bs_read_u32_le(bs);\n\tif (*frame_size > 256 * 1024 * 1024) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[IVF] Wrong frame size %u\\n\", *frame_size));\n\t\t*frame_size = 0;\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\t*pts = gf_bs_read_u64_le(bs);",
"\treturn GF_OK;\n}",
"GF_Err gf_media_vp9_parse_superframe(GF_BitStream *bs, u64 ivf_frame_size, u32 *num_frames_in_superframe, u32 frame_sizes[VP9_MAX_FRAMES_IN_SUPERFRAME], u32 *superframe_index_size)\n{\n\tu32 byte, bytes_per_framesize;\n\tu64 pos = gf_bs_get_position(bs), i = 0;\n\tGF_Err e;",
"\tassert(bs && num_frames_in_superframe);",
"\t/*initialize like there is no superframe*/\n\tmemset(frame_sizes, 0, VP9_MAX_FRAMES_IN_SUPERFRAME * sizeof(frame_sizes[0]));\n\t*num_frames_in_superframe = 1;\n\tframe_sizes[0] = (u32)ivf_frame_size;\n\t*superframe_index_size = 0;",
"\te = gf_bs_seek(bs, pos + ivf_frame_size - 1);\n\tif (e) return e;",
"\tbyte = gf_bs_read_u8(bs);\n\tif ((byte & 0xe0) != 0xc0)\n\t\tgoto exit; /*no superframe*/",
"\tbytes_per_framesize = 1 + ((byte & 0x18) >> 3);\n\t*num_frames_in_superframe = (u32)(1 + (byte & 0x7));",
"\t/*superframe_index()*/\n\t*superframe_index_size = 2 + bytes_per_framesize * *num_frames_in_superframe;\n\tgf_bs_seek(bs, pos + ivf_frame_size - *superframe_index_size);\n\tbyte = gf_bs_read_u8(bs);\n\tif ((byte & 0xe0) != 0xc0)\n\t\tgoto exit; /*no superframe*/",
"\tframe_sizes[0] = 0;\n\tfor (i = 0; i < *num_frames_in_superframe; ++i) {\n\t\tgf_bs_read_data(bs, (char*)(frame_sizes + i), bytes_per_framesize);\n\t}",
"exit:\n\tgf_bs_seek(bs, pos);\n\treturn e;\n}",
"\nstatic Bool vp9_frame_sync_code(GF_BitStream *bs)\n{\n\tu8 val = gf_bs_read_int_log(bs, 8, \"syncbyte1\");\n\tif (val != 0x49)\n\t\treturn GF_FALSE;",
"\tval = gf_bs_read_int_log(bs, 8, \"syncbyte2\");\n\tif (val != 0x83)\n\t\treturn GF_FALSE;",
"\tval = gf_bs_read_int_log(bs, 8, \"syncbyte3\");\n\tif (val != 0x42)\n\t\treturn GF_FALSE;",
"\treturn GF_TRUE;\n}",
"typedef enum {\n\tCS_UNKNOWN = 0,\n\tCS_BT_601 = 1,\n\tCS_BT_709 = 2,\n\tCS_SMPTE_170 = 3,\n\tCS_SMPTE_240 = 4,\n\tCS_BT_2020 = 5,\n\tCS_RESERVED = 6,\n\tCS_RGB = 7,\n} VP9_color_space;",
"static const int VP9_CS_to_23001_8_colour_primaries[] = { -1/*undefined*/, 5, 1, 6, 7, 9, -1/*reserved*/, 1 };\nstatic const int VP9_CS_to_23001_8_transfer_characteristics[] = { -1/*undefined*/, 5, 1, 6, 7, 9, -1/*reserved*/, 13 };\nstatic const int VP9_CS_to_23001_8_matrix_coefficients[] = { -1/*undefined*/, 6, 1, -1, -1, 9, -1/*reserved*/, 0 };",
"static GF_Err vp9_color_config(GF_BitStream *bs, GF_VPConfig *vp9_cfg)\n{\n\tVP9_color_space color_space;",
"\tif (vp9_cfg->profile >= 2) {\n\t\tBool ten_or_twelve_bit = gf_bs_read_int_log(bs, 1, \"ten_or_twelve_bit\");\n\t\tvp9_cfg->bit_depth = ten_or_twelve_bit ? 12 : 10;\n\t}\n\telse {\n\t\tvp9_cfg->bit_depth = 8;\n\t}",
"\tcolor_space = gf_bs_read_int_log(bs, 3, \"color_space\");\n\tvp9_cfg->colour_primaries = VP9_CS_to_23001_8_colour_primaries[color_space];\n\tvp9_cfg->transfer_characteristics = VP9_CS_to_23001_8_transfer_characteristics[color_space];\n\tvp9_cfg->matrix_coefficients = VP9_CS_to_23001_8_matrix_coefficients[color_space];\n\tif (color_space != CS_RGB) {\n\t\tvp9_cfg->video_fullRange_flag = gf_bs_read_int_log(bs, 1, \"video_fullRange_flag\");\n\t\tif (vp9_cfg->profile == 1 || vp9_cfg->profile == 3) {\n\t\t\tu8 subsampling_x, subsampling_y, subsampling_xy_to_chroma_subsampling[2][2] = { {3, 0}, {2, 0} };\n\t\t\tsubsampling_x = gf_bs_read_int_log(bs, 1, \"subsampling_x\");\n\t\t\tsubsampling_y = gf_bs_read_int_log(bs, 1, \"subsampling_x\");\n\t\t\tvp9_cfg->chroma_subsampling = subsampling_xy_to_chroma_subsampling[subsampling_x][subsampling_y];\n\t\t\tBool reserved_zero = gf_bs_read_int_log(bs, 1, \"reserved_zero\");\n\t\t\tif (reserved_zero) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VP9] color config reserved zero (1) is not zero.\\n\"));\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tvp9_cfg->chroma_subsampling = 0;\n\t\t}\n\t}\n\telse {\n\t\tvp9_cfg->video_fullRange_flag = GF_TRUE;\n\t\tif (vp9_cfg->profile == 1 || vp9_cfg->profile == 3) {\n\t\t\tvp9_cfg->chroma_subsampling = 3;\n\t\t\tBool reserved_zero = gf_bs_read_int_log(bs, 1, \"reserved_zero\");\n\t\t\tif (reserved_zero) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VP9] color config reserved zero (2) is not zero.\\n\"));\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t}\n\t}",
"\treturn GF_OK;\n}",
"static void vp9_compute_image_size(int FrameWidth, int FrameHeight, int *Sb64Cols, int *Sb64Rows)\n{\n\tint MiCols = (FrameWidth + 7) >> 3;\n\tint MiRows = (FrameHeight + 7) >> 3;\n\t*Sb64Cols = (MiCols + 7) >> 3;\n\t*Sb64Rows = (MiRows + 7) >> 3;\n}",
"static void vp9_frame_size(GF_BitStream *bs, int *FrameWidth, int *FrameHeight, int *Sb64Cols, int *Sb64Rows)\n{\n\tint frame_width_minus_1 = gf_bs_read_int_log(bs, 16, \"frame_width_minus_1\");\n\tint frame_height_minus_1 = gf_bs_read_int_log(bs, 16, \"frame_height_minus_1\");\n\tif (frame_width_minus_1 + 1 != *FrameWidth || frame_height_minus_1 + 1 != *FrameHeight) {\n\t\tif (*FrameWidth || *FrameHeight)\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[VP9] inconsistent frame dimensions: previous was %dx%d, new one is %dx%d.\\n\", *FrameWidth, *FrameHeight, frame_width_minus_1 + 1, frame_height_minus_1 + 1));\n\t}\n\t*FrameWidth = frame_width_minus_1 + 1;\n\t*FrameHeight = frame_height_minus_1 + 1;\n\tvp9_compute_image_size(*FrameWidth, *FrameHeight, Sb64Cols, Sb64Rows);\n}",
"static void vp9_render_size(GF_BitStream *bs, int FrameWidth, int FrameHeight, int *renderWidth, int *renderHeight)\n{\n\tBool render_and_frame_size_different = gf_bs_read_int_log(bs, 1, \"render_and_frame_size_different\");\n\tif (render_and_frame_size_different == 1) {\n\t\tint render_width_minus_1 = gf_bs_read_int_log(bs, 16, \"render_width_minus_1\");\n\t\tint render_height_minus_1 = gf_bs_read_int_log(bs, 16, \"render_height_minus_1\");\n\t\t*renderWidth = render_width_minus_1 + 1;\n\t\t*renderHeight = render_height_minus_1 + 1;\n\t}\n\telse {\n\t\t*renderWidth = FrameWidth;\n\t\t*renderHeight = FrameHeight;\n\t}\n}",
"static s64 vp9_s(GF_BitStream *bs, int n, const char *fname, u32 idx) {\n\ts64 value = gf_bs_read_int(bs, n);\n\tBool sign = gf_bs_read_int(bs, 1);\n\tif (sign) value = -value;\n\tgf_bs_log_idx(bs, n+1, fname, value, idx, -1, -1);\n\treturn value;\n}",
"static void vp9_loop_filter_params(GF_BitStream *bs)\n{\n\t/*loop_filter_level = */gf_bs_read_int_log(bs, 6, \"loop_filter_level\");\n\t/*loop_filter_sharpness = */gf_bs_read_int_log(bs, 3, \"loop_filter_sharpness\");\n\tBool loop_filter_delta_enabled = gf_bs_read_int_log(bs, 1, \"loop_filter_delta_enabled\");\n\tif (loop_filter_delta_enabled == 1) {\n\t\tBool loop_filter_delta_update = gf_bs_read_int_log(bs, 1, \"loop_filter_delta_update\");\n\t\tif (loop_filter_delta_update == GF_TRUE) {\n\t\t\tint i;\n\t\t\tfor (i = 0; i < 4; i++) {\n\t\t\t\tBool update_ref_delta = gf_bs_read_int_log_idx(bs, 1, \"update_ref_delta\", i);\n\t\t\t\tif (update_ref_delta == GF_TRUE)\n\t\t\t\t\tvp9_s(bs, 6, \"loop_filter_ref_deltas\", i);\n\t\t\t}\n\t\t\tfor (i = 0; i < 2; i++) {\n\t\t\t\tBool update_mode_delta = gf_bs_read_int_log_idx(bs, 1, \"update_mode_delta\", i);\n\t\t\t\tif (update_mode_delta == GF_TRUE)\n\t\t\t\t\tvp9_s(bs, 6, \"loop_filter_mode_deltas\", i);\n\t\t\t}\n\t\t}\n\t}\n}",
"static void vp9_quantization_params(GF_BitStream *bs)\n{\n\t/*base_q_idx = */gf_bs_read_int_log(bs, 8, \"base_q_idx\");\n}",
"#define VP9_MAX_SEGMENTS 8\n#define VP9_SEG_LVL_MAX 4\nstatic const int segmentation_feature_bits[VP9_SEG_LVL_MAX] = { 8, 6, 2, 0 };\nstatic const int segmentation_feature_signed[VP9_SEG_LVL_MAX] = { 1, 1, 0, 0 };",
"#define VP9_MIN_TILE_WIDTH_B64 4\n#define VP9_MAX_TILE_WIDTH_B64 64",
"static void vp9_segmentation_params(GF_BitStream *bs)\n{\n\tBool segmentation_enabled = gf_bs_read_int_log(bs, 1, \"segmentation_enabled\");\n\tif (segmentation_enabled == 1) {\n\t\tint i;\n\t\tBool segmentation_update_map = gf_bs_read_int_log(bs, 1, \"segmentation_update_map\");\n\t\tif (segmentation_update_map) {\n\t\t\tfor (i = 0; i < 7; i++)\n\t\t\t\t/*segmentation_tree_probs[i] = read_prob()*/\n\t\t\t\t/*segmentation_temporal_update = */gf_bs_read_int_log(bs, 1, \"segmentation_temporal_update\");\n\t\t\t/*for (i = 0; i < 3; i++)\n\t\t\t\tsegmentation_pred_prob[i] = segmentation_temporal_update ? read_prob() : 255*/\n\t\t}\n\t\tBool segmentation_update_data = gf_bs_read_int_log(bs, 1, \"segmentation_update_data\");\n\t\tif (segmentation_update_data == 1) {\n\t\t\t/*segmentation_abs_or_delta_update =*/ gf_bs_read_int_log(bs, 1, \"segmentation_abs_or_delta_update\");\n\t\t\tfor (i = 0; i < VP9_MAX_SEGMENTS; i++) {\n\t\t\t\tint j;\n\t\t\t\tfor (j = 0; j < VP9_SEG_LVL_MAX; j++) {\n\t\t\t\t\t/*feature_value = 0*/\n\t\t\t\t\tBool feature_enabled = gf_bs_read_int_log(bs, 1, \"feature_enabled\");\n\t\t\t\t\t/*FeatureEnabled[i][j] = feature_enabled*/\n\t\t\t\t\tif (feature_enabled) {\n\t\t\t\t\t\tint bits_to_read = segmentation_feature_bits[j];\n\t\t\t\t\t\t/*feature_value =*/ gf_bs_read_int_log(bs, bits_to_read, \"feature_value\");\n\t\t\t\t\t\tif (segmentation_feature_signed[j] == 1) {\n\t\t\t\t\t\t\t/*Bool feature_sign = */gf_bs_read_int_log(bs, 1, \"feature_sign\");\n\t\t\t\t\t\t\t/*if (feature_sign == 1)\n\t\t\t\t\t\t\t\tfeature_value *= -1*/\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t/*FeatureData[i][j] = feature_value*/\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"static int calc_min_log2_tile_cols(int Sb64Cols) {\n\tint minLog2 = 0;\n\twhile ((VP9_MAX_TILE_WIDTH_B64 << minLog2) < Sb64Cols)\n\t\tminLog2++;",
"\treturn minLog2;\n}",
"static int calc_max_log2_tile_cols(int Sb64Cols) {\n\tint maxLog2 = 1;\n\twhile ((Sb64Cols >> maxLog2) >= VP9_MIN_TILE_WIDTH_B64)\n\t\tmaxLog2++;",
"\treturn maxLog2 - 1;\n}",
"static void vp9_tile_info(GF_BitStream *bs, int Sb64Cols)\n{\n\tBool tile_rows_log2;\n\tint minLog2TileCols = calc_min_log2_tile_cols(Sb64Cols);\n\tint maxLog2TileCols = calc_max_log2_tile_cols(Sb64Cols);\n\tint tile_cols_log2 = minLog2TileCols;\n\twhile (tile_cols_log2 < maxLog2TileCols) {\n\t\tBool increment_tile_cols_log2 = gf_bs_read_int_log(bs, 1, \"increment_tile_cols_log2\");\n\t\tif (increment_tile_cols_log2)\n\t\t\ttile_cols_log2++;\n\t\telse\n\t\t\tbreak;\n\t}\n\ttile_rows_log2 = gf_bs_read_int_log(bs, 1, \"tile_rows_log2\");\n\tif (tile_rows_log2) {\n\t\t/*Bool increment_tile_rows_log2 = */gf_bs_read_int_log(bs, 1, \"increment_tile_rows_log2\");\n\t\t//tile_rows_log2 += increment_tile_rows_log2;\n\t}\n}",
"static void vp9_frame_size_with_refs(GF_BitStream *bs, u8 refresh_frame_flags, u8 * ref_frame_idx, int * RefFrameWidth, int *RefFrameHeight,\n\tint *FrameWidth, int *FrameHeight, int *RenderWidth, int *RenderHeight, int *Sb64Cols, int *Sb64Rows)\n{\n\tBool found_ref;\n\tint i;\n\tfor (i = 0; i < 3; i++) {\n\t\tfound_ref = gf_bs_read_int_log(bs, 1, \"found_ref\");\n\t\tif (found_ref) {\n\t\t\t*FrameWidth = RefFrameWidth [ref_frame_idx[i]];\n\t\t\t*FrameHeight = RefFrameHeight[ref_frame_idx[i]];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (found_ref == 0) {\n\t\tvp9_frame_size(bs, FrameWidth, FrameHeight, Sb64Cols, Sb64Rows);\n\t}\n\telse {\n\t\tvp9_compute_image_size(*FrameWidth, *FrameHeight, Sb64Cols, Sb64Rows);\n\t}",
"\tvp9_render_size(bs, *FrameWidth, *FrameHeight, RenderWidth, RenderHeight);\n}",
"static void vp9_read_interpolation_filter(GF_BitStream *bs)\n{\n\tBool is_filter_switchable = gf_bs_read_int_log(bs, 1, \"is_filter_switchable\");\n\tif (!is_filter_switchable) {\n\t\t/*raw_interpolation_filter = */gf_bs_read_int_log(bs, 2, \"raw_interpolation_filter\");\n\t}\n}",
"\n#define VP9_KEY_FRAME 0",
"GF_Err gf_media_vp9_parse_sample(GF_BitStream *bs, GF_VPConfig *vp9_cfg, Bool *key_frame, u32 *FrameWidth, u32 *FrameHeight, u32 *renderWidth, u32 *renderHeight)\n{\n\tBool FrameIsIntra = GF_FALSE, profile_low_bit, profile_high_bit, show_existing_frame = GF_FALSE, frame_type = GF_FALSE, show_frame = GF_FALSE, error_resilient_mode = GF_FALSE;\n\t/*u8 frame_context_idx = 0, reset_frame_context = 0, frame_marker = 0*/;\n\tint Sb64Cols = 0, Sb64Rows = 0, i;\n\tu8 refresh_frame_flags = 0;",
"\tassert(bs && key_frame);",
"\t/*uncompressed header*/\n\t/*frame_marker = */gf_bs_read_int_log(bs, 2, \"frame_marker\");\n\tprofile_low_bit = gf_bs_read_int_log(bs, 1, \"profile_low_bit\");\n\tprofile_high_bit = gf_bs_read_int_log(bs, 1, \"profile_high_bit\");\n\tvp9_cfg->profile = (profile_high_bit << 1) + profile_low_bit;\n\tif (vp9_cfg->profile == 3) {\n\t\tBool reserved_zero = gf_bs_read_int_log(bs, 1, \"reserved_zero\");\n\t\tif (reserved_zero) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VP9] uncompressed header reserved zero is not zero.\\n\"));\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t}",
"\tshow_existing_frame = gf_bs_read_int_log(bs, 1, \"show_existing_frame\");\n\tif (show_existing_frame == GF_TRUE) {\n\t\t/*frame_to_show_map_idx = */gf_bs_read_int_log(bs, 3, \"frame_to_show_map_idx\");\n\t\treturn GF_OK;\n\t}",
"\tframe_type = gf_bs_read_int_log(bs, 1, \"frame_type\");\n\tshow_frame = gf_bs_read_int_log(bs, 1, \"show_frame\");\n\terror_resilient_mode = gf_bs_read_int_log(bs, 1, \"error_resilient_mode\");\n\tif (frame_type == VP9_KEY_FRAME) {\n\t\tif (!vp9_frame_sync_code(bs))\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\tif (vp9_color_config(bs, vp9_cfg) != GF_OK)\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\tvp9_frame_size(bs, FrameWidth, FrameHeight, &Sb64Cols, &Sb64Rows);\n\t\tvp9_render_size(bs, *FrameWidth, *FrameHeight, renderWidth, renderHeight);\n\t\trefresh_frame_flags = 0xFF;\n\t\t*key_frame = GF_TRUE;\n\t\tFrameIsIntra = GF_TRUE;\n\t}\n\telse {\n\t\tBool intra_only = GF_FALSE;\n\t\t*key_frame = GF_FALSE;",
"\t\tif (show_frame == GF_FALSE) {\n\t\t\tintra_only = gf_bs_read_int_log(bs, 1, \"intra_only\");\n\t\t}\n\t\tFrameIsIntra = intra_only;",
"\t\tif (error_resilient_mode == GF_FALSE) {\n\t\t\t/*reset_frame_context = */gf_bs_read_int_log(bs, 2, \"reset_frame_context\");\n\t\t}",
"\t\tif (intra_only == GF_TRUE) {\n\t\t\tif (!vp9_frame_sync_code(bs))\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;",
"\t\t\tif (vp9_cfg->profile > 0) {\n\t\t\t\tif (vp9_color_config(bs, vp9_cfg) != GF_OK)\n\t\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tu8 color_space = CS_BT_601;\n\t\t\t\tvp9_cfg->colour_primaries = VP9_CS_to_23001_8_colour_primaries[color_space];\n\t\t\t\tvp9_cfg->transfer_characteristics = VP9_CS_to_23001_8_transfer_characteristics[color_space];\n\t\t\t\tvp9_cfg->matrix_coefficients = VP9_CS_to_23001_8_matrix_coefficients[color_space];\n\t\t\t\tvp9_cfg->chroma_subsampling = 0;\n\t\t\t\tvp9_cfg->bit_depth = 8;\n\t\t\t}\n\t\t\trefresh_frame_flags = gf_bs_read_int_log(bs, 8, \"refresh_frame_flags\");\n\t\t\tvp9_frame_size(bs, FrameWidth, FrameHeight, &Sb64Cols, &Sb64Rows);\n\t\t\tvp9_render_size(bs, *FrameWidth, *FrameHeight, renderWidth, renderHeight);\n\t\t}\n\t\telse {\n\t\t\trefresh_frame_flags = gf_bs_read_int_log(bs, 8, \"refresh_frame_flags\");\n\t\t\tu8 ref_frame_idx[3];\n\t\t\tfor (i = 0; i < 3; i++) {\n\t\t\t\tref_frame_idx[i] = gf_bs_read_int_log_idx(bs, 3, \"ref_frame_idx\", i);\n\t\t\t\t/*ref_frame_sign_bias[LAST_FRAME + i] = */gf_bs_read_int_log_idx(bs, 1, \"ref_frame_sign_bias\", i);\n\t\t\t}\n\t\t\tvp9_frame_size_with_refs(bs, refresh_frame_flags, ref_frame_idx, vp9_cfg->RefFrameWidth, vp9_cfg->RefFrameHeight, FrameWidth, FrameHeight, renderWidth, renderHeight, &Sb64Cols, &Sb64Rows);\n\t\t\t/*allow_high_precision_mv = */gf_bs_read_int_log(bs, 1, \"allow_high_precision_mv\");\n\t\t\tvp9_read_interpolation_filter(bs);\n\t\t}\n\t}",
"\tif (error_resilient_mode == 0) {\n\t\t/*refresh_frame_context = */gf_bs_read_int_log(bs, 1, \"refresh_frame_context\");\n\t\t/*frame_parallel_decoding_mode = */gf_bs_read_int_log(bs, 1, \"frame_parallel_decoding_mode\");\n\t}",
"\t/*frame_context_idx = */gf_bs_read_int_log(bs, 2, \"frame_context_idx\");\n\tif (FrameIsIntra || error_resilient_mode) {\n\t\t/*setup_past_independence + save_probs ...*/\n\t\t//frame_context_idx = 0;\n\t}",
"\tvp9_loop_filter_params(bs);\n\tvp9_quantization_params(bs);\n\tvp9_segmentation_params(bs);\n\tvp9_tile_info(bs, Sb64Cols);",
"\t/*header_size_in_bytes = */gf_bs_read_int_log(bs, 16, \"header_size_in_bytes\");",
"\t/*Reference frame update process (8.10 - partial)*/\n\tfor (i = 0; i < VP9_NUM_REF_FRAMES; i++) {\n\t\tif ((refresh_frame_flags >> i) & 1) {\n\t\t\tvp9_cfg->RefFrameWidth[i] = *FrameWidth;\n\t\t\tvp9_cfg->RefFrameHeight[i] = *FrameHeight;\n\t\t}\n\t}",
"\treturn GF_OK;\n}",
"GF_Err gf_av1_parse_obu_header(GF_BitStream *bs, ObuType *obu_type, Bool *obu_extension_flag, Bool *obu_has_size_field, u8 *temporal_id, u8 *spatial_id)\n{\n\tBool forbidden = gf_bs_read_int(bs, 1);\n\tif (forbidden) {\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\t*obu_type = gf_bs_read_int(bs, 4);\n\t*obu_extension_flag = gf_bs_read_int(bs, 1);\n\t*obu_has_size_field = gf_bs_read_int(bs, 1);\n\tif (gf_bs_read_int(bs, 1) /*obu_reserved_1bit*/) {\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\tif (*obu_extension_flag) {\n\t\t*temporal_id = gf_bs_read_int(bs, 3);\n\t\t*spatial_id = gf_bs_read_int(bs, 2);\n\t\t/*extension_header_reserved_3bits = */gf_bs_read_int(bs, 3);\n\t}",
"\treturn GF_OK;\n}",
"#endif // GPAC_DISABLE_AV_PARSERS",
"GF_EXPORT\nconst char *gf_av1_get_obu_name(ObuType obu_type)\n{\n\tswitch (obu_type) {\n\tcase OBU_SEQUENCE_HEADER: return \"seq_header\";\n\tcase OBU_TEMPORAL_DELIMITER: return \"delimiter\";\n\tcase OBU_FRAME_HEADER: return \"frame_header\";\n\tcase OBU_TILE_GROUP: return \"tile_group\";\n\tcase OBU_METADATA: return \"metadata\";\n\tcase OBU_FRAME: return \"frame\";\n\tcase OBU_REDUNDANT_FRAME_HEADER: return \"redundant_frame_header\";\n\tcase OBU_TILE_LIST: return \"tile_list\";\n\tcase OBU_PADDING: return \"padding\";\n\tcase OBU_RESERVED_0:\n\tcase OBU_RESERVED_9:\n\tcase OBU_RESERVED_10:\n\tcase OBU_RESERVED_11:\n\tcase OBU_RESERVED_12:\n\tcase OBU_RESERVED_13:\n\tcase OBU_RESERVED_14:\n\t\treturn \"reserved\";\n\tdefault: return \"unknown\";\n\t}\n}",
"Bool av1_is_obu_header(ObuType obu_type) {\n\tswitch (obu_type) {\n\tcase OBU_SEQUENCE_HEADER:\n\tcase OBU_METADATA:\n\t\t// TODO add check based on the metadata type\n\t\treturn GF_TRUE;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n}",
"#ifndef GPAC_DISABLE_AV_PARSERS",
"static Bool av1_is_obu_frame(AV1State *state, ObuType obu_type)\n{\n\tswitch (obu_type) {\n\tcase OBU_PADDING:\n\tcase OBU_REDUNDANT_FRAME_HEADER:\n\t\treturn GF_FALSE;\n\tcase OBU_TEMPORAL_DELIMITER:\n\t\treturn state->keep_temporal_delim ? GF_TRUE : GF_FALSE;\n\tdefault:\n\t\treturn GF_TRUE;\n\t}\n}",
"u64 gf_av1_leb128_read(GF_BitStream *bs, u8 *opt_Leb128Bytes) {\n\tu64 value = 0;\n\tu8 Leb128Bytes = 0, i = 0;\n\tfor (i = 0; i < 8; i++) {\n\t\tu8 leb128_byte = gf_bs_read_u8(bs);\n\t\tvalue |= ( ((u64) (leb128_byte & 0x7f)) << (i * 7));\n\t\tLeb128Bytes += 1;\n\t\tif (!(leb128_byte & 0x80)) {\n\t\t\tbreak;\n\t\t}\n\t}",
"\tif (opt_Leb128Bytes) {\n\t\t*opt_Leb128Bytes = Leb128Bytes;\n\t}\n\treturn value;\n}",
"u32 gf_av1_leb128_size(u64 value)\n{\n\tu32 gf_av1_leb128_size = 0;\n\tdo {\n\t\t++gf_av1_leb128_size;\n\t} while ((value >>= 7) != 0);",
"\treturn gf_av1_leb128_size;\n}",
"u64 gf_av1_leb128_write(GF_BitStream *bs, u64 value)\n{\n\tu32 i, leb_size = gf_av1_leb128_size(value);\n\tfor (i = 0; i < leb_size; ++i) {\n\t\tu8 byte = value & 0x7f;\n\t\tvalue >>= 7;\n\t\tif (value != 0) byte |= 0x80; //more bytes follow\n\t\tgf_bs_write_u8(bs, byte);\n\t}",
"\treturn leb_size;\n}",
"#define OBU_BLOCK_SIZE 4096\nstatic void av1_add_obu_internal(GF_BitStream *bs, u64 pos, u64 obu_length, ObuType obu_type, GF_List **obu_list, AV1State *state)\n{\n\tchar block[OBU_BLOCK_SIZE];\n\tBool has_size_field = 0, obu_extension_flag = 0;\n\tu8 temporal_id, spatial_id;\n\tGF_AV1_OBUArrayEntry *a = NULL;",
"\tif (state && state->mem_mode) {\n\t\tif (!state->bs) state->bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\t\telse gf_bs_reassign_buffer(state->bs, state->frame_obus, state->frame_obus_alloc);\n\t}\n\telse {\n\t\tGF_SAFEALLOC(a, GF_AV1_OBUArrayEntry);\n\t\tif (!a) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[AV1] Failed to allocate OBU\\n\"));\n\t\t\treturn;\n\t\t}\n\t}",
"\tgf_bs_seek(bs, pos);\n\tgf_av1_parse_obu_header(bs, &obu_type, &obu_extension_flag, &has_size_field, &temporal_id, &spatial_id);\n\tgf_bs_seek(bs, pos);",
"\tif (has_size_field) {\n\t\tif (a) {\n\t\t\ta->obu = gf_malloc((size_t)obu_length);\n\t\t\tgf_bs_read_data(bs, a->obu, (u32)obu_length);\n\t\t\ta->obu_length = obu_length;\n\t\t}\n\t\telse {\n\t\t\tu32 remain = (u32)obu_length;\n\t\t\twhile (remain) {\n\t\t\t\tu32 block_size = OBU_BLOCK_SIZE;\n\t\t\t\tif (block_size > remain) block_size = remain;\n\t\t\t\tgf_bs_read_data(bs, block, block_size);\n\t\t\t\tgf_bs_write_data(state->bs, block, block_size);\n\t\t\t\tremain -= block_size;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t}\n\telse {\n\t\tu8 i, hdr_size = obu_extension_flag ? 2 : 1;\n\t\tconst u32 leb_size = (u32)gf_av1_leb128_size(obu_length);\n\t\tconst u64 obu_size = obu_length - hdr_size;",
"\t\tif (a) {\n\t\t\ta->obu = gf_malloc((size_t)obu_length + leb_size);\n\t\t\ta->obu_length = obu_length + leb_size;\n\t\t\tfor (i = 0; i < hdr_size; ++i) {\n\t\t\t\ta->obu[i] = gf_bs_read_u8(bs);\n\t\t\t\t/*add size field flag*/\n\t\t\t\tif (i == 0) a->obu[0] |= 0x02;\n\t\t\t}\n\t\t\t{\n\t\t\t\tu32 out_size = 0;\n\t\t\t\tu8 *output = NULL;\n\t\t\t\tGF_BitStream *bsLeb128 = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\t\t\t\t/*write size field*/\n\t\t\t\tgf_av1_leb128_write(bsLeb128, obu_size);\n\t\t\t\tassert(gf_bs_get_position(bsLeb128) == leb_size);\n\t\t\t\tgf_bs_get_content(bsLeb128, &output, &out_size);\n\t\t\t\tgf_bs_del(bsLeb128);\n\t\t\t\tmemcpy(a->obu + hdr_size, output, out_size);\n\t\t\t\tgf_free(output);\n\t\t\t}\n\t\t\tgf_bs_read_data(bs, a->obu + hdr_size + leb_size, (u32)(obu_size));\n\t\t\tassert(gf_bs_get_position(bs) == pos + obu_length);\n\t\t}\n\t\telse {\n\t\t\tu32 remain;\n\t\t\tfor (i = 0; i < hdr_size; ++i) {\n\t\t\t\tu8 hdr_b = gf_bs_read_u8(bs);\n\t\t\t\tif (i == 0) hdr_b |= 0x02; /*add size field flag*/\n\t\t\t\tgf_bs_write_u8(state->bs, hdr_b);\n\t\t\t}\n\t\t\t/*add size field */\n\t\t\tgf_av1_leb128_write(state->bs, obu_size);\n\t\t\tremain = (u32)obu_length - hdr_size;\n\t\t\twhile (remain) {\n\t\t\t\tu32 block_size = OBU_BLOCK_SIZE;\n\t\t\t\tif (block_size > remain) block_size = remain;\n\t\t\t\tgf_bs_read_data(bs, block, block_size);\n\t\t\t\tgf_bs_write_data(state->bs, block, block_size);\n\t\t\t\tremain -= block_size;\n\t\t\t}\n\t\t\tassert(gf_bs_get_position(bs) == pos + obu_length);\n\t\t\treturn;\n\t\t}\n\t}\n\tif (!obu_list) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[AV1] internal error, no OBU list cannot add\\n\"));\n\t\tgf_free(a->obu);\n\t\tgf_free(a);\n\t\treturn;\n\t}\n\ta->obu_type = obu_type;\n\tif (! *obu_list)\n\t\t*obu_list = gf_list_new();\n\tgf_list_add(*obu_list, a);\n}",
"static void av1_populate_state_from_obu(GF_BitStream *bs, u64 pos, u64 obu_length, ObuType obu_type, AV1State *state)\n{\n\tif (av1_is_obu_header(obu_type)) {\n\t\tav1_add_obu_internal(bs, pos, obu_length, obu_type, &state->frame_state.header_obus, NULL);\n\t}\n\tif (!state->skip_frames && av1_is_obu_frame(state, obu_type)) {\n\t\tif (!state->mem_mode) {\n\t\t\tav1_add_obu_internal(bs, pos, obu_length, obu_type, &state->frame_state.frame_obus, NULL);\n\t\t}\n\t\telse {\n\t\t\tav1_add_obu_internal(bs, pos, obu_length, obu_type, NULL, state);\n\t\t}\n\t}\n}",
"GF_Err aom_av1_parse_temporal_unit_from_section5(GF_BitStream *bs, AV1State *state)\n{\n\tif (!state) return GF_BAD_PARAM;\n\tstate->obu_type = -1;",
"\twhile (state->obu_type != OBU_TEMPORAL_DELIMITER) {\n\t\tGF_Err e;\n\t\tif (!gf_bs_available(bs))\n\t\t\treturn state->unframed ? GF_BUFFER_TOO_SMALL : GF_OK;",
"\t\tu64 pos = gf_bs_get_position(bs), obu_length = 0;",
"\t\te = gf_av1_parse_obu(bs, &state->obu_type, &obu_length, NULL, state);\n\t\tif (e)\n\t\t\treturn e;",
"\t\tif (obu_length != gf_bs_get_position(bs) - pos) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[AV1] OBU (Section 5) frame size \"LLU\" different from consumed bytes \"LLU\".\\n\", obu_length, gf_bs_get_position(bs) - pos));\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}",
"\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] Section5 OBU detected (size \"LLU\")\\n\", obu_length));\n\t\tav1_populate_state_from_obu(bs, pos, obu_length, state->obu_type, state);\n\t}",
"\treturn GF_OK;\n}",
"Bool gf_media_aom_probe_annexb(GF_BitStream *bs)\n{\n\tBool res = GF_TRUE;\n\tu64 init_pos = gf_bs_get_position(bs);\n\tu64 sz = gf_av1_leb128_read(bs, NULL);\n\tif (!sz) res = GF_FALSE;\n\twhile (sz > 0) {\n\t\tu8 Leb128Bytes = 0;\n\t\tu64 frame_unit_size = gf_av1_leb128_read(bs, &Leb128Bytes);",
"\t\tif (!frame_unit_size) {\n\t\t\tres = GF_FALSE;\n\t\t\tbreak;\n\t\t}",
"\t\tif (sz < Leb128Bytes + frame_unit_size) {\n\t\t\tres = GF_FALSE;\n\t\t\tbreak;\n\t\t}\n\t\tsz -= Leb128Bytes + frame_unit_size;",
"\t\twhile (frame_unit_size > 0) {\n\t\t\tObuType obu_type;\n\t\t\tu64 pos, obu_length = gf_av1_leb128_read(bs, &Leb128Bytes);\n\t\t\tif (frame_unit_size < Leb128Bytes + obu_length) {\n\t\t\t\tres = GF_FALSE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpos = gf_bs_get_position(bs);\n\t\t\tframe_unit_size -= Leb128Bytes;",
"\t\t\tu8 tid, sid;\n\t\t\tBool extflag, has_size;\n\t\t\tGF_Err e = gf_av1_parse_obu_header(bs, &obu_type, &extflag, &has_size, &tid, &sid);\n\t\t\tif (e) {\n\t\t\t\tres = GF_FALSE;\n\t\t\t\tbreak;\n\t\t\t}",
"\t\t\tif (has_size) {\n\t\t\t\tobu_length = (u32)gf_av1_leb128_read(bs, NULL);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (obu_length >= 1 + extflag) {\n\t\t\t\t\tobu_length = obu_length - 1 - extflag;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tres = GF_FALSE;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tu32 hdr_size = (u32)(gf_bs_get_position(bs) - pos);\n\t\t\tobu_length += hdr_size;",
"\t\t\tif (frame_unit_size < obu_length) {\n\t\t\t\tres = GF_FALSE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tframe_unit_size -= obu_length;\n\t\t\tgf_bs_skip_bytes(bs, obu_length - hdr_size);\n\t\t}\n\t\tif (!res) break;\n\t}\n\tgf_bs_seek(bs, init_pos);\n\treturn res;\n}",
"GF_Err aom_av1_parse_temporal_unit_from_annexb(GF_BitStream *bs, AV1State *state)\n{\n\tGF_Err e;\n\tu64 tupos;\n\tu64 tusize, sz;\n\tif (!bs || !state) return GF_BAD_PARAM;",
"\tstate->bs_overread = GF_FALSE;\n\ttusize = sz = gf_av1_leb128_read(bs, NULL);\n\ttupos = gf_bs_get_position(bs);\n\tif (!sz) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CODING, (\"[AV1] temporal unit size is 0, likely not annex B\\n\"));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] Annex B temporal unit detected (size \"LLU\") ***** \\n\", sz));\n\twhile (sz > 0) {\n\t\tu8 Leb128Bytes = 0;\n\t\tu64 frame_unit_size = gf_av1_leb128_read(bs, &Leb128Bytes);",
"\t\tif (state->bs_overread) {\n\t\t\treturn GF_BUFFER_TOO_SMALL;\n\t\t}\n\t\tif (sz < Leb128Bytes + frame_unit_size) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] Annex B sz(\"LLU\") < Leb128Bytes(\"LLU\") + frame_unit_size(\"LLU\")\\n\", sz, Leb128Bytes, frame_unit_size));\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] Annex B frame unit detected (size \"LLU\")\\n\", frame_unit_size));\n\t\tsz -= Leb128Bytes + frame_unit_size;",
"\t\twhile (frame_unit_size > 0) {\n\t\t\tu64 pos, obu_length = gf_av1_leb128_read(bs, &Leb128Bytes);",
"\t\t\tif (state->bs_overread) {\n\t\t\t\treturn GF_BUFFER_TOO_SMALL;\n\t\t\t}\n\t\t\tif (frame_unit_size < Leb128Bytes + obu_length) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] Annex B frame_unit_size(\"LLU\") < Leb128Bytes(\"LLU\") + obu_length(\"LLU\")\\n\", frame_unit_size, Leb128Bytes, obu_length));\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] Annex B OBU detected (size \"LLU\")\\n\", obu_length));\n\t\t\tpos = gf_bs_get_position(bs);\n\t\t\tframe_unit_size -= Leb128Bytes;",
"\t\t\te = gf_av1_parse_obu(bs, &state->obu_type, &obu_length, NULL, state);\n\t\t\tif (e) return e;",
"\t\t\tif (obu_length != gf_bs_get_position(bs) - pos) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[AV1] Annex B frame size \"LLU\" different from consumed bytes \"LLU\".\\n\", obu_length, gf_bs_get_position(bs) - pos));\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}",
"\t\t\tav1_populate_state_from_obu(bs, pos, obu_length, state->obu_type, state);\n\t\t\tif (frame_unit_size < obu_length) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] Annex B frame_unit_size(\"LLU\") < OBU size (\"LLU\")\\n\", frame_unit_size, obu_length));\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t\tframe_unit_size -= obu_length;\n\t\t}\n\t}\n\tassert(sz == 0);\n\tif (tusize != gf_bs_get_position(bs) - tupos) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[AV1] Annex B TU size \"LLU\" different from consumed bytes \"LLU\".\\n\", tusize, gf_bs_get_position(bs) - tupos));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\treturn GF_OK;\n}",
"GF_Err aom_av1_parse_temporal_unit_from_ivf(GF_BitStream *bs, AV1State *state)\n{\n\tu64 frame_size, pts_ignored;\n\tGF_Err e;\n\tif (gf_bs_available(bs)<12) return GF_EOS;\n\te = gf_media_parse_ivf_frame_header(bs, &frame_size, &pts_ignored);\n\tif (e) return e;\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] IVF frame detected (size \"LLU\")\\n\", frame_size));",
"\tif (gf_bs_available(bs) < frame_size) return GF_EOS;",
"\twhile (frame_size > 0) {\n\t\tu64 obu_size = 0, pos = gf_bs_get_position(bs);",
"\t\te = gf_av1_parse_obu(bs, &state->obu_type, &obu_size, NULL, state);\n\t\tif (e != GF_OK)\n\t\t\treturn e;",
"\t\tif (obu_size != gf_bs_get_position(bs) - pos) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[AV1] IVF frame size \"LLU\" different from consumed bytes \"LLU\".\\n\", obu_size, gf_bs_get_position(bs) - pos));\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}",
"\t\tav1_populate_state_from_obu(bs, pos, obu_size, state->obu_type, state);",
"\t\tframe_size -= obu_size;\n\t}\n\treturn GF_OK;\n}",
"#define AV1_NUM_REF_FRAMES 8\n#define AV1_ALL_FRAMES ((1 << AV1_NUM_REF_FRAMES) - 1)",
"#define AV1_SUPERRES_DENOM_MIN 9\n#define AV1_SUPERRES_DENOM_BITS 3\n#define AV1_SUPERRES_NUM 8",
"#define AV1_REFS_PER_FRAME 7\n#define AV1_PRIMARY_REF_NONE 7",
"#define MAX_TILE_WIDTH 4096\n#define MAX_TILE_AREA (4096 * 2304)",
"static u32 aom_av1_tile_log2(u32 blkSize, u32 target)\n{\n\tu32 k;\n\tfor (k = 0; (blkSize << k) < target; k++) {\n\t}\n\treturn k;\n}",
"static u64 aom_av1_le(GF_BitStream *bs, u32 n, const char *name) {\n\tu32 i = 0;\n\tu64 t = 0;\n\tfor (i = 0; i < n; i++) {\n\t\tu8 byte = gf_bs_read_int(bs, 8);\n\t\tt += (byte << (i * 8));\n\t}\n\tgf_bs_log(bs, n*8, name, t);\n\treturn t;\n}",
"\nstatic void av1_parse_tile_info(GF_BitStream *bs, AV1State *state)\n{\n\tu32 i;\n\tu32 MiCols = 2 * ((state->width + 7) >> 3);\n\tu32 MiRows = 2 * ((state->height + 7) >> 3);\n\tu32 sbCols = state->use_128x128_superblock ? ((MiCols + 31) >> 5) : ((MiCols + 15) >> 4);\n\tu32 sbRows = state->use_128x128_superblock ? ((MiRows + 31) >> 5) : ((MiRows + 15) >> 4);\n\tu32 sbShift = state->use_128x128_superblock ? 5 : 4;\n\tu32 sbSize = sbShift + 2;\n\tu32 maxTileWidthSb = MAX_TILE_WIDTH >> sbSize;\n\tu32 maxTileAreaSb = MAX_TILE_AREA >> (2 * sbSize);\n\tu32 minLog2tileCols = aom_av1_tile_log2(maxTileWidthSb, sbCols);\n\tu32 maxLog2tileCols = aom_av1_tile_log2(1, MIN(sbCols, AV1_MAX_TILE_COLS));\n\tu32 maxLog2tileRows = aom_av1_tile_log2(1, MIN(sbRows, AV1_MAX_TILE_ROWS));\n\tu32 minLog2Tiles = MAX(minLog2tileCols, aom_av1_tile_log2(maxTileAreaSb, sbRows * sbCols));\n\tBool uniform_tile_spacing_flag = gf_bs_read_int_log(bs, 1, \"uniform_tile_spacing_flag\");\n\tif (uniform_tile_spacing_flag) {\n\t\tu32 startSb, tileWidthSb, tileHeightSb, minLog2tileRows;\n\t\tstate->tileColsLog2 = minLog2tileCols;\n\t\twhile (state->tileColsLog2 < maxLog2tileCols) {\n\t\t\tBool increment_tile_cols_log2 = gf_bs_read_int_log(bs, 1, \"increment_tile_cols_log2\");\n\t\t\tif (increment_tile_cols_log2 == 1)\n\t\t\t\tstate->tileColsLog2++;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}",
"\t\ttileWidthSb = (sbCols + (1 << state->tileColsLog2) - 1) >> state->tileColsLog2;\n\t\ti = 0;\n\t\tfor (startSb = 0; startSb < sbCols; startSb += tileWidthSb) {\n\t\t\ti += 1;\n\t\t}\n\t\tstate->tileCols = i;\n\t\tminLog2tileRows = MAX((int)(minLog2Tiles - state->tileColsLog2), 0);\n\t\tstate->tileRowsLog2 = minLog2tileRows;\n\t\twhile (state->tileRowsLog2 < maxLog2tileRows) {\n\t\t\tBool increment_tile_rows_log2 = gf_bs_read_int_log(bs, 1, \"increment_tile_rows_log2\");\n\t\t\tif (increment_tile_rows_log2 == 1)\n\t\t\t\tstate->tileRowsLog2++;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}",
"\t\ttileHeightSb = (sbRows + (1 << state->tileRowsLog2) - 1) >> state->tileRowsLog2;\n\t\ti = 0;\n\t\tfor (startSb = 0; startSb < sbRows; startSb += tileHeightSb) {\n\t\t\ti += 1;\n\t\t}\n\t\tstate->tileRows = i;\n\t}\n\telse {\n\t\tu32 startSb, maxTileHeightSb, widestTileSb;\n\t\twidestTileSb = 0;\n\t\tstartSb = 0;\n\t\tfor (i = 0; startSb < sbCols; i++) {\n\t\t\tu32 maxWidth = MIN((int)(sbCols - startSb), maxTileWidthSb);\n\t\t\tu32 width_in_sbs_minus_1 = av1_read_ns(bs, maxWidth, \"width_in_sbs_minus_1\");\n\t\t\tu32 sizeSb = width_in_sbs_minus_1 + 1;\n\t\t\twidestTileSb = MAX(sizeSb, widestTileSb);\n\t\t\tstartSb += sizeSb;\n\t\t}\n\t\tif (!widestTileSb) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] widest tile is 0, broken bitstream\\n\"));\n\t\t\treturn;\n\t\t}\n\t\tstate->tileCols = i;\n\t\tstate->tileColsLog2 = aom_av1_tile_log2(1, state->tileCols);",
"\t\tif (minLog2Tiles > 0)\n\t\t\tmaxTileAreaSb = (sbRows * sbCols) >> (minLog2Tiles + 1);\n\t\telse\n\t\t\tmaxTileAreaSb = sbRows * sbCols;\n\t\tmaxTileHeightSb = MAX(maxTileAreaSb / widestTileSb, 1);",
"\t\tstartSb = 0;\n\t\tfor (i = 0; startSb < sbRows; i++) {\n\t\t\tu32 maxHeight = MIN((int)(sbRows - startSb), maxTileHeightSb);\n\t\t\tu32 height_in_sbs_minus_1 = av1_read_ns(bs, maxHeight, \"height_in_sbs_minus_1\");\n\t\t\tu32 sizeSb = height_in_sbs_minus_1 + 1;\n\t\t\tstartSb += sizeSb;\n\t\t}",
"\t\tstate->tileRows = i;\n\t\tstate->tileRowsLog2 = aom_av1_tile_log2(1, state->tileRows);\n\t}\n\tif (state->tileColsLog2 > 0 || state->tileRowsLog2 > 0) {\n\t\tgf_bs_read_int_log(bs, state->tileRowsLog2 + state->tileColsLog2, \"context_update_tile_id\");\n\t\tstate->tile_size_bytes = gf_bs_read_int_log(bs, 2, \"tile_size_bytes_minus1\") + 1;\n\t}\n}",
"static void superres_params(GF_BitStream *bs, AV1State *state)\n{\n\tu32 SuperresDenom;\n\tBool use_superres;",
"\tif (state->enable_superres) {\n\t\tuse_superres = gf_bs_read_int_log(bs, 1, \"use_superres\");\n\t}\n\telse {\n\t\tuse_superres = GF_FALSE;\n\t}\n\tif (use_superres) {\n\t\tu8 coded_denom = gf_bs_read_int_log(bs, AV1_SUPERRES_DENOM_BITS, \"coded_denom\");\n\t\tSuperresDenom = coded_denom + AV1_SUPERRES_DENOM_MIN;\n\t}\n\telse {\n\t\tSuperresDenom = AV1_SUPERRES_NUM;\n\t}\n\tstate->UpscaledWidth = state->width;\n\tstate->width = (state->UpscaledWidth * AV1_SUPERRES_NUM + (SuperresDenom / 2)) / SuperresDenom;\n}",
"static void av1_frame_size(GF_BitStream *bs, AV1State *state, Bool frame_size_override_flag)\n{\n\tif (frame_size_override_flag) {\n\t\tu32 frame_width_minus_1, frame_height_minus_1;\n\t\tu8 n = state->frame_width_bits_minus_1 + 1;\n\t\tframe_width_minus_1 = gf_bs_read_int_log(bs, n, \"frame_width_minus_1\");\n\t\tn = state->frame_height_bits_minus_1 + 1;\n\t\tframe_height_minus_1 = gf_bs_read_int_log(bs, n, \"frame_height_minus_1\");\n\t\tstate->width = frame_width_minus_1 + 1;\n\t\tstate->height = frame_height_minus_1 + 1;\n\t} else {\n\t\tstate->width = state->sequence_width;\n\t\tstate->height = state->sequence_height;\n\t}\n\tsuperres_params(bs, state);\n\t//compute_image_size(); //no bits\n}",
"static void av1_render_size(GF_BitStream *bs)\n{\n\tBool render_and_frame_size_different = gf_bs_read_int_log(bs, 1, \"render_and_frame_size_different_flag\");\n\tif (render_and_frame_size_different == GF_TRUE) {\n\t\tgf_bs_read_int_log(bs, 16, \"render_width_minus_1\");\n\t\tgf_bs_read_int_log(bs, 16, \"render_height_minus_1\");\n\t\t//RenderWidth = render_width_minus_1 + 1;\n\t\t//RenderHeight = render_height_minus_1 + 1;\n\t}\n\telse {\n\t\t//RenderWidth = UpscaledWidth;\n\t\t//RenderHeight = FrameHeight;\n\t}\n}",
"static void read_interpolation_filter(GF_BitStream *bs)\n{\n\tBool is_filter_switchable = gf_bs_read_int_log(bs, 1, \"is_filter_switchable\");\n\tif (!is_filter_switchable) {\n\t\t/*interpolation_filter =*/ gf_bs_read_int_log(bs, 2, \"interpolation_filter\");\n\t}\n}",
"static void frame_size_with_refs(GF_BitStream *bs, AV1State *state, Bool frame_size_override_flag, s8 *ref_frame_idx)\n{\n\tBool found_ref = GF_FALSE;\n\tu32 i = 0;\n\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\tfound_ref = gf_bs_read_int_log_idx(bs, 1, \"found_ref\", i);\n\t\tif (found_ref == 1) {\n\t\t\tstate->UpscaledWidth = state->RefUpscaledWidth[ref_frame_idx[i]];\n\t\t\tstate->width = state->UpscaledWidth;\n\t\t\tstate->height = state->RefFrameHeight[ref_frame_idx[i]];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (found_ref == 0) {\n\t\tav1_frame_size(bs, state, frame_size_override_flag);\n\t\tav1_render_size(bs);\n\t}\n\telse {\n\t\tsuperres_params(bs, state);\n\t\t//compute_image_size();\n\t}\n}",
"static s32 av1_delta_q(GF_BitStream *bs, const char *name_flag, const char *name)\n{\n\tBool delta_coded = gf_bs_read_int_log(bs, 1, name_flag);\n\ts32 delta_q = 0;\n\tif (delta_coded) {\n\t\tu32 signMask = 1 << (7 - 1);\n\t\tdelta_q = gf_bs_read_int_log(bs, 7, name);\n\t\tif (delta_q & signMask)\n\t\t\tdelta_q = delta_q - 2 * signMask;\n\t}\n\treturn delta_q;\n}",
"static u8 Segmentation_Feature_Bits[] = { 8,6,6,6,6,3,0,0 };\nstatic u8 Segmentation_Feature_Signed[] = { 1, 1, 1, 1, 1, 0, 0, 0 };",
"static u8 av1_get_qindex(Bool ignoreDeltaQ, u32 segmentId, u32 base_q_idx, u32 delta_q_present, u32 CurrentQIndex, Bool segmentation_enabled, u8 *features_SEG_LVL_ALT_Q_enabled, s32 *features_SEG_LVL_ALT_Q)\n{\n\t//If seg_feature_active_idx( segmentId, SEG_LVL_ALT_Q ) is equal to 1 the following ordered steps apply:\n\tif (segmentation_enabled && features_SEG_LVL_ALT_Q_enabled[segmentId]) {\n\t\t//Set the variable data equal to FeatureData[ segmentId ][ SEG_LVL_ALT_Q ].\n\t\ts32 data = features_SEG_LVL_ALT_Q[segmentId];\n\t\ts32 qindex = base_q_idx + data;\n\t\t//If ignoreDeltaQ is equal to 0 and delta_q_present is equal to 1, set qindex equal to CurrentQIndex + data.\n\t\tif ((ignoreDeltaQ == 0) && (delta_q_present == 1)) qindex = CurrentQIndex + data;\n\t\t//Return Clip3( 0, 255, qindex ).\n\t\tif (qindex < 0) return 0;\n\t\telse if (qindex > 255) return 255;\n\t\telse return (u8)qindex;\n\t}\n\t//Otherwise, if ignoreDeltaQ is equal to 0 and delta_q_present is equal to 1, return CurrentQIndex.\n\tif ((ignoreDeltaQ == 0) && (delta_q_present == 1)) return CurrentQIndex;\n\t//otherwise\n\treturn base_q_idx;\n}",
"enum {\n\tAV1_RESTORE_NONE = 0,\n\tAV1_RESTORE_SWITCHABLE,\n\tAV1_RESTORE_WIENER,\n\tAV1_RESTORE_SGRPROJ\n};",
"#define AV1_GMC_IDENTITY 0\n#define AV1_GMC_TRANSLATION 1\n#define AV1_GMC_ROTZOOM 2\n#define AV1_GMC_AFFINE 3",
"#define AV1_LAST_FRAME 1\n#define AV1_LAST2_FRAME 2\n#define AV1_LAST3_FRAME 3\n#define AV1_GOLDEN_FRAME 4\n#define AV1_BWDREF_FRAME 5\n#define AV1_ALTREF2_FRAME 6\n#define AV1_ALTREF_FRAME 7",
"#define GM_ABS_ALPHA_BITS 12\n#define GM_ALPHA_PREC_BITS 15\n#define GM_ABS_TRANS_ONLY_BITS 9\n#define GM_TRANS_ONLY_PREC_BITS 3\n#define GM_ABS_TRANS_BITS 12\n#define GM_TRANS_PREC_BITS 6\n#define WARPEDMODEL_PREC_BITS 16",
"\nstatic u32 av1_decode_subexp(GF_BitStream *bs, s32 numSyms)\n{\n\ts32 i = 0;\n\ts32 mk = 0;\n\ts32 k = 3;\n\twhile (1) {\n\t\ts32 b2 = i ? k + i - 1 : k;\n\t\ts32 a = 1 << b2;\n\t\tif (numSyms <= mk + 3 * a) {\n\t\t\ts32 subexp_final_bits = av1_read_ns(bs, numSyms - mk, NULL);\n\t\t\treturn subexp_final_bits + mk;\n\t\t}\n\t\telse {\n\t\t\ts32 subexp_more_bits = gf_bs_read_int(bs, 1);\n\t\t\tif (subexp_more_bits) {\n\t\t\t\ti++;\n\t\t\t\tmk += a;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ts32 subexp_bits = gf_bs_read_int(bs, b2);\n\t\t\t\treturn subexp_bits + mk;\n\t\t\t}\n\t\t}\n\t}\n}",
"static GFINLINE s32 inverse_recenter(s32 r, u32 v)\n{\n\tif ((s64)v > (s64)(2 * r))\n\t\treturn v;\n\telse if (v & 1)\n\t\treturn r - ((v + 1) >> 1);\n\telse\n\t\treturn r + (v >> 1);\n}",
"static s32 av1_decode_unsigned_subexp_with_ref(GF_BitStream *bs, s32 mx, s32 r)\n{\n\tu32 v = av1_decode_subexp(bs, mx);\n\tif ((r < 0) && (-(-r << 1) <= mx)) {\n\t\treturn inverse_recenter(r, v);\n\t}\n\telse if ((r << 1) <= mx) {\n\t\treturn inverse_recenter(r, v);\n\t}\n\telse {\n\t\treturn mx - 1 - inverse_recenter(mx - 1 - r, v);\n\t}\n}\nstatic s16 av1_decode_signed_subexp_with_ref(GF_BitStream *bs, s32 low, s32 high, s32 r)\n{\n\ts16 x = av1_decode_unsigned_subexp_with_ref(bs, high - low, r - low);\n\treturn x + low;\n}",
"static void av1_read_global_param(AV1State *state, GF_BitStream *bs, u8 type, u8 ref, u8 idx)\n{\n\tu8 absBits = GM_ABS_ALPHA_BITS;\n\tu8 precBits = GM_ALPHA_PREC_BITS;\n\tif (idx < 2) {\n\t\tif (type == AV1_GMC_TRANSLATION) {\n\t\t\tabsBits = GM_ABS_TRANS_ONLY_BITS - (!state->frame_state.allow_high_precision_mv ? 1 : 0);\n\t\t\tprecBits = GM_TRANS_ONLY_PREC_BITS - (!state->frame_state.allow_high_precision_mv ? 1 : 0);\n\t\t}\n\t\telse {\n\t\t\tabsBits = GM_ABS_TRANS_BITS;\n\t\t\tprecBits = GM_TRANS_PREC_BITS;\n\t\t}\n\t}\n\ts32 precDiff = WARPEDMODEL_PREC_BITS - precBits;\n\ts32 round = (idx % 3) == 2 ? (1 << WARPEDMODEL_PREC_BITS) : 0;\n\ts32 sub = (idx % 3) == 2 ? (1 << precBits) : 0;\n\ts32 mx = (1 << absBits);\n\ts32 r = (state->PrevGmParams.coefs[ref][idx] >> precDiff) - sub;\n\ts32 val = av1_decode_signed_subexp_with_ref(bs, -mx, mx + 1, r);",
"\tif (val < 0) {\n\t\tval = -val;\n\t\tstate->GmParams.coefs[ref][idx] = (-(val << precDiff) + round);\n\t}\n\telse {\n\t\tstate->GmParams.coefs[ref][idx] = (val << precDiff) + round;\n\t}\n}",
"static s32 av1_get_relative_dist(s32 a, s32 b, AV1State *state)\n{\n\tif (!state->enable_order_hint)\n\t\treturn 0;\n\ts32 diff = a - b;\n\ts32 m = 1 << (state->OrderHintBits - 1);\n\tdiff = (diff & (m - 1)) - (diff & m);\n\treturn diff;\n}",
"static void av1_setup_past_independence(AV1State *state)\n{\n\tu32 ref, i;\n\tfor (ref = AV1_LAST_FRAME; ref <= AV1_ALTREF_FRAME; ref++) {\n\t\tfor (i = 0; i <= 5; i++) {\n\t\t\tstate->PrevGmParams.coefs[ref][i] = ((i % 3 == 2) ? 1 << WARPEDMODEL_PREC_BITS : 0);\n\t\t}\n\t}\n}",
"static void av1_load_previous(AV1State *state, u8 primary_ref_frame, s8 *ref_frame_idx)\n{\n\ts8 prevFrame = ref_frame_idx[primary_ref_frame];\n\tif (prevFrame < 0) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] load_previous: prevFrame reference index %d is invalid\\n\", prevFrame));\n\t}\n\telse {\n\t\tstate->PrevGmParams = state->SavedGmParams[prevFrame];\n\t\t// load_loop_filter_params( prevFrame )\n\t\t// load_segmentation_params( prevFrame )\n\t}\n}",
"static void av1_decode_frame_wrapup(AV1State *state)\n{\n\tu32 i;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\tif ((state->frame_state.refresh_frame_flags >> i) & 1) {\n\t\t\tstate->RefOrderHint[i] = state->frame_state.order_hint;\n\t\t\tstate->SavedGmParams[i] = state->GmParams;\n\t\t\tstate->RefFrameType[i] = state->frame_state.frame_type;\n\t\t\tstate->RefUpscaledWidth[i] = state->UpscaledWidth;\n\t\t\tstate->RefFrameHeight[i] = state->height;\n\t\t}\n\t}\n\tstate->frame_state.seen_frame_header = GF_FALSE;\n\t//Otherwise (show_existing_frame is equal to 1), if frame_type is equal to KEY_FRAME, the reference frame loading process as specified in section 7.21 is invoked\n\tif ((state->frame_state.show_existing_frame) && (state->frame_state.frame_type == AV1_KEY_FRAME)) {\n\t\tstate->frame_state.order_hint = state->RefOrderHint[state->frame_state.frame_to_show_map_idx];\n\t\t//OrderHints[ j + LAST_FRAME ] is set equal to SavedOrderHints[state->frame_to_show_map_idx ][ j + LAST_FRAME ] for j = 0..REFS_PER_FRAME-1.",
"\t\t//gm_params[ ref ][ j ] is set equal to SavedGmParams[ frame_to_show_map_idx ][ ref ][ j ] for ref = LAST_FRAME..ALTREF_FRAME, for j = 0..5.\n\t\tstate->GmParams = state->SavedGmParams[state->frame_state.frame_to_show_map_idx];",
"\t}\n}",
"static s32 find_latest_forward(u32 curFrameHint, u8 *shiftedOrderHints, u8 *usedFrame)\n{\n\tu32 i;\n\ts32 ref = -1;\n\ts32 latestOrderHint = 0;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\ts32 hint = shiftedOrderHints[i];\n\t\tif (!usedFrame[i] && ((u32)hint < curFrameHint) && (ref < 0 || hint >= latestOrderHint)) {\n\t\t\tref = i;\n\t\t\tlatestOrderHint = hint;\n\t\t}\n\t}\n\treturn ref;\n}",
"//see 7.8 of AV1 spec\nstatic void av1_set_frame_refs(AV1State *state, u8 last_frame_idx, u8 gold_frame_idx, s8 *ref_frame_idx)\n{\n\tu32 i;\n\tu8 usedFrame[AV1_NUM_REF_FRAMES];\n\tu8 shiftedOrderHints[AV1_NUM_REF_FRAMES];",
"\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++)\n\t\tref_frame_idx[i] = -1;",
"\tref_frame_idx[AV1_LAST_FRAME - AV1_LAST_FRAME] = last_frame_idx;\n\tref_frame_idx[AV1_GOLDEN_FRAME - AV1_LAST_FRAME] = gold_frame_idx;",
"\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\tusedFrame[i] = 0;\n\t}",
"\tusedFrame[last_frame_idx] = 1;\n\tusedFrame[gold_frame_idx] = 1;\n\tu32 curFrameHint = 1 << (state->OrderHintBits - 1);",
"\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\tshiftedOrderHints[i] = curFrameHint + av1_get_relative_dist(state->RefOrderHint[i], state->frame_state.order_hint, state);\n\t}",
"\tu8 lastOrderHint = shiftedOrderHints[last_frame_idx];\n\tu8 goldOrderHint = shiftedOrderHints[gold_frame_idx];",
"\t//It is a requirement of bitstream conformance that lastOrderHint is strictly less than curFrameHint.\n\tif (lastOrderHint >= curFrameHint) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] non conformant bitstream detected while setting up frame refs: lastOrderHint(%d) shall be stricly less than curFrameHint(%d)\\n\", lastOrderHint, curFrameHint));\n\t}\n\t//It is a requirement of bitstream conformance that goldOrderHint is strictly less than curFrameHint.\n\tif (goldOrderHint >= curFrameHint) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] non conformant bitstream detected while setting up frame refs: goldOrderHint(%d) shall be stricly less than curFrameHint(%d)\\n\", lastOrderHint, curFrameHint));\n\t}",
"\t//find_latest_backward() {\n\ts32 ref = -1;\n\ts32 latestOrderHint = 0;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\ts32 hint = shiftedOrderHints[i];\n\t\tif (!usedFrame[i] && ((u32)hint >= curFrameHint) && (ref < 0 || hint >= latestOrderHint)) {\n\t\t\tref = i;\n\t\t\tlatestOrderHint = hint;\n\t\t}\n\t}\n\tif (ref >= 0) {\n\t\tref_frame_idx[AV1_ALTREF_FRAME - AV1_LAST_FRAME] = ref;\n\t\tusedFrame[ref] = 1;\n\t}\n\t//find_earliest_backward() for BWDREF_FRAME\n\tref = -1;\n\ts32 earliestOrderHint = 0;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\ts32 hint = shiftedOrderHints[i];\n\t\tif (!usedFrame[i] && ((u32)hint >= curFrameHint) && (ref < 0 || hint < earliestOrderHint)) {\n\t\t\tref = i;\n\t\t\tearliestOrderHint = hint;\n\t\t}\n\t}\n\tif (ref >= 0) {\n\t\tref_frame_idx[AV1_BWDREF_FRAME - AV1_LAST_FRAME] = ref;\n\t\tusedFrame[ref] = 1;\n\t}",
"\t//find_earliest_backward() for ALTREF2_FRAME\n\tref = -1;\n\tearliestOrderHint = 0;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\ts32 hint = shiftedOrderHints[i];\n\t\tif (!usedFrame[i] && ((u32)hint >= curFrameHint) && (ref < 0 || hint < earliestOrderHint)) {\n\t\t\tref = i;\n\t\t\tearliestOrderHint = hint;\n\t\t}\n\t}\n\tif (ref >= 0) {\n\t\tref_frame_idx[AV1_ALTREF2_FRAME - AV1_LAST_FRAME] = ref;\n\t\tusedFrame[ref] = 1;\n\t}",
"\t//The remaining references are set to be forward references in anti-chronological order as follows:",
"\tconst u8 Ref_Frame_List[AV1_REFS_PER_FRAME - 2] = {\n\t\tAV1_LAST2_FRAME, AV1_LAST3_FRAME, AV1_BWDREF_FRAME, AV1_ALTREF2_FRAME, AV1_ALTREF_FRAME\n\t};",
"\tfor (i = 0; i < AV1_REFS_PER_FRAME - 2; i++) {\n\t\tu8 refFrame = Ref_Frame_List[i];\n\t\tif (ref_frame_idx[refFrame - AV1_LAST_FRAME] < 0) {\n\t\t\ts32 last_ref = find_latest_forward(curFrameHint, shiftedOrderHints, usedFrame);\n\t\t\tif (last_ref >= 0) {\n\t\t\t\tref_frame_idx[refFrame - AV1_LAST_FRAME] = last_ref;\n\t\t\t\tusedFrame[last_ref] = 1;\n\t\t\t}\n\t\t}\n\t}\n\t//Finally, any remaining references are set to the reference frame with smallest output order as follows:\n\tref = -1;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\ts32 hint = shiftedOrderHints[i];\n\t\tif (ref < 0 || hint < earliestOrderHint) {\n\t\t\tref = i;\n\t\t\tearliestOrderHint = hint;\n\t\t}\n\t}\n\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\tif (ref_frame_idx[i] < 0) {\n\t\t\tref_frame_idx[i] = ref;\n\t\t}\n\t}\n}",
"\nstatic void av1_parse_uncompressed_header(GF_BitStream *bs, AV1State *state)\n{\n\tBool error_resilient_mode = GF_FALSE, allow_screen_content_tools = GF_FALSE, force_integer_mv = GF_FALSE;\n\tBool /*use_ref_frame_mvs = GF_FALSE,*/ FrameIsIntra = GF_FALSE, frame_size_override_flag = GF_FALSE;\n\tBool disable_cdf_update = GF_FALSE;\n\tu8 showable_frame;\n\tu8 primary_ref_frame;\n\tu16 idLen = 0;\n\tu32 idx;\n\ts8 ref_frame_idx[AV1_REFS_PER_FRAME];\n\tAV1StateFrame *frame_state = &state->frame_state;",
"\tif (state->frame_id_numbers_present_flag) {\n\t\tidLen = (state->additional_frame_id_length_minus_1 + state->delta_frame_id_length_minus_2 + 3);\n\t}\n\tframe_state->refresh_frame_flags = 0;",
"\tshowable_frame = 0;\n\tif (state->reduced_still_picture_header) {\n\t\tframe_state->key_frame = GF_TRUE;\n\t\tFrameIsIntra = GF_TRUE;\n\t\tframe_state->frame_type = AV1_KEY_FRAME;\n\t\tframe_state->show_frame = GF_TRUE;\n\t\tframe_state->show_existing_frame = 0;\n\t}\n\telse {\n\t\tframe_state->show_existing_frame = gf_bs_read_int_log(bs, 1, \"show_existing_frame\");\n\t\tif (frame_state->show_existing_frame == GF_TRUE) {\n\t\t\tframe_state->frame_to_show_map_idx = gf_bs_read_int_log(bs, 3, \"frame_to_show_map_idx\");\n\t\t\tframe_state->frame_type = state->RefFrameType[frame_state->frame_to_show_map_idx];",
"\t\t\tif (state->decoder_model_info_present_flag && !state->equal_picture_interval) {\n\t\t\t\tgf_bs_read_int_log(bs, state->frame_presentation_time_length, \"frame_presentation_time\");\n\t\t\t}",
"\t\t\tframe_state->refresh_frame_flags = 0;\n\t\t\tif (state->frame_id_numbers_present_flag) {\n\t\t\t\tgf_bs_read_int_log(bs, idLen, \"display_frame_id\");\n\t\t\t}\n\t\t\tif (frame_state->frame_type == AV1_KEY_FRAME) {\n\t\t\t\tframe_state->refresh_frame_flags = AV1_ALL_FRAMES;\n\t\t\t}\n\t\t\t/*\n\t\t\tif (film_grain_params_present) {\n\t\t\t\tload_grain_params(frame_to_show_map_idx)\n\t\t\t}*/\n\t\t\treturn;\n\t\t}\n\t\tframe_state->frame_type = gf_bs_read_int_log(bs, 2, \"frame_type\");\n\t\tFrameIsIntra = (frame_state->frame_type == AV1_INTRA_ONLY_FRAME || frame_state->frame_type == AV1_KEY_FRAME);\n\t\tframe_state->show_frame = gf_bs_read_int_log(bs, 1, \"show_frame\");\n\t\tif (frame_state->is_first_frame) {\n\t\t\tframe_state->key_frame = frame_state->seen_seq_header && frame_state->show_frame && frame_state->frame_type == AV1_KEY_FRAME && frame_state->seen_frame_header;\n\t\t}\n\t\tif (frame_state->show_frame && state->decoder_model_info_present_flag && !state->equal_picture_interval) {\n\t\t\tgf_bs_read_int_log(bs, state->frame_presentation_time_length, \"frame_presentation_time\");\n\t\t}\n\t\tif (frame_state->show_frame) {\n\t\t\tshowable_frame = frame_state->frame_type != AV1_KEY_FRAME;",
"\t\t}\n\t\telse {\n\t\t\tshowable_frame = gf_bs_read_int_log(bs, 1, \"showable_frame\");\n\t\t}\n\t\tif (frame_state->frame_type == AV1_SWITCH_FRAME || (frame_state->frame_type == AV1_KEY_FRAME && frame_state->show_frame))\n\t\t\terror_resilient_mode = GF_TRUE;\n\t\telse\n\t\t\terror_resilient_mode = gf_bs_read_int_log(bs, 1, \"error_resilient_mode\");\n\t}",
"\tif ((frame_state->frame_type == AV1_KEY_FRAME) && frame_state->show_frame) {\n\t\tu32 i;\n\t\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\t\tstate->RefValid[i] = 0;\n\t\t\tstate->RefOrderHint[i] = 0;\n\t\t}\n\t\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\t\tstate->OrderHints[AV1_LAST_FRAME + i] = 0;\n\t\t}\n\t}",
"\tdisable_cdf_update = gf_bs_read_int_log(bs, 1, \"disable_cdf_update\");\n\tif (state->seq_force_screen_content_tools == 2/*SELECT_SCREEN_CONTENT_TOOLS*/) {\n\t\tallow_screen_content_tools = gf_bs_read_int_log(bs, 1, \"allow_screen_content_tools\");\n\t}\n\telse {\n\t\tallow_screen_content_tools = state->seq_force_screen_content_tools;\n\t}\n\tif (allow_screen_content_tools) {\n\t\tif (state->seq_force_integer_mv == 2/*SELECT_INTEGER_MV*/) {\n\t\t\tforce_integer_mv = gf_bs_read_int_log(bs, 1, \"force_integer_mv\");\n\t\t}\n\t\telse {\n\t\t\tforce_integer_mv = state->seq_force_integer_mv;\n\t\t}\n\t}\n\telse {\n\t\tforce_integer_mv = 0;\n\t}\n\tif (FrameIsIntra) {\n\t\tforce_integer_mv = 1;\n\t}\n\tif (state->frame_id_numbers_present_flag) {\n\t\tgf_bs_read_int_log(bs, idLen, \"current_frame_id\");\n\t}\n\tif (frame_state->frame_type == AV1_SWITCH_FRAME)\n\t\tframe_size_override_flag = GF_TRUE;\n\telse if (state->reduced_still_picture_header)\n\t\tframe_size_override_flag = GF_FALSE;\n\telse\n\t\tframe_size_override_flag = gf_bs_read_int_log(bs, 1, \"frame_size_override_flag\");",
"\tframe_state->order_hint = gf_bs_read_int_log(bs, state->OrderHintBits, \"order_hint\");\n\tif (FrameIsIntra || error_resilient_mode) {\n\t\tprimary_ref_frame = AV1_PRIMARY_REF_NONE;\n\t}\n\telse {\n\t\tprimary_ref_frame = gf_bs_read_int_log(bs, 3, \"primary_ref_frame\");\n\t}",
"\tif (state->decoder_model_info_present_flag) {\n\t\tu8 buffer_removal_time_present_flag = gf_bs_read_int_log(bs, 1, \"buffer_removal_time_present_flag\");\n\t\tif (buffer_removal_time_present_flag) {\n\t\t\tu32 opNum;\n\t\t\tfor (opNum = 0; opNum < state->operating_points_count; opNum++) {\n\t\t\t\tif (state->decoder_model_present_for_this_op[opNum]) {\n\t\t\t\t\tu8 opPtIdc = state->operating_point_idc[opNum];\n\t\t\t\t\tu8 inTemporalLayer = (opPtIdc >> state->temporal_id) & 1;\n\t\t\t\t\tu8 inSpatialLayer = (opPtIdc >> (state->spatial_id + 8)) & 1;\n\t\t\t\t\tif (opPtIdc == 0 || (inTemporalLayer && inSpatialLayer)) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, state->buffer_removal_time_length, \"buffer_removal_time\", opNum);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\tif (frame_state->frame_type == AV1_SWITCH_FRAME || (frame_state->frame_type == AV1_KEY_FRAME && frame_state->show_frame)) {\n\t\tframe_state->refresh_frame_flags = AV1_ALL_FRAMES;\n\t}\n\telse {\n\t\tframe_state->refresh_frame_flags = gf_bs_read_int_log(bs, 8, \"refresh_frame_flags\");\n\t}\n\tif (!FrameIsIntra || frame_state->refresh_frame_flags != AV1_ALL_FRAMES) {\n\t\tif (error_resilient_mode && state->enable_order_hint) {\n\t\t\tu32 i = 0;\n\t\t\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\t\t\tu8 ref_order_hint = gf_bs_read_int_log_idx(bs, state->OrderHintBits, \"ref_order_hint\", i);\n\t\t\t\tif (ref_order_hint != state->RefOrderHint[i]) {\n\t\t\t\t\tstate->RefValid[i] = 0;\n\t\t\t\t}\n\t\t\t\tstate->RefOrderHint[i] = ref_order_hint;\n\t\t\t}\n\t\t}\n\t}",
"\tu8 allow_intrabc = 0;\n\tif (frame_state->frame_type == AV1_KEY_FRAME) {\n\t\tav1_frame_size(bs, state, frame_size_override_flag);\n\t\tav1_render_size(bs);\n\t\tif (allow_screen_content_tools && state->UpscaledWidth == state->width) {\n\t\t\tallow_intrabc = gf_bs_read_int_log(bs, 1, \"allow_intrabc\");\n\t\t}\n\t}\n\telse {\n\t\tif (frame_state->frame_type == AV1_INTRA_ONLY_FRAME) {\n\t\t\tav1_frame_size(bs, state, frame_size_override_flag);\n\t\t\tav1_render_size(bs);\n\t\t\tif (allow_screen_content_tools && state->UpscaledWidth == state->width) {\n\t\t\t\tallow_intrabc = gf_bs_read_int_log(bs, 1, \"allow_intrabc\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tu32 i = 0;\n\t\t\tBool frame_refs_short_signaling = GF_FALSE;\n\t\t\tif (state->enable_order_hint) {\n\t\t\t\tframe_refs_short_signaling = gf_bs_read_int_log(bs, 1, \"frame_refs_short_signaling\");\n\t\t\t\tif (frame_refs_short_signaling) {\n\t\t\t\t\tu8 last_frame_idx = gf_bs_read_int_log(bs, 3, \"last_frame_idx\");\n\t\t\t\t\tu8 gold_frame_idx = gf_bs_read_int_log(bs, 3, \"gold_frame_idx\");\n\t\t\t\t\tav1_set_frame_refs(state, last_frame_idx, gold_frame_idx, ref_frame_idx);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\t\t\tif (!frame_refs_short_signaling)\n\t\t\t\t\tref_frame_idx[i] = gf_bs_read_int_log_idx(bs, 3, \"ref_frame_idx\", i);",
"\t\t\t\tif (state->frame_id_numbers_present_flag) {\n\t\t\t\t\tu32 n = state->delta_frame_id_length_minus_2 + 2;\n\t\t\t\t\t/*delta_frame_id_minus_1 =*/ gf_bs_read_int_log_idx(bs, n, \"delta_frame_id_minus1\", i);\n\t\t\t\t\t//DeltaFrameId = delta_frame_id_minus_1 + 1;\n\t\t\t\t\t//expectedFrameId[i] = ((current_frame_id + (1 << idLen) - DeltaFrameId) % (1 << idLen));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (frame_size_override_flag && !error_resilient_mode) {\n\t\t\t\tframe_size_with_refs(bs, state, frame_size_override_flag, ref_frame_idx);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tav1_frame_size(bs, state, frame_size_override_flag);\n\t\t\t\tav1_render_size(bs);\n\t\t\t}\n\t\t\tframe_state->allow_high_precision_mv = 0;\n\t\t\tif (!force_integer_mv) {\n\t\t\t\tframe_state->allow_high_precision_mv = gf_bs_read_int_log(bs, 1, \"allow_high_precision_mv\");\n\t\t\t}",
"\t\t\tread_interpolation_filter(bs);",
"\t\t\tgf_bs_read_int_log(bs, 1, \"is_motion_mode_switchable\");\n\t\t\tif (!(error_resilient_mode || !state->enable_ref_frame_mvs)) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"use_ref_frame_mvs\");\n\t\t\t}\n\t\t}\n\t}",
"\tif (!FrameIsIntra) {\n\t\tu32 i;\n\t\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\t\tu8 refFrame = AV1_LAST_FRAME + i;\n\t\t\tu8 ridx = ref_frame_idx[i];\n\t\t\tif (ridx >= 0) {\n\t\t\t\tu8 hint = state->RefOrderHint[ridx];\n\t\t\t\tstate->OrderHints[refFrame] = hint;\n\t\t\t\t/*\t\t\tif ( !enable_order_hint ) {\n\t\t\t\t\t\t\t\tRefFrameSignBias[ refFrame ] = 0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tRefFrameSignBias[ refFrame ] = get_relative_dist( hint, OrderHint) > 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t*/\n\t\t\t}",
"\t\t}\n\t}",
"\tif (!(state->reduced_still_picture_header || disable_cdf_update))\n\t\tgf_bs_read_int_log(bs, 1, \"disable_frame_end_update_cdf\");",
"\tif (primary_ref_frame == AV1_PRIMARY_REF_NONE) {\n\t\t//init_non_coeff_cdfs();\n\t\tav1_setup_past_independence(state);\n\t}\n\telse {\n\t\t//load_cdfs(ref_frame_idx[primary_ref_frame]);\n\t\tav1_load_previous(state, primary_ref_frame, ref_frame_idx);\n\t}",
"\tav1_parse_tile_info(bs, state);\n\t//quantization_params( ):\n\tu8 base_q_idx = gf_bs_read_int_log(bs, 8, \"base_q_idx\");\n\ts32 DeltaQUDc = 0;\n\ts32 DeltaQUAc = 0;\n\ts32 DeltaQVDc = 0;\n\ts32 DeltaQVAc = 0;\n\ts32 DeltaQYDc = av1_delta_q(bs, \"DeltaQYDc_coded\", \"DeltaQYDc\");\n\tif (!state->config->monochrome) {\n\t\tu8 diff_uv_delta = 0;\n\t\tif (state->separate_uv_delta_q)\n\t\t\tdiff_uv_delta = gf_bs_read_int_log(bs, 1, \"diff_uv_delta\");",
"\t\tDeltaQUDc = av1_delta_q(bs, \"DeltaQUDc_coded\", \"DeltaQUDc\");\n\t\tDeltaQUAc = av1_delta_q(bs, \"DeltaQUAc_coded\", \"DeltaQUAc\");\n\t\tif (diff_uv_delta) {\n\t\t\tDeltaQVDc = av1_delta_q(bs, \"DeltaQVDc_coded\", \"DeltaQVDc\");\n\t\t\tDeltaQVAc = av1_delta_q(bs, \"DeltaQVAc_coded\", \"DeltaQVAc\");\n\t\t}\n\t}\n\tif (gf_bs_read_int_log(bs, 1, \"using_qmatrix\")) {\n\t\tgf_bs_read_int_log(bs, 4, \"qm_y\");\n\t\tgf_bs_read_int_log(bs, 4, \"qm_u\");\n\t\tif (!state->separate_uv_delta_q) {\n\t\t\tgf_bs_read_int_log(bs, 4, \"qm_v\");\n\t\t}\n\t}",
"\tu8 seg_features_SEG_LVL_ALT_Q_enabled[8] = { 0,0,0,0,0,0,0,0 };\n\ts32 seg_features_SEG_LVL_ALT_Q[8] = { 0,0,0,0,0,0,0,0 };",
"\t//segmentation_params( ):\n\tu8 segmentation_enabled = gf_bs_read_int_log(bs, 1, \"segmentation_enabled\");\n\tif (segmentation_enabled) {\n\t\t/*u8 segmentation_temporal_update = 0;*/\n\t\tu8 segmentation_update_data = 1;\n\t\tif (primary_ref_frame != AV1_PRIMARY_REF_NONE) {\n\t\t\tu8 segmentation_update_map = gf_bs_read_int_log(bs, 1, \"segmentation_update_map\");\n\t\t\tif (segmentation_update_map == 1)\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"segmentation_temporal_update\");\n\t\t\tsegmentation_update_data = gf_bs_read_int_log(bs, 1, \"segmentation_update_data\");\n\t\t}\n\t\tif (segmentation_update_data == 1) {\n\t\t\tu32 i, j;\n\t\t\tfor (i = 0; i < 8/*=MAX_SEGMENTS*/; i++) {\n\t\t\t\tfor (j = 0; j < 8 /*=SEG_LVL_MAX*/; j++) {\n\t\t\t\t\tif (/*feature_enabled = */gf_bs_read_int_log_idx2(bs, 1, \"feature_enabled\", i, j) == 1) {\n\t\t\t\t\t\ts32 val;\n\t\t\t\t\t\tu32 bitsToRead = Segmentation_Feature_Bits[j];\n\t\t\t\t\t\t//this is SEG_LVL_ALT_Q\n\t\t\t\t\t\tif (!j) seg_features_SEG_LVL_ALT_Q_enabled[i] = 1;",
"\t\t\t\t\t\tif (Segmentation_Feature_Signed[j] == 1) {\n\t\t\t\t\t\t\tval = gf_bs_read_int_log_idx2(bs, 1 + bitsToRead, \"signed_feature_value\", i, j);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tval = gf_bs_read_int_log_idx2(bs, bitsToRead, \"feature_value\", i, j);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!j) seg_features_SEG_LVL_ALT_Q[i] = val;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//ignore all init steps\n\t\t}",
"\t}",
"\t//delta_q_params():\n\t/*u8 delta_q_res = 0;*/\n\tu8 delta_q_present = 0;\n\tif (base_q_idx > 0) {\n\t\tdelta_q_present = gf_bs_read_int_log(bs, 1, \"delta_q_present\");\n\t}\n\tif (delta_q_present) {\n\t\tgf_bs_read_int_log(bs, 2, \"delta_q_res\");\n\t}",
"\t//delta_lf_params():\n\tu8 delta_lf_present = 0;\n\t/*u8 delta_lf_res = 0;\n\tu8 delta_lf_multi = 0;*/\n\tif (delta_q_present) {\n\t\tif (!allow_intrabc) {\n\t\t\tdelta_lf_present = gf_bs_read_int_log(bs, 1, \"delta_lf_present\");\n\t\t}\n\t\tif (delta_lf_present) {\n\t\t\tgf_bs_read_int_log(bs, 2, \"delta_lf_res\");\n\t\t\tgf_bs_read_int_log(bs, 1, \"delta_lf_multi\");\n\t\t}\n\t}",
"\t//init lossless stuff!\n\tu8 CodedLossless = 1;\n\tfor (idx = 0; idx < 8; idx++) {\n\t\tu8 qindex = av1_get_qindex(GF_TRUE, idx, base_q_idx, delta_q_present, 0/*CurrentQIndex always ignored at this level of parsin*/, segmentation_enabled, seg_features_SEG_LVL_ALT_Q_enabled, seg_features_SEG_LVL_ALT_Q);\n\t\tBool LosslessArray = (qindex == 0) && (DeltaQYDc == 0) && (DeltaQUAc == 0) && (DeltaQUDc == 0) && (DeltaQVAc == 0) && (DeltaQVDc == 0);\n\t\tif (!LosslessArray)\n\t\t\tCodedLossless = 0;\n\t}\n\tBool AllLossless = CodedLossless && (state->width == state->UpscaledWidth);",
"\t//loop_filter_params():\n\tif (!CodedLossless && !allow_intrabc) {\n\t\tu8 loop_filter_level_0 = gf_bs_read_int_log(bs, 6, \"loop_filter_level_0\");\n\t\tu8 loop_filter_level_1 = gf_bs_read_int_log(bs, 6, \"loop_filter_level_1\");\n\t\tif (!state->config->monochrome) {\n\t\t\tif (loop_filter_level_0 || loop_filter_level_1) {\n\t\t\t\tgf_bs_read_int_log(bs, 6, \"loop_filter_level_2\");\n\t\t\t\tgf_bs_read_int_log(bs, 6, \"loop_filter_level_3\");\n\t\t\t}\n\t\t}\n\t\tgf_bs_read_int_log(bs, 3, \"loop_filter_sharpness\");\n\t\tu8 loop_filter_delta_enabled = gf_bs_read_int_log(bs, 1, \"loop_filter_delta_enabled\");\n\t\tif (loop_filter_delta_enabled == 1) {\n\t\t\tu8 loop_filter_delta_update = gf_bs_read_int_log(bs, 1, \"loop_filter_delta_update\");\n\t\t\tif (loop_filter_delta_update) {\n\t\t\t\tu32 i;\n\t\t\t\tfor (i = 0; i < 8/*TOTAL_REFS_PER_FRAME*/; i++) {\n\t\t\t\t\tu8 update_ref_delta = gf_bs_read_int_log_idx(bs, 1, \"update_ref_delta\", i);\n\t\t\t\t\tif (update_ref_delta == 1) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 1 + 6, \"loop_filter_ref_deltas\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (i = 0; i < 2; i++) {\n\t\t\t\t\tu8 update_mode_delta = gf_bs_read_int_log_idx(bs, 1, \"update_mode_delta\", i);\n\t\t\t\t\tif (update_mode_delta) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 1 + 6, \"loop_filter_mode_deltas\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//cdef_params( ):\n\tif (!CodedLossless && !allow_intrabc && state->enable_cdef) {\n\t\tgf_bs_read_int_log(bs, 2, \"cdef_damping_minus_3\");\n\t\tu8 cdef_bits = gf_bs_read_int_log(bs, 2, \"cdef_bits\");\n\t\tu32 i, num_cd = 1 << cdef_bits;\n\t\tfor (i = 0; i < num_cd; i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, 4, \"cdef_y_pri_strength\", i);\n\t\t\tgf_bs_read_int_log_idx(bs, 2, \"cdef_y_sec_strength\", i);\n\t\t\tif (!state->config->monochrome) {\n\t\t\t\tgf_bs_read_int_log_idx(bs, 4, \"cdef_uv_pri_strength\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 2, \"cdef_uv_sec_strength\", i);\n\t\t\t}\n\t\t}\n\t}",
"\t//lr_params( ) :\n\tif (!AllLossless && !allow_intrabc && state->enable_restoration) {\n\t\tu32 i, nb_planes = state->config->monochrome ? 1 : 3;\n\t\tu8 UsesLr = 0;\n\t\tu8 usesChromaLr = 0;\n\t\tfor (i = 0; i < nb_planes; i++) {\n\t\t\tu8 lr_type = gf_bs_read_int_log_idx(bs, 2, \"lr_type\", i);\n\t\t\t//FrameRestorationType[i] = Remap_Lr_Type[lr_type]\n\t\t\tif (lr_type != AV1_RESTORE_NONE) {\n\t\t\t\tUsesLr = 1;\n\t\t\t\tif (i > 0) {\n\t\t\t\t\tusesChromaLr = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (UsesLr) {\n\t\t\tif (state->use_128x128_superblock) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"lr_unit_shift_minus_1\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tu8 lr_unit_shift = gf_bs_read_int_log(bs, 1, \"lr_unit_shift\");\n\t\t\t\tif (lr_unit_shift) {\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"lr_unit_extra_shift\");\n\t\t\t\t\t//lr_unit_shift += lr_unit_extra_shift;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (state->config->chroma_subsampling_x && state->config->chroma_subsampling_y && usesChromaLr) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"lr_uv_shift\");\n\t\t\t}\n\t\t}\n\t}\n\t//read_tx_mode():\n\tif (CodedLossless == 1) {\n\t}\n\telse {\n\t\tgf_bs_read_int_log(bs, 1, \"tx_mode_select\");\n\t}",
"\t//frame_reference_mode( ):\n\tu8 reference_select = 0;\n\tif (FrameIsIntra) {\n\t}\n\telse {\n\t\treference_select = gf_bs_read_int_log(bs, 1, \"reference_select\");\n\t}",
"\t//skip_mode_params( ):\n\tu8 skipModeAllowed = 0;\n\tif (FrameIsIntra || !reference_select || !state->enable_order_hint) {\n\t}\n\telse {\n\t\tu32 i;\n\t\ts32 forwardIdx = -1;\n\t\ts32 backwardIdx = -1;\n\t\ts32 forwardHint = 0;\n\t\ts32 backwardHint = 0;\n\t\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\t\tu8 refHint = state->RefOrderHint[ref_frame_idx[i]];\n\t\t\tif (av1_get_relative_dist(refHint, frame_state->order_hint, state) < 0) {\n\t\t\t\tif (forwardIdx < 0 || av1_get_relative_dist(refHint, forwardHint, state) > 0) {\n\t\t\t\t\tforwardIdx = i;\n\t\t\t\t\tforwardHint = refHint;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (av1_get_relative_dist(refHint, frame_state->order_hint, state) > 0) {\n\t\t\t\tif (backwardIdx < 0 || av1_get_relative_dist(refHint, backwardHint, state) < 0) {\n\t\t\t\t\tbackwardIdx = i;\n\t\t\t\t\tbackwardHint = refHint;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (forwardIdx < 0) {\n\t\t\tskipModeAllowed = 0;\n\t\t}\n\t\telse if (backwardIdx >= 0) {\n\t\t\tskipModeAllowed = 1;\n\t\t\t//SkipModeFrame[0] = AV1_LAST_FRAME + MIN(forwardIdx, backwardIdx);\n\t\t\t//SkipModeFrame[1] = AV1_LAST_FRAME + MAX(forwardIdx, backwardIdx);\n\t\t}\n\t\telse {\n\t\t\ts32 secondForwardIdx = -1;\n\t\t\ts32 secondForwardHint = 0;\n\t\t\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\t\t\tu8 refHint = state->RefOrderHint[ref_frame_idx[i]];\n\t\t\t\tif (av1_get_relative_dist(refHint, forwardHint, state) < 0) {\n\t\t\t\t\tif (secondForwardIdx < 0 || av1_get_relative_dist(refHint, secondForwardHint, state) > 0) {\n\t\t\t\t\t\tsecondForwardIdx = i;\n\t\t\t\t\t\tsecondForwardHint = refHint;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (secondForwardIdx < 0) {\n\t\t\t\tskipModeAllowed = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tskipModeAllowed = 1;\n\t\t\t\t//SkipModeFrame[ 0 ] = LAST_FRAME + Min(forwardIdx, secondForwardIdx)\n\t\t\t\t//SkipModeFrame[ 1 ] = LAST_FRAME + Max(forwardIdx, secondForwardIdx)\n\t\t\t}\n\t\t}\n\t}\n\tif (skipModeAllowed) {\n\t\tgf_bs_read_int_log(bs, 1, \"skip_mode_present\");\n\t}",
"\n\tif (FrameIsIntra || error_resilient_mode || !state->enable_warped_motion) {",
"\t}\n\telse {\n\t\tgf_bs_read_int_log(bs, 1, \"allow_warped_motion\");\n\t}",
"\tgf_bs_read_int_log(bs, 1, \"reduced_tx\");",
"\t//global_motion_params( )\n\tu32 ref;\n\tfor (ref = AV1_LAST_FRAME; ref <= AV1_ALTREF_FRAME; ref++) {\n\t\tu32 i;\n\t\tfor (i = 0; i < 6; i++) {\n\t\t\tstate->GmParams.coefs[ref][i] = ((i % 3 == 2) ? 1 << WARPEDMODEL_PREC_BITS : 0);\n\t\t}\n\t}\n\tif (!FrameIsIntra) {\n\t\tu32 refs;\n\t\tfor (refs = AV1_LAST_FRAME; refs <= AV1_ALTREF_FRAME; refs++) {\n\t\t\tu8 type = AV1_GMC_IDENTITY;\n\t\t\tBool is_global = gf_bs_read_int_log_idx(bs, 1, \"is_global\", refs);\n\t\t\tif (is_global) {\n\t\t\t\tBool is_rot_zoom = gf_bs_read_int_log_idx(bs, 1, \"is_rot_zoom\", refs);\n\t\t\t\tif (is_rot_zoom) {\n\t\t\t\t\ttype = AV1_GMC_ROTZOOM;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tBool is_trans = gf_bs_read_int_log_idx(bs, 1, \"is_translation\", refs);\n\t\t\t\t\ttype = is_trans ? AV1_GMC_TRANSLATION : AV1_GMC_AFFINE;",
"\t\t\t\t}\n\t\t\t}",
"\t\t\tif (type >= AV1_GMC_ROTZOOM) {\n\t\t\t\tav1_read_global_param(state, bs, type, refs, 2);\n\t\t\t\tav1_read_global_param(state, bs, type, refs, 3);\n\t\t\t\tif (type == AV1_GMC_AFFINE) {\n\t\t\t\t\tav1_read_global_param(state, bs, type, refs, 4);\n\t\t\t\t\tav1_read_global_param(state, bs, type, refs, 5);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstate->GmParams.coefs[refs][4] = -state->GmParams.coefs[refs][3];\n\t\t\t\t\tstate->GmParams.coefs[refs][5] = state->GmParams.coefs[refs][2];",
"\t\t\t\t}\n\t\t\t}\n\t\t\tif (type >= AV1_GMC_TRANSLATION) {\n\t\t\t\tav1_read_global_param(state, bs, type, refs, 0);\n\t\t\t\tav1_read_global_param(state, bs, type, refs, 1);\n\t\t\t}\n\t\t}\n\t}",
"\t//film_grain_params()\n\tif (!state->film_grain_params_present || (!state->frame_state.show_frame && !showable_frame)) {\n\t}\n\telse {\n\t\tu8 apply_grain = gf_bs_read_int_log(bs, 1, \"apply_grain\");\n\t\tif (apply_grain) {\n\t\t\tgf_bs_read_int_log(bs, 16, \"grain_seed\");\n\t\t\tu8 update_grain = 1;\n\t\t\tif (state->frame_state.frame_type == AV1_INTER_FRAME) {\n\t\t\t\tupdate_grain = gf_bs_read_int_log(bs, 1, \"update_grain\");\n\t\t\t}\n\t\t\tif (!update_grain) {\n\t\t\t\tgf_bs_read_int_log(bs, 3, \"film_grain_params_ref_idx\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tu32 i, num_y_points = gf_bs_read_int_log(bs, 4, \"num_y_points\");\n\t\t\t\tfor (i = 0; i < num_y_points; i++) {\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_y_value\", i);\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_y_scaling\", i);\n\t\t\t\t}\n\t\t\t\tu8 chroma_scaling_from_luma = 0;\n\t\t\t\tif (!state->config->monochrome)\n\t\t\t\t\tchroma_scaling_from_luma = gf_bs_read_int_log(bs, 1, \"chroma_scaling_from_luma\");",
"\t\t\t\tu8 num_cb_points = 0;\n\t\t\t\tu8 num_cr_points = 0;\n\t\t\t\tif (state->config->monochrome || chroma_scaling_from_luma ||\n\t\t\t\t\t((state->config->chroma_subsampling_x == 1) && (state->config->chroma_subsampling_y == 1) && (num_y_points == 0))\n\t\t\t\t\t) {\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnum_cb_points = gf_bs_read_int_log(bs, 4, \"num_cb_points\");\n\t\t\t\t\tfor (i = 0; i < num_cb_points; i++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_cb_value\", i);\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_cb_scaling\", i);\n\t\t\t\t\t}\n\t\t\t\t\tnum_cr_points = gf_bs_read_int_log(bs, 4, \"num_cr_points\");\n\t\t\t\t\tfor (i = 0; i < num_cr_points; i++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_cr_value\", i);\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_cr_scaling\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_bs_read_int_log(bs, 2, \"grain_scaling_minus_8\");\n\t\t\t\tu8 ar_coeff_lag = gf_bs_read_int_log(bs, 2, \"ar_coeff_lag\");\n\t\t\t\tu16 numPosLuma = 2 * ar_coeff_lag * (ar_coeff_lag + 1);\n\t\t\t\tu16 numPosChroma = numPosLuma;\n\t\t\t\tif (num_y_points) {\n\t\t\t\t\tnumPosChroma = numPosLuma + 1;\n\t\t\t\t\tfor (i = 0; i < numPosLuma; i++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"ar_coeffs_y_plus_128\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (chroma_scaling_from_luma || num_cb_points) {\n\t\t\t\t\tfor (i = 0; i < numPosChroma; i++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"ar_coeffs_cb_plus_128\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (chroma_scaling_from_luma || num_cr_points) {\n\t\t\t\t\tfor (i = 0; i < numPosChroma; i++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"ar_coeffs_cr_plus_128\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_bs_read_int_log(bs, 2, \"ar_coeff_shift_minus_6\");\n\t\t\t\tgf_bs_read_int_log(bs, 2, \"grain_scale_shift\");\n\t\t\t\tif (num_cb_points) {\n\t\t\t\t\tgf_bs_read_int_log(bs, 8, \"cb_mult\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 8, \"cb_luma_mult\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 9, \"cb_offset\");\n\t\t\t\t}\n\t\t\t\tif (num_cr_points) {\n\t\t\t\t\tgf_bs_read_int_log(bs, 8, \"cr_mult\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 8, \"cr_luma_mult\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 9, \"cr_offset\");\n\t\t\t\t}\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"overlap_flag\");\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"clip_to_restricted_range\");\n\t\t\t}\n\t\t}\n\t}",
"\t//end of uncompressed header !!\n}",
"GF_EXPORT\nvoid gf_av1_init_state(AV1State *state)\n{\n\tif (!state) return;\n\tmemset(state, 0, sizeof(AV1State));\n\tstate->color_primaries = 2;\n\tstate->transfer_characteristics = 2;\n\tstate->matrix_coefficients = 2;\n}",
"GF_EXPORT\nvoid gf_av1_reset_state(AV1State *state, Bool is_destroy)\n{\n\tGF_List *l1, *l2;",
"\tif (state->frame_state.header_obus) {\n\t\twhile (gf_list_count(state->frame_state.header_obus)) {\n\t\t\tGF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.header_obus);\n\t\t\tif (a->obu) gf_free(a->obu);\n\t\t\tgf_free(a);\n\t\t}\n\t}",
"\tif (state->frame_state.frame_obus) {\n\t\twhile (gf_list_count(state->frame_state.frame_obus)) {\n\t\t\tGF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.frame_obus);\n\t\t\tif (a->obu) gf_free(a->obu);\n\t\t\tgf_free(a);\n\t\t}\n\t}\n\tl1 = state->frame_state.frame_obus;\n\tl2 = state->frame_state.header_obus;\n\tmemset(&state->frame_state, 0, sizeof(AV1StateFrame));\n\tstate->frame_state.is_first_frame = GF_TRUE;",
"\tif (is_destroy) {\n\t\tgf_list_del(l1);\n\t\tgf_list_del(l2);\n\t\tif (state->bs) {\n\t\t\tu32 size;\n\t\t\tgf_bs_get_content_no_truncate(state->bs, &state->frame_obus, &size, &state->frame_obus_alloc);\n\t\t\tgf_bs_del(state->bs);\n\t\t}\n\t\tstate->bs = NULL;\n\t}\n\telse {\n\t\tstate->frame_state.frame_obus = l1;\n\t\tstate->frame_state.header_obus = l2;\n\t\tif (state->bs)\n\t\t\tgf_bs_seek(state->bs, 0);\n\t}\n}",
"static GF_Err av1_parse_tile_group(GF_BitStream *bs, AV1State *state, u64 obu_start, u64 obu_size)\n{\n\tu32 TileNum, tg_start = 0, tg_end = 0;\n\tBool numTiles = state->tileCols * state->tileRows;\n\tBool tile_start_and_end_present_flag = GF_FALSE;\n\tGF_Err e = GF_OK;\n\tif (numTiles > 1)\n\t\ttile_start_and_end_present_flag = gf_bs_read_int_log(bs, 1, \"tile_start_and_end_present_flag\");",
"\tif (numTiles == 1 || !tile_start_and_end_present_flag) {\n\t\ttg_start = 0;\n\t\ttg_end = numTiles - 1;\n\t\t/*state->frame_state.tg[0].start_idx = 0;\n\t\tstate->frame_state.tg[0].end_idx = numTiles - 1;*/\n\t}\n\telse {\n\t\tu32 tileBits = state->tileColsLog2 + state->tileRowsLog2;\n\t\t/*state->frame_state.tg[state->frame_state.tg_idx].start_idx*/ tg_start = gf_bs_read_int_log(bs, tileBits, \"tg_start\");\n\t\t/*state->frame_state.tg[state->frame_state.tg_idx].end_idx*/ tg_end = gf_bs_read_int_log(bs, tileBits, \"tg_end\");\n\t}\n\t/*state->frame_state.tg_idx++;*/",
"\tgf_bs_align(bs);",
"\tif (tg_end >= GF_ARRAY_LENGTH(state->frame_state.tiles))\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;",
"\tstate->frame_state.nb_tiles_in_obu = 0;\n\tfor (TileNum = tg_start; TileNum <= tg_end; TileNum++) {\n\t\tu32 tile_start_offset, tile_size;\n\t\t/*u32 tileRow = TileNum / state->tileCols;\n\t\tu32 tileCol = TileNum % state->tileCols;*/\n\t\tBool lastTile = TileNum == tg_end;\n\t\tu64 pos = gf_bs_get_position(bs);\n\t\tif (lastTile) {\n\t\t\ttile_start_offset = (u32)(pos - obu_start);\n\t\t\ttile_size = (u32)(obu_size - (pos - obu_start));\n\t\t}\n\t\telse {\n\t\t\tu64 tile_size_minus_1 = aom_av1_le(bs, state->tile_size_bytes, \"tile_size_minus_1\");\n\t\t\tpos = gf_bs_get_position(bs);\n\t\t\ttile_start_offset = (u32)(pos - obu_start);\n\t\t\ttile_size = (u32)(tile_size_minus_1 + 1/* + state->tile_size_bytes*/);\n\t\t}",
"\n\t\tif (tile_start_offset + tile_size > obu_size) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] Error parsing tile group, tile %d start %d + size %d exceeds OBU length %d\\n\", TileNum, tile_start_offset, tile_size, obu_size));\n\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\tbreak;\n\t\t}",
"\t\tstate->frame_state.tiles[state->frame_state.nb_tiles_in_obu].obu_start_offset = tile_start_offset;\n\t\tstate->frame_state.tiles[state->frame_state.nb_tiles_in_obu].size = tile_size;\n\t\tgf_bs_skip_bytes(bs, tile_size);\n\t\tstate->frame_state.nb_tiles_in_obu++;\n\t}\n\tif (tg_end == numTiles - 1) {\n\t\tav1_decode_frame_wrapup(state);\n\t}\n\treturn e;\n}",
"static void av1_parse_frame_header(GF_BitStream *bs, AV1State *state)\n{\n\tAV1StateFrame *frame_state = &state->frame_state;\n\tif (frame_state->seen_frame_header == GF_FALSE) {\n\t\tu64 pos = gf_bs_get_position(bs);\n\t\tstate->frame_state.show_existing_frame = GF_FALSE;\n\t\tframe_state->seen_frame_header = GF_TRUE;\n\t\tav1_parse_uncompressed_header(bs, state);\n\t\tstate->frame_state.is_first_frame = GF_FALSE;\n\t\tstate->frame_state.uncompressed_header_bytes = (u32) (gf_bs_get_position(bs) - pos);",
"\t\tif (state->frame_state.show_existing_frame) {\n\t\t\tav1_decode_frame_wrapup(state);\n\t\t\tframe_state->seen_frame_header = GF_FALSE;\n\t\t}\n\t\telse {\n\t\t\t//TileNum = 0;\n\t\t\tframe_state->seen_frame_header = GF_TRUE;\n\t\t}\n\t}\n}",
"static GF_Err av1_parse_frame(GF_BitStream *bs, AV1State *state, u64 obu_start, u64 obu_size)\n{\n\tav1_parse_frame_header(bs, state);\n\t//byte alignment\n\tgf_bs_align(bs);\n\treturn av1_parse_tile_group(bs, state, obu_start, obu_size);\n}",
"static void on_aom_av1_eos(void *_state)\n{\n\tAV1State *state = (AV1State *)_state;\n\tstate->bs_overread = GF_TRUE;\n}",
"GF_EXPORT\nGF_Err gf_av1_parse_obu(GF_BitStream *bs, ObuType *obu_type, u64 *obu_size, u32 *obu_hdr_size, AV1State *state)\n{\n\tGF_Err e = GF_OK;\n\tu32 i, hdr_size;\n\tu64 pos = gf_bs_get_position(bs);",
"\tif (!bs || !obu_type || !state)\n\t\treturn GF_BAD_PARAM;",
"\tstate->bs_overread = GF_FALSE;\n\tgf_bs_set_eos_callback(bs, on_aom_av1_eos, state);",
"\tstate->obu_extension_flag = state->obu_has_size_field = 0;\n\tstate->temporal_id = state->spatial_id = 0;\n\tstate->frame_state.uncompressed_header_bytes = 0;\n\te = gf_av1_parse_obu_header(bs, obu_type, &state->obu_extension_flag, &state->obu_has_size_field, &state->temporal_id, &state->spatial_id);\n\tif (e)\n\t\treturn e;",
"\tif (state->obu_has_size_field) {\n\t\t*obu_size = (u32)gf_av1_leb128_read(bs, NULL);\n\t}\n\telse {\n\t\tif (*obu_size >= 1 + state->obu_extension_flag) {\n\t\t\t*obu_size = *obu_size - 1 - state->obu_extension_flag;\n\t\t}\n\t\telse {\n\t\t\tGF_LOG(state->config ? GF_LOG_WARNING : GF_LOG_DEBUG, GF_LOG_CODING, (\"[AV1] computed OBU size \"LLD\" (input value = \"LLU\"). Skipping.\\n\", *obu_size - 1 - state->obu_extension_flag, *obu_size));\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t}\n\thdr_size = (u32)(gf_bs_get_position(bs) - pos);\n\tif ((gf_bs_available(bs) < *obu_size) || state->bs_overread) {\n\t\tgf_bs_seek(bs, pos);\n\t\treturn GF_BUFFER_TOO_SMALL;\n\t}\n\t*obu_size += hdr_size;\n\tif (obu_hdr_size) *obu_hdr_size = hdr_size;",
"\n\tif (*obu_type != OBU_SEQUENCE_HEADER && *obu_type != OBU_TEMPORAL_DELIMITER &&\n\t\tstate->OperatingPointIdc != 0 && state->obu_extension_flag == 1)\n\t{\n\t\tu32 inTemporalLayer = (state->OperatingPointIdc >> state->temporal_id) & 1;\n\t\tu32 inSpatialLayer = (state->OperatingPointIdc >> (state->spatial_id + 8)) & 1;\n\t\tif (!inTemporalLayer || !inSpatialLayer) {\n\t\t\t*obu_type = -1;\n\t\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\t\treturn GF_OK;\n\t\t}\n\t}",
"\te = GF_OK;",
"\t/* for AVIF a1lx */\n\tfor (i = state->spatial_id; i < 4; i++) {\n\t\tstate->layer_size[i] = (u32) (pos + *obu_size);\n\t}",
"\tswitch (*obu_type) {\n\tcase OBU_SEQUENCE_HEADER:\n\t\tav1_parse_sequence_header_obu(bs, state);\n\t\tif (gf_bs_get_position(bs) > pos + *obu_size) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] Sequence header parsing consumed too many bytes !\\n\"));\n\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;",
"\tcase OBU_METADATA:\n#if 0\n\t\t//TODO + sample groups\n\t\tconst ObuMetadataType metadata_type = (u32)read_leb128(bs, NULL); we should check for 16 bits limit(AV1MetadataSampleGroupEntry) for ISOBMFF bindings, see https ://github.com/AOMediaCodec/av1-isobmff/pull/86#issuecomment-416659538\n\t\tif (metadata_type == OBU_METADATA_TYPE_ITUT_T35) {\n\t\t}\n\t\telse if (metadata_type == OBU_METADATA_TYPE_HDR_CLL) {\n\t\t}\n\t\telse if (metadata_type == OBU_METADATA_TYPE_HDR_MDCV) {\n\t\t}\n\t\telse if (metadata_type == OBU_METADATA_TYPE_SCALABILITY) {\n\t\t}\n\t\telse if (metadata_type == METADATA_TYPE_TIMECODE) {\n\t\t}\n#endif\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CODING, (\"[AV1] parsing for metadata is not implemented. Forwarding.\\n\"));",
"\t\tif (gf_bs_get_position(bs) > pos + *obu_size) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] Metadata parsing consumed too many bytes !\\n\"));\n\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;",
"\tcase OBU_FRAME_HEADER:\n\tcase OBU_REDUNDANT_FRAME_HEADER:\n\t\tif (state->config) {\n\t\t\tav1_parse_frame_header(bs, state);\n\t\t\tif (gf_bs_get_position(bs) > pos + *obu_size) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] Frame header parsing consumed too many bytes !\\n\"));\n\t\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t}\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;\n\tcase OBU_FRAME:\n\t\te = av1_parse_frame(bs, state, pos, *obu_size);\n\t\tif (gf_bs_get_position(bs) != pos + *obu_size) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] Frame parsing did not consume the right number of bytes !\\n\"));\n\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;\n\tcase OBU_TILE_GROUP:\n\t\tif (state->config) {\n\t\t\te = av1_parse_tile_group(bs, state, pos, *obu_size);\n\t\t\tif (gf_bs_get_position(bs) != pos + *obu_size) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] Tile group parsing did not consume the right number of bytes !\\n\"));\n\t\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t}\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;\n\tcase OBU_TEMPORAL_DELIMITER:\n\t\tstate->frame_state.seen_frame_header = GF_FALSE;\n\tcase OBU_PADDING:\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;\n\tdefault:\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] unknown OBU type %u (size \"LLU\"). Skipping.\\n\", *obu_type, *obu_size));\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;\n\t}\n\treturn e;\n}",
"\nGF_EXPORT\nGF_Err gf_media_prores_parse_bs(GF_BitStream *bs, GF_ProResFrameInfo *prores_frame)\n{\n\tu32 i, j;\n\tu64 start, pos;\n\tmemset(prores_frame, 0, sizeof(GF_ProResFrameInfo));",
"\tstart = gf_bs_get_position(bs);\n\tif (gf_bs_available(bs) < 10)\n\t\treturn GF_BUFFER_TOO_SMALL;",
"\tprores_frame->frame_size = gf_bs_read_u32(bs);\n\tprores_frame->frame_identifier = gf_bs_read_u32(bs);\n\tif (prores_frame->frame_identifier != GF_4CC('i','c','p','f')) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[ProRes] Invalid frame identifier, expected \\\"icpf\\\" got \\\"%s\\\"\\n\", gf_4cc_to_str(prores_frame->frame_identifier) ));\n\t\tgf_bs_seek(bs, start);\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\t/*parse frame header*/\n\tpos = gf_bs_get_position(bs);\n\tprores_frame->frame_hdr_size = gf_bs_read_u16(bs);\n\tif (gf_bs_available(bs) + 2 < prores_frame->frame_hdr_size) {\n\t\tgf_bs_seek(bs, start);\n\t\treturn GF_BUFFER_TOO_SMALL;\n\t}\n\tgf_bs_read_u8(bs);\n\tprores_frame->version = gf_bs_read_u8(bs);\n\tprores_frame->encoder_id = gf_bs_read_u32(bs);\n\tprores_frame->width = gf_bs_read_u16(bs);\n\tprores_frame->height = gf_bs_read_u16(bs);\n\tprores_frame->chroma_format = gf_bs_read_int(bs, 2);\n\tgf_bs_read_int(bs, 2);\n\tprores_frame->interlaced_mode = gf_bs_read_int(bs, 2);\n\tgf_bs_read_int(bs, 2);\n\tprores_frame->aspect_ratio_information = gf_bs_read_int(bs, 4);\n\tprores_frame->framerate_code = gf_bs_read_int(bs, 4);\n\tprores_frame->color_primaries = gf_bs_read_u8(bs);\n\tprores_frame->transfer_characteristics = gf_bs_read_u8(bs);\n\tprores_frame->matrix_coefficients = gf_bs_read_u8(bs);\n\tgf_bs_read_int(bs, 4);\n\tprores_frame->alpha_channel_type = gf_bs_read_int(bs, 4);\n\tgf_bs_read_int(bs, 14);\n\tprores_frame->load_luma_quant_matrix = gf_bs_read_int(bs, 1);\n\tprores_frame->load_chroma_quant_matrix = gf_bs_read_int(bs, 1);\n\tif (prores_frame->load_luma_quant_matrix) {\n\t\tfor (i=0; i<8; i++) {\n\t\t\tfor (j=0; j<8; j++) {\n\t\t\t\tprores_frame->luma_quant_matrix[i][j] = gf_bs_read_u8(bs);\n\t\t\t}\n\t\t}\n\t}\n\tif (prores_frame->load_chroma_quant_matrix) {\n\t\tfor (i=0; i<8; i++) {\n\t\t\tfor (j=0; j<8; j++) {\n\t\t\t\tprores_frame->chroma_quant_matrix[i][j] = gf_bs_read_u8(bs);\n\t\t\t}\n\t\t}\n\t}\n\tpos = gf_bs_get_position(bs) - pos;\n\tif (pos != prores_frame->frame_hdr_size) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[ProRes] Invalid frame header size, expected %d got %d\\n\", prores_frame->frame_hdr_size, (u32) pos));\n\t\tgf_bs_seek(bs, start);\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\tprores_frame->nb_pic = ((prores_frame->interlaced_mode==1) || (prores_frame->interlaced_mode==2)) ? 2 : 1;\n\tgf_bs_seek(bs, start);",
"\treturn GF_OK;\n}",
"#endif /*GPAC_DISABLE_AV_PARSERS*/",
"GF_EXPORT\nu8 gf_mp3_version(u32 hdr)\n{\n\treturn ((hdr >> 19) & 0x3);\n}",
"GF_EXPORT\nconst char *gf_mp3_version_name(u32 hdr)\n{\n\tu32 v = gf_mp3_version(hdr);\n\tswitch (v) {\n\tcase 0:\n\t\treturn \"MPEG-2.5\";\n\tcase 1:\n\t\treturn \"Reserved\";\n\tcase 2:\n\t\treturn \"MPEG-2\";\n\tcase 3:\n\t\treturn \"MPEG-1\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n}",
"#ifndef GPAC_DISABLE_AV_PARSERS",
"GF_EXPORT\nu8 gf_mp3_layer(u32 hdr)\n{\n\treturn 4 - (((hdr >> 17) & 0x3));\n}",
"GF_EXPORT\nu8 gf_mp3_num_channels(u32 hdr)\n{\n\tif (((hdr >> 6) & 0x3) == 3) return 1;\n\treturn 2;\n}",
"GF_EXPORT\nu16 gf_mp3_sampling_rate(u32 hdr)\n{\n\tu16 res;\n\t/* extract the necessary fields from the MP3 header */\n\tu8 version = gf_mp3_version(hdr);\n\tu8 sampleRateIndex = (hdr >> 10) & 0x3;",
"\tswitch (sampleRateIndex) {\n\tcase 0:\n\t\tres = 44100;\n\t\tbreak;\n\tcase 1:\n\t\tres = 48000;\n\t\tbreak;\n\tcase 2:\n\t\tres = 32000;\n\t\tbreak;\n\tdefault:\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[MPEG-1/2 Audio] Samplerate index not valid\\n\"));\n\t\treturn 0;\n\t}\n\t/*reserved or MPEG-1*/\n\tif (version & 1) return res;",
"\t/*MPEG-2*/\n\tres /= 2;\n\t/*MPEG-2.5*/\n\tif (version == 0) res /= 2;\n\treturn res;\n}",
"GF_EXPORT\nu16 gf_mp3_window_size(u32 hdr)\n{\n\tu8 version = gf_mp3_version(hdr);\n\tu8 layer = gf_mp3_layer(hdr);",
"\tif (layer == 3) {\n\t\tif (version == 3) return 1152;\n\t\treturn 576;\n\t}\n\tif (layer == 2) return 1152;\n\treturn 384;\n}",
"GF_EXPORT\nu8 gf_mp3_object_type_indication(u32 hdr)\n{\n\tswitch (gf_mp3_version(hdr)) {\n\tcase 3:\n\t\treturn GF_CODECID_MPEG_AUDIO;\n\tcase 2:\n\tcase 0:\n\t\treturn GF_CODECID_MPEG2_PART3;\n\tdefault:\n\t\treturn 0x00;\n\t}\n}",
"/*aligned bitrate parsing with libMAD*/",
"static\nu32 const bitrate_table[5][15] = {\n\t/* MPEG-1 */\n\t{\t0, 32000, 64000, 96000, 128000, 160000, 192000, 224000, /* Layer I */\n\t\t256000, 288000, 320000, 352000, 384000, 416000, 448000\n\t},\n\t{\t0, 32000, 48000, 56000, 64000, 80000, 96000, 112000, /* Layer II */\n\t\t128000, 160000, 192000, 224000, 256000, 320000, 384000\n\t},\n\t{\t0, 32000, 40000, 48000, 56000, 64000, 80000, 96000, /* Layer III */\n\t\t112000, 128000, 160000, 192000, 224000, 256000, 320000\n\t},",
"\t/* MPEG-2 LSF */\n\t{\t0, 32000, 48000, 56000, 64000, 80000, 96000, 112000, /* Layer I */\n\t\t128000, 144000, 160000, 176000, 192000, 224000, 256000\n\t},\n\t{\t0, 8000, 16000, 24000, 32000, 40000, 48000, 56000, /* Layers */\n\t\t64000, 80000, 96000, 112000, 128000, 144000, 160000\n\t} /* II & III */\n};",
"\nu32 gf_mp3_bit_rate(u32 hdr)\n{\n\tu8 version = gf_mp3_version(hdr);\n\tu8 layer = gf_mp3_layer(hdr);\n\tu8 bitRateIndex = (hdr >> 12) & 0xF;\n\tu32 lidx;\n\t/*MPEG-1*/\n\tif (version & 1) {\n\t\tif (!layer) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[MPEG-1/2 Audio] layer index not valid\\n\"));\n\t\t\treturn 0;\n\t\t}\n\t\tlidx = layer - 1;\n\t}\n\t/*MPEG-2/2.5*/\n\telse {\n\t\tlidx = 3 + (layer >> 1);\n\t}\n\tif (lidx>4) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[MPEG-1/2 Audio] layer index not valid\\n\"));\n\t\treturn 0;\n\t}\n\treturn bitrate_table[lidx][bitRateIndex];\n}",
"",
"GF_EXPORT\nu16 gf_mp3_frame_size(u32 hdr)\n{\n\tu8 version = gf_mp3_version(hdr);\n\tu8 layer = gf_mp3_layer(hdr);\n\tu32 pad = ((hdr >> 9) & 0x1) ? 1 : 0;\n\tu32 bitrate = gf_mp3_bit_rate(hdr);\n\tu32 samplerate = gf_mp3_sampling_rate(hdr);",
"\tu32 frameSize = 0;\n\tif (!samplerate || !bitrate) return 0;",
"\tif (layer == 1) {\n\t\tframeSize = ((12 * bitrate / samplerate) + pad) * 4;\n\t}\n\telse {\n\t\tu32 slots_per_frame = 144;\n\t\tif ((layer == 3) && !(version & 1)) slots_per_frame = 72;\n\t\tframeSize = (slots_per_frame * bitrate / samplerate) + pad;\n\t}\n\treturn (u16)frameSize;\n}",
"\nGF_EXPORT\nu32 gf_mp3_get_next_header(FILE* in)\n{\n\tu8 b, state = 0;\n\tu32 dropped = 0;\n\tunsigned char bytes[4];\n\tbytes[0] = bytes[1] = bytes[2] = bytes[3] = 0;",
"\twhile (1) {\n\t\tif (gf_fread(&b, 1, in) == 0) return 0;",
"\t\tif (state == 3) {\n\t\t\tbytes[state] = b;\n\t\t\treturn GF_4CC((u32)bytes[0], bytes[1], bytes[2], bytes[3]);\n\t\t}\n\t\tif (state == 2) {\n\t\t\tif (((b & 0xF0) == 0) || ((b & 0xF0) == 0xF0) || ((b & 0x0C) == 0x0C)) {\n\t\t\t\tif (bytes[1] == 0xFF) state = 1;\n\t\t\t\telse state = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 3;\n\t\t\t}\n\t\t}\n\t\tif (state == 1) {\n\t\t\tif (((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = 0;\n\t\t\t}\n\t\t}",
"\t\tif (state == 0) {\n\t\t\tif (b == 0xFF) {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif ((dropped == 0) && ((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {\n\t\t\t\t\tbytes[0] = (u8)0xFF;\n\t\t\t\t\tbytes[1] = b;\n\t\t\t\t\tstate = 2;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tdropped++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}",
"GF_EXPORT\nu32 gf_mp3_get_next_header_mem(const u8 *buffer, u32 size, u32 *pos)\n{\n\tu32 cur;\n\tu8 b, state = 0;\n\tu32 dropped = 0;\n\tunsigned char bytes[4];\n\tbytes[0] = bytes[1] = bytes[2] = bytes[3] = 0;",
"\tcur = 0;\n\t*pos = 0;\n\twhile (cur < size) {\n\t\tb = (u8)buffer[cur];\n\t\tcur++;",
"\t\tif (state == 3) {\n\t\t\tu32 val;\n\t\t\tbytes[state] = b;\n\t\t\tval = GF_4CC((u32)bytes[0], bytes[1], bytes[2], bytes[3]);\n\t\t\tif (gf_mp3_frame_size(val)) {\n\t\t\t\t*pos = dropped;\n\t\t\t\treturn val;\n\t\t\t}\n\t\t\tstate = 0;\n\t\t\tdropped = cur;\n\t\t}\n\t\tif (state == 2) {\n\t\t\tif (((b & 0xF0) == 0) || ((b & 0xF0) == 0xF0) || ((b & 0x0C) == 0x0C)) {\n\t\t\t\tif (bytes[1] == 0xFF) {\n\t\t\t\t\tstate = 1;\n\t\t\t\t\tdropped += 1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstate = 0;\n\t\t\t\t\tdropped = cur;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 3;\n\t\t\t}\n\t\t}\n\t\tif (state == 1) {\n\t\t\tif (((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = 0;\n\t\t\t\tdropped = cur;\n\t\t\t}\n\t\t}",
"\t\tif (state == 0) {\n\t\t\tif (b == 0xFF) {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdropped++;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}",
"#endif /*GPAC_DISABLE_AV_PARSERS*/",
"\nGF_EXPORT\nBool gf_avc_is_rext_profile(u8 profile_idc)\n{\n\tswitch (profile_idc) {\n\tcase 100:\n\tcase 110:\n\tcase 122:\n\tcase 244:\n\tcase 44:\n\tcase 83:\n\tcase 86:\n\tcase 118:\n\tcase 128:\n\tcase 138:\n\tcase 139:\n\tcase 134:\n\tcase 135:\n\t\treturn GF_TRUE;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n}",
"GF_EXPORT\nconst char *gf_avc_get_profile_name(u8 video_prof)\n{\n\tswitch (video_prof) {\n\tcase 0x42:\n\t\treturn \"Baseline\";\n\tcase 0x4D:\n\t\treturn \"Main\";\n\tcase 0x53:\n\t\treturn \"Scalable Baseline\";\n\tcase 0x56:\n\t\treturn \"Scalable High\";\n\tcase 0x58:\n\t\treturn \"Extended\";\n\tcase 0x64:\n\t\treturn \"High\";\n\tcase 0x6E:\n\t\treturn \"High 10\";\n\tcase 0x7A:\n\t\treturn \"High 4:2:2\";\n\tcase 0x90:\n\tcase 0xF4:\n\t\treturn \"High 4:4:4\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n}",
"GF_EXPORT\nconst char *gf_hevc_get_profile_name(u8 video_prof)\n{\n\tswitch (video_prof) {\n\tcase 0x01:\n\t\treturn \"Main\";\n\tcase 0x02:\n\t\treturn \"Main 10\";\n\tcase 0x03:\n\t\treturn \"Main Still Picture\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n}\nGF_EXPORT\nconst char *gf_avc_hevc_get_chroma_format_name(u8 chroma_format)\n{\n\tswitch (chroma_format) {\n\tcase 1:\n\t\treturn \"YUV 4:2:0\";\n\tcase 2:\n\t\treturn \"YUV 4:2:2\";\n\tcase 3:\n\t\treturn \"YUV 4:4:4\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n}",
"#ifndef GPAC_DISABLE_AV_PARSERS",
"u32 gf_bs_read_ue_log_idx3(GF_BitStream *bs, const char *fname, s32 idx1, s32 idx2, s32 idx3)\n{\n\tu32 val=0, code;\n\ts32 nb_lead = -1;\n\tu32 bits = 0;\n\tfor (code=0; !code; nb_lead++) {\n\t\tif (nb_lead>=32) {",
"\t\t\t//gf_bs_read_int keeps returning 0 on EOS, so if no more bits available, rbsp was truncated otherwise code is broken in rbsp)\n\t\t\t//we only test once nb_lead>=32 to avoid testing at each bit read\n\t\t\tif (!gf_bs_available(bs)) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[Core] exp-golomb read failed, not enough bits in bitstream !\\n\"));\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[Core] corrupted exp-golomb code, %d leading zeros, max 31 allowed !\\n\", nb_lead));\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n",
"\t\tcode = gf_bs_read_int(bs, 1);\n\t\tbits++;",
"",
"\t}",
"\tif (nb_lead) {\n\t\tu32 leads=1;\n\t\tval = gf_bs_read_int(bs, nb_lead);\n\t\tleads <<= nb_lead;\n\t\tleads -= 1;\n\t\tval += leads;\n//\t\tval += (1 << nb_lead) - 1;\n\t\tbits += nb_lead;\n\t}",
"\tif (fname) {\n\t\tgf_bs_log_idx(bs, bits, fname, val, idx1, idx2, idx3);\n\t}\n\treturn val;\n}",
"#define gf_bs_read_ue_log_idx2(_bs, _fname, _idx1, _idx2) gf_bs_read_ue_log_idx3(_bs, _fname, (s32) _idx1, (s32) _idx2, -1)\n#define gf_bs_read_ue_log_idx(_bs, _fname, _idx) gf_bs_read_ue_log_idx3(_bs, _fname, (s32) _idx, -1, -1)\n#define gf_bs_read_ue_log(_bs, _fname) gf_bs_read_ue_log_idx3(_bs, _fname, -1, -1, -1)",
"\nu32 gf_bs_read_ue(GF_BitStream *bs)\n{\n\treturn gf_bs_read_ue_log(bs, NULL);\n}",
"s32 gf_bs_read_se(GF_BitStream *bs)\n{\n\tu32 v = gf_bs_read_ue(bs);\n\tif ((v & 0x1) == 0) return (s32)(0 - (v >> 1));\n\treturn (v + 1) >> 1;\n}",
"s32 gf_bs_read_se_log_idx2(GF_BitStream *bs, const char *fname, s32 idx1, s32 idx2)\n{\n\ts32 res = gf_bs_read_se(bs);\n\tif (fname)\n\t\tgf_bs_log_idx(bs, -1, fname, res, idx1, idx2, -1);\n\treturn res;\n}\n#define gf_bs_read_se_log_idx(_bs, _fname, _idx) gf_bs_read_se_log_idx2(_bs, _fname, (s32) _idx, -1)\n#define gf_bs_read_se_log(_bs, _fname) gf_bs_read_se_log_idx2(_bs, _fname, -1, -1)",
"",
"void gf_bs_write_ue(GF_BitStream *bs, u32 num) {\n\ts32 length = 1;\n\ts32 temp = ++num;",
"\twhile (temp != 1) {\n\t\ttemp >>= 1;\n\t\tlength += 2;\n\t}",
"\tgf_bs_write_int(bs, 0, length >> 1);\n\tgf_bs_write_int(bs, num, (length + 1) >> 1);\n}",
"void gf_bs_write_se(GF_BitStream *bs, s32 num)\n{\n\tu32 v;\n\tif (num <= 0)\n\t\tv = (-1 * num) << 1;\n\telse\n\t\tv = (num << 1) - 1;",
"\tgf_bs_write_ue(bs, v);\n}",
"u32 gf_media_nalu_is_start_code(GF_BitStream *bs)\n{\n\tu8 s1, s2, s3, s4;\n\tBool is_sc = 0;\n\tu64 pos = gf_bs_get_position(bs);\n\ts1 = gf_bs_read_int(bs, 8);\n\ts2 = gf_bs_read_int(bs, 8);\n\tif (!s1 && !s2) {\n\t\ts3 = gf_bs_read_int(bs, 8);\n\t\tif (s3 == 0x01) is_sc = 3;\n\t\telse if (!s3) {\n\t\t\ts4 = gf_bs_read_int(bs, 8);\n\t\t\tif (s4 == 0x01) is_sc = 4;\n\t\t}\n\t}\n\tgf_bs_seek(bs, pos + is_sc);\n\treturn is_sc;\n}",
"/*read that amount of data at each IO access rather than fetching byte by byte...*/\n#define AVC_CACHE_SIZE\t4096",
"static u32 gf_media_nalu_locate_start_code_bs(GF_BitStream *bs, Bool locate_trailing)\n{\n\tu32 v, bpos, nb_cons_zeros = 0;\n\tchar avc_cache[AVC_CACHE_SIZE];\n\tu64 end, cache_start, load_size;\n\tu64 start = gf_bs_get_position(bs);\n\tif (start < 3) return 0;",
"\tload_size = 0;\n\tbpos = 0;\n\tcache_start = 0;\n\tend = 0;\n\tv = 0xffffffff;\n\twhile (!end) {\n\t\t/*refill cache*/\n\t\tif (bpos == (u32)load_size) {\n\t\t\tif (!gf_bs_available(bs)) break;\n\t\t\tload_size = gf_bs_available(bs);\n\t\t\tif (load_size > AVC_CACHE_SIZE) load_size = AVC_CACHE_SIZE;\n\t\t\tbpos = 0;\n\t\t\tcache_start = gf_bs_get_position(bs);\n\t\t\tgf_bs_read_data(bs, avc_cache, (u32)load_size);\n\t\t}\n\t\tv = ( (v<<8) & 0xFFFFFF00) | ((u32) avc_cache[bpos]);\n\t\tbpos++;",
"\t\tif (locate_trailing) {\n\t\t\tif ((v & 0x000000FF) == 0) nb_cons_zeros++;\n\t\t\telse nb_cons_zeros = 0;\n\t\t}",
"\t\tif (v == 0x00000001) end = cache_start + bpos - 4;\n\t\telse if ((v & 0x00FFFFFF) == 0x00000001) end = cache_start + bpos - 3;\n\t}",
"\tgf_bs_seek(bs, start);\n\tif (!end) end = gf_bs_get_size(bs);\n\tif (locate_trailing) {\n\t\tif (nb_cons_zeros >= 3)\n\t\t\treturn (u32)(end - start - nb_cons_zeros);\n\t}\n\treturn (u32)(end - start);\n}",
"GF_EXPORT\nu32 gf_media_nalu_next_start_code_bs(GF_BitStream *bs)\n{\n\treturn gf_media_nalu_locate_start_code_bs(bs, 0);\n}",
"GF_EXPORT\nu32 gf_media_nalu_next_start_code(const u8 *data, u32 data_len, u32 *sc_size)\n{\n\tu32 avail = data_len;\n\tconst u8 *cur = data;",
"\twhile (cur) {\n\t\tu32 v, bpos;\n\t\tu8 *next_zero = memchr(cur, 0, avail);\n\t\tif (!next_zero) return data_len;",
"\t\tv = 0xffffff00;\n\t\tbpos = (u32)(next_zero - data) + 1;\n\t\twhile (1) {\n\t\t\tu8 cval;\n\t\t\tif (bpos == (u32)data_len)\n\t\t\t\treturn data_len;",
"\t\t\tcval = data[bpos];\n\t\t\tv = ((v << 8) & 0xFFFFFF00) | ((u32)cval);\n\t\t\tbpos++;\n\t\t\tif (v == 0x00000001) {\n\t\t\t\t*sc_size = 4;\n\t\t\t\treturn bpos - 4;\n\t\t\t}\n\t\t\telse if ((v & 0x00FFFFFF) == 0x00000001) {\n\t\t\t\t*sc_size = 3;\n\t\t\t\treturn bpos - 3;\n\t\t\t}\n\t\t\tif (cval)\n\t\t\t\tbreak;\n\t\t}\n\t\tif (bpos >= data_len)\n\t\t\tbreak;\n\t\tcur = data + bpos;\n\t\tavail = data_len - bpos;\n\t}\n\treturn data_len;\n}",
"Bool gf_media_avc_slice_is_intra(AVCState *avc)\n{\n\tswitch (avc->s_info.slice_type) {\n\tcase GF_AVC_TYPE_I:\n\tcase GF_AVC_TYPE2_I:\n\tcase GF_AVC_TYPE_SI:\n\tcase GF_AVC_TYPE2_SI:\n\t\treturn 1;\n\tdefault:\n\t\treturn 0;\n\t}\n}",
"#if 0 //unused\nBool gf_media_avc_slice_is_IDR(AVCState *avc)\n{\n\tif (avc->sei.recovery_point.valid)\n\t{\n\t\tavc->sei.recovery_point.valid = 0;\n\t\treturn 1;\n\t}\n\tif (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE)\n\t\treturn 0;\n\treturn gf_media_avc_slice_is_intra(avc);\n}\n#endif",
"static const struct {\n\tu32 w, h;\n} avc_hevc_sar[] = {\n\t{ 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 },\n\t{ 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },\n\t{ 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },\n\t{ 64, 33 }, { 160,99 }, { 4, 3 }, { 3, 2 },\n\t{ 2, 1 }\n};",
"\n/*ISO 14496-10 (N11084) E.1.2*/\nstatic void avc_parse_hrd_parameters(GF_BitStream *bs, AVC_HRD *hrd)\n{\n\tint i, cpb_cnt_minus1;",
"\tcpb_cnt_minus1 = gf_bs_read_ue_log(bs, \"cpb_cnt_minus1\");\n\tif (cpb_cnt_minus1 > 31)\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] invalid cpb_cnt_minus1 value: %d (expected in [0;31])\\n\", cpb_cnt_minus1));\n\tgf_bs_read_int_log(bs, 4, \"bit_rate_scale\");\n\tgf_bs_read_int_log(bs, 4, \"cpb_size_scale\");",
"\t/*for( SchedSelIdx = 0; SchedSelIdx <= cpb_cnt_minus1; SchedSelIdx++ ) {*/\n\tfor (i = 0; i <= cpb_cnt_minus1; i++) {\n\t\tgf_bs_read_ue_log_idx(bs, \"bit_rate_value_minus1\", i);\n\t\tgf_bs_read_ue_log_idx(bs, \"cpb_size_value_minus1\", i);\n\t\tgf_bs_read_int_log_idx(bs, 1, \"cbr_flag\", i);\n\t}\n\tgf_bs_read_int_log(bs, 5, \"initial_cpb_removal_delay_length_minus1\");\n\thrd->cpb_removal_delay_length_minus1 = gf_bs_read_int_log(bs, 5, \"cpb_removal_delay_length_minus1\");\n\thrd->dpb_output_delay_length_minus1 = gf_bs_read_int_log(bs, 5, \"dpb_output_delay_length_minus1\");\n\thrd->time_offset_length = gf_bs_read_int_log(bs, 5, \"time_offset_length\");\n\treturn;\n}",
"/*returns the nal_size without emulation prevention bytes*/\nu32 gf_media_nalu_emulation_bytes_add_count(u8 *buffer, u32 nal_size)\n{\n\tu32 i = 0, emulation_bytes_count = 0;\n\tu8 num_zero = 0;",
"\twhile (i < nal_size) {\n\t\t/*ISO 14496-10: \"Within the NAL unit, any four-byte sequence that starts with 0x000003\n\t\tother than the following sequences shall not occur at any byte-aligned position:\n\t\t\\96 0x00000300\n\t\t\\96 0x00000301\n\t\t\\96 0x00000302\n\t\t\\96 0x00000303\"\n\t\t*/\n\t\tif (num_zero == 2 && (u8)buffer[i] < 0x04) {\n\t\t\t/*emulation code found*/\n\t\t\tnum_zero = 0;\n\t\t\temulation_bytes_count++;\n\t\t\tif (!buffer[i])\n\t\t\t\tnum_zero = 1;\n\t\t}\n\t\telse {\n\t\t\tif (!buffer[i])\n\t\t\t\tnum_zero++;\n\t\t\telse\n\t\t\t\tnum_zero = 0;\n\t\t}\n\t\ti++;\n\t}\n\treturn emulation_bytes_count;\n}",
"u32 gf_media_nalu_add_emulation_bytes(const u8 *buffer_src, u8 *buffer_dst, u32 nal_size)\n{\n\tu32 i = 0, emulation_bytes_count = 0;\n\tu8 num_zero = 0;",
"\twhile (i < nal_size) {\n\t\t/*ISO 14496-10: \"Within the NAL unit, any four-byte sequence that starts with 0x000003\n\t\tother than the following sequences shall not occur at any byte-aligned position:\n\t\t0x00000300\n\t\t0x00000301\n\t\t0x00000302\n\t\t0x00000303\"\n\t\t*/\n\t\tif (num_zero == 2 && (u8)buffer_src[i] < 0x04) {\n\t\t\t/*add emulation code*/\n\t\t\tnum_zero = 0;\n\t\t\tbuffer_dst[i + emulation_bytes_count] = 0x03;\n\t\t\temulation_bytes_count++;\n\t\t\tif (!buffer_src[i])\n\t\t\t\tnum_zero = 1;\n\t\t}\n\t\telse {\n\t\t\tif (!buffer_src[i])\n\t\t\t\tnum_zero++;\n\t\t\telse\n\t\t\t\tnum_zero = 0;\n\t\t}\n\t\tbuffer_dst[i + emulation_bytes_count] = buffer_src[i];\n\t\ti++;\n\t}\n\treturn nal_size + emulation_bytes_count;\n}",
"/*returns the nal_size without emulation prevention bytes*/\nu32 gf_media_nalu_emulation_bytes_remove_count(const u8 *buffer, u32 nal_size)\n{\n\tu32 i = 0, emulation_bytes_count = 0;\n\tu8 num_zero = 0;\n\tif (!buffer || !nal_size) return 0;",
"\twhile (i < nal_size)\n\t{\n\t\t/*ISO 14496-10: \"Within the NAL unit, any four-byte sequence that starts with 0x000003\n\t\t other than the following sequences shall not occur at any byte-aligned position:\n\t\t \\96 0x00000300\n\t\t \\96 0x00000301\n\t\t \\96 0x00000302\n\t\t \\96 0x00000303\"\n\t\t*/\n\t\tif (num_zero == 2\n\t\t\t&& buffer[i] == 0x03\n\t\t\t&& i + 1 < nal_size /*next byte is readable*/\n\t\t\t&& (u8)buffer[i + 1] < 0x04)\n\t\t{\n\t\t\t/*emulation code found*/\n\t\t\tnum_zero = 0;\n\t\t\temulation_bytes_count++;\n\t\t\ti++;\n\t\t}",
"\t\tif (!buffer[i])\n\t\t\tnum_zero++;\n\t\telse\n\t\t\tnum_zero = 0;",
"\t\ti++;\n\t}",
"\treturn emulation_bytes_count;\n}",
"/*nal_size is updated to allow better error detection*/\nGF_EXPORT\nu32 gf_media_nalu_remove_emulation_bytes(const u8 *buffer_src, u8 *buffer_dst, u32 nal_size)\n{\n\tu32 i = 0, emulation_bytes_count = 0;\n\tu8 num_zero = 0;",
"\twhile (i < nal_size)\n\t{\n\t\t/*ISO 14496-10: \"Within the NAL unit, any four-byte sequence that starts with 0x000003\n\t\t other than the following sequences shall not occur at any byte-aligned position:\n\t\t 0x00000300\n\t\t 0x00000301\n\t\t 0x00000302\n\t\t 0x00000303\"\n\t\t*/\n\t\tif (num_zero == 2\n\t\t\t&& buffer_src[i] == 0x03\n\t\t\t&& i + 1 < nal_size /*next byte is readable*/\n\t\t\t&& (u8)buffer_src[i + 1] < 0x04)\n\t\t{\n\t\t\t/*emulation code found*/\n\t\t\tnum_zero = 0;\n\t\t\temulation_bytes_count++;\n\t\t\ti++;\n\t\t}",
"\t\tbuffer_dst[i - emulation_bytes_count] = buffer_src[i];",
"\t\tif (!buffer_src[i])\n\t\t\tnum_zero++;\n\t\telse\n\t\t\tnum_zero = 0;",
"\t\ti++;\n\t}",
"\treturn nal_size - emulation_bytes_count;\n}",
"static s32 gf_avc_read_sps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos, u32 nal_hdr)\n{\n\tAVC_SPS *sps;\n\ts32 mb_width, mb_height, sps_id = -1;\n\tu32 profile_idc, level_idc, pcomp, i, chroma_format_idc, cl = 0, cr = 0, ct = 0, cb = 0, luma_bd, chroma_bd;\n\tu8 separate_colour_plane_flag = 0;",
"\tif (!vui_flag_pos) {\n\t\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\t}",
"\tif (!bs) {\n\t\treturn -1;\n\t}",
"\tif (!nal_hdr) {\n\t\tgf_bs_read_int_log(bs, 1, \"forbidden_zero_bit\");\n\t\tgf_bs_read_int_log(bs, 2, \"nal_ref_idc\");\n\t\tgf_bs_read_int_log(bs, 5, \"nal_unit_type\");\n\t}\n\tprofile_idc = gf_bs_read_int_log(bs, 8, \"profile_idc\");",
"\tpcomp = gf_bs_read_int_log(bs, 8, \"profile_compatibility\");\n\t/*sanity checks*/\n\tif (pcomp & 0x3)\n\t\treturn -1;",
"\tlevel_idc = gf_bs_read_int_log(bs, 8, \"level_idc\");",
"\t/*SubsetSps is used to be sure that AVC SPS are not going to be scratched\n\tby subset SPS. According to the SVC standard, subset SPS can have the same sps_id\n\tthan its base layer, but it does not refer to the same SPS. */\n\tsps_id = gf_bs_read_ue_log(bs, \"sps_id\") + GF_SVC_SSPS_ID_SHIFT * subseq_sps;\n\tif ((sps_id < 0) || (sps_id >= 32)) {\n\t\treturn -1;\n\t}",
"\tluma_bd = chroma_bd = 0;\n\tsps = &avc->sps[sps_id];\n\tchroma_format_idc = sps->ChromaArrayType = 1;\n\tsps->state |= subseq_sps ? AVC_SUBSPS_PARSED : AVC_SPS_PARSED;",
"\t/*High Profile and SVC*/\n\tswitch (profile_idc) {\n\tcase 100:\n\tcase 110:\n\tcase 122:\n\tcase 244:\n\tcase 44:\n\t\t/*sanity checks: note1 from 7.4.2.1.1 of iso/iec 14496-10-N11084*/\n\t\tif (pcomp & 0xE0)\n\t\t\treturn -1;\n\tcase 83:\n\tcase 86:\n\tcase 118:\n\tcase 128:\n\t\tchroma_format_idc = gf_bs_read_ue_log(bs, \"chroma_format_idc\");\n\t\tsps->ChromaArrayType = chroma_format_idc;\n\t\tif (chroma_format_idc == 3) {\n\t\t\tseparate_colour_plane_flag = gf_bs_read_int_log(bs, 1, \"separate_colour_plane_flag\");\n\t\t\t/*\n\t\t\tDepending on the value of separate_colour_plane_flag, the value of the variable ChromaArrayType is assigned as follows.\n\t\t\t\\96\tIf separate_colour_plane_flag is equal to 0, ChromaArrayType is set equal to chroma_format_idc.\n\t\t\t\\96\tOtherwise (separate_colour_plane_flag is equal to 1), ChromaArrayType is set equal to 0.\n\t\t\t*/\n\t\t\tif (separate_colour_plane_flag) sps->ChromaArrayType = 0;\n\t\t}\n\t\tluma_bd = gf_bs_read_ue_log(bs, \"luma_bit_depth\");\n\t\tchroma_bd = gf_bs_read_ue_log(bs, \"chroma_bit_depth\");\n\t\t/*qpprime_y_zero_transform_bypass_flag = */ gf_bs_read_int_log(bs, 1, \"qpprime_y_zero_transform_bypass_flag\");\n\t\t/*seq_scaling_matrix_present_flag*/\n\t\tif (gf_bs_read_int_log(bs, 1, \"seq_scaling_matrix_present_flag\")) {\n\t\t\tu32 k;\n\t\t\tfor (k = 0; k < 8; k++) {\n\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"seq_scaling_list_present_flag\", k)) {\n\t\t\t\t\tu32 z, last = 8, next = 8;\n\t\t\t\t\tu32 sl = k < 6 ? 16 : 64;\n\t\t\t\t\tfor (z = 0; z < sl; z++) {\n\t\t\t\t\t\tif (next) {\n\t\t\t\t\t\t\ts32 delta = gf_bs_read_se(bs);\n\t\t\t\t\t\t\tnext = (last + delta + 256) % 256;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlast = next ? next : last;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}",
"\tsps->profile_idc = profile_idc;\n\tsps->level_idc = level_idc;\n\tsps->prof_compat = pcomp;\n\tsps->log2_max_frame_num = gf_bs_read_ue_log(bs, \"log2_max_frame_num\") + 4;\n\tsps->poc_type = gf_bs_read_ue_log(bs, \"poc_type\");\n\tsps->chroma_format = chroma_format_idc;\n\tsps->luma_bit_depth_m8 = luma_bd;\n\tsps->chroma_bit_depth_m8 = chroma_bd;",
"\tif (sps->poc_type == 0) {\n\t\tsps->log2_max_poc_lsb = gf_bs_read_ue_log(bs, \"log2_max_poc_lsb\") + 4;\n\t}\n\telse if (sps->poc_type == 1) {\n\t\tsps->delta_pic_order_always_zero_flag = gf_bs_read_int_log(bs, 1, \"delta_pic_order_always_zero_flag\");\n\t\tsps->offset_for_non_ref_pic = gf_bs_read_se_log(bs, \"offset_for_non_ref_pic\");\n\t\tsps->offset_for_top_to_bottom_field = gf_bs_read_se_log(bs, \"offset_for_top_to_bottom_field\");\n\t\tsps->poc_cycle_length = gf_bs_read_ue_log(bs, \"poc_cycle_length\");\n\t\tif (sps->poc_cycle_length > GF_ARRAY_LENGTH(sps->offset_for_ref_frame)) {\n\t\t\tsps->poc_cycle_length = 255;\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[avc-h264] offset_for_ref_frame overflow from poc_cycle_length\\n\"));\n\t\t\treturn -1;\n\t\t}\n\t\tfor (i = 0; i < sps->poc_cycle_length; i++)\n\t\t\tsps->offset_for_ref_frame[i] = gf_bs_read_se_log_idx(bs, \"offset_for_ref_frame\", i);\n\t}\n\tif (sps->poc_type > 2) {\n\t\treturn -1;\n\t}\n\tsps->max_num_ref_frames = gf_bs_read_ue_log(bs, \"max_num_ref_frames\");\n\tsps->gaps_in_frame_num_value_allowed_flag = gf_bs_read_int_log(bs, 1, \"gaps_in_frame_num_value_allowed_flag\");\n\tmb_width = gf_bs_read_ue_log(bs, \"pic_width_in_mbs_minus1\") + 1;\n\tmb_height = gf_bs_read_ue_log(bs, \"pic_height_in_map_units_minus1\") + 1;",
"\tsps->frame_mbs_only_flag = gf_bs_read_int_log(bs, 1, \"frame_mbs_only_flag\");",
"\tsps->width = mb_width * 16;\n\tsps->height = (2 - sps->frame_mbs_only_flag) * mb_height * 16;",
"\tif (!sps->frame_mbs_only_flag) sps->mb_adaptive_frame_field_flag = gf_bs_read_int_log(bs, 1, \"mb_adaptive_frame_field_flag\");\n\tgf_bs_read_int_log(bs, 1, \"direct_8x8_inference_flag\");",
"\tif (gf_bs_read_int_log(bs, 1, \"frame_cropping_flag\")) {\n\t\tint CropUnitX, CropUnitY, SubWidthC = -1, SubHeightC = -1;",
"\t\tif (chroma_format_idc == 1) {\n\t\t\tSubWidthC = 2; SubHeightC = 2;\n\t\t}\n\t\telse if (chroma_format_idc == 2) {\n\t\t\tSubWidthC = 2; SubHeightC = 1;\n\t\t}\n\t\telse if ((chroma_format_idc == 3) && (separate_colour_plane_flag == 0)) {\n\t\t\tSubWidthC = 1; SubHeightC = 1;\n\t\t}",
"\t\tif (sps->ChromaArrayType == 0) {\n\t\t\tassert(SubWidthC == -1);\n\t\t\tCropUnitX = 1;\n\t\t\tCropUnitY = 2 - sps->frame_mbs_only_flag;\n\t\t}\n\t\telse {\n\t\t\tCropUnitX = SubWidthC;\n\t\t\tCropUnitY = SubHeightC * (2 - sps->frame_mbs_only_flag);\n\t\t}",
"\t\tcl = gf_bs_read_ue_log(bs, \"frame_crop_left_offset\");\n\t\tcr = gf_bs_read_ue_log(bs, \"frame_crop_right_offset\");\n\t\tct = gf_bs_read_ue_log(bs, \"frame_crop_top_offset\");\n\t\tcb = gf_bs_read_ue_log(bs, \"frame_crop_bottom_offset\");",
"\t\tsps->width -= CropUnitX * (cl + cr);\n\t\tsps->height -= CropUnitY * (ct + cb);\n\t\tcl *= CropUnitX;\n\t\tcr *= CropUnitX;\n\t\tct *= CropUnitY;\n\t\tcb *= CropUnitY;\n\t}\n\tsps->crop.left = cl;\n\tsps->crop.right = cr;\n\tsps->crop.top = ct;\n\tsps->crop.bottom = cb;",
"\tif (vui_flag_pos) {\n\t\t*vui_flag_pos = (u32)gf_bs_get_bit_offset(bs);\n\t}\n\t/*vui_parameters_present_flag*/\n\tsps->vui_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vui_parameters_present_flag\");\n\tif (sps->vui_parameters_present_flag) {\n\t\tsps->vui.aspect_ratio_info_present_flag = gf_bs_read_int_log(bs, 1, \"aspect_ratio_info_present_flag\");\n\t\tif (sps->vui.aspect_ratio_info_present_flag) {\n\t\t\ts32 aspect_ratio_idc = gf_bs_read_int_log(bs, 8, \"aspect_ratio_idc\");\n\t\t\tif (aspect_ratio_idc == 255) {\n\t\t\t\tsps->vui.par_num = gf_bs_read_int_log(bs, 16, \"aspect_ratio_num\");\n\t\t\t\tsps->vui.par_den = gf_bs_read_int_log(bs, 16, \"aspect_ratio_den\");\n\t\t\t}\n\t\t\telse if (aspect_ratio_idc < GF_ARRAY_LENGTH(avc_hevc_sar) ) {\n\t\t\t\tsps->vui.par_num = avc_hevc_sar[aspect_ratio_idc].w;\n\t\t\t\tsps->vui.par_den = avc_hevc_sar[aspect_ratio_idc].h;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] Unknown aspect_ratio_idc: your video may have a wrong aspect ratio. Contact the GPAC team!\\n\"));\n\t\t\t}\n\t\t}\n\t\tsps->vui.overscan_info_present_flag = gf_bs_read_int_log(bs, 1, \"overscan_info_present_flag\");\n\t\tif (sps->vui.overscan_info_present_flag)\n\t\t\tgf_bs_read_int_log(bs, 1, \"overscan_appropriate_flag\");",
"\t\t/* default values */\n\t\tsps->vui.video_format = 5;\n\t\tsps->vui.colour_primaries = 2;\n\t\tsps->vui.transfer_characteristics = 2;\n\t\tsps->vui.matrix_coefficients = 2;\n\t\t/* now read values if possible */\n\t\tsps->vui.video_signal_type_present_flag = gf_bs_read_int_log(bs, 1, \"video_signal_type_present_flag\");\n\t\tif (sps->vui.video_signal_type_present_flag) {\n\t\t\tsps->vui.video_format = gf_bs_read_int_log(bs, 3, \"video_format\");\n\t\t\tsps->vui.video_full_range_flag = gf_bs_read_int_log(bs, 1, \"video_full_range_flag\");\n\t\t\tsps->vui.colour_description_present_flag = gf_bs_read_int_log(bs, 1, \"colour_description_present_flag\");\n\t\t\tif (sps->vui.colour_description_present_flag) {\n\t\t\t\tsps->vui.colour_primaries = gf_bs_read_int_log(bs, 8, \"colour_primaries\");\n\t\t\t\tsps->vui.transfer_characteristics = gf_bs_read_int_log(bs, 8, \"transfer_characteristics\");\n\t\t\t\tsps->vui.matrix_coefficients = gf_bs_read_int_log(bs, 8, \"matrix_coefficients\");\n\t\t\t}\n\t\t}",
"\t\tif (gf_bs_read_int_log(bs, 1, \"chroma_location_info_present_flag\")) {\n\t\t\tgf_bs_read_ue_log(bs, \"chroma_sample_location_type_top_field\");\n\t\t\tgf_bs_read_ue_log(bs, \"chroma_sample_location_type_bottom_field\");\n\t\t}",
"\t\tsps->vui.timing_info_present_flag = gf_bs_read_int_log(bs, 1, \"timing_info_present_flag\");\n\t\tif (sps->vui.timing_info_present_flag) {\n\t\t\tsps->vui.num_units_in_tick = gf_bs_read_int_log(bs, 32, \"num_units_in_tick\");\n\t\t\tsps->vui.time_scale = gf_bs_read_int_log(bs, 32, \"time_scale\");\n\t\t\tsps->vui.fixed_frame_rate_flag = gf_bs_read_int_log(bs, 1, \"fixed_frame_rate_flag\");\n\t\t}",
"\t\tsps->vui.nal_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"nal_hrd_parameters_present_flag\");\n\t\tif (sps->vui.nal_hrd_parameters_present_flag)\n\t\t\tavc_parse_hrd_parameters(bs, &sps->vui.hrd);",
"\t\tsps->vui.vcl_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vcl_hrd_parameters_present_flag\");\n\t\tif (sps->vui.vcl_hrd_parameters_present_flag)\n\t\t\tavc_parse_hrd_parameters(bs, &sps->vui.hrd);",
"\t\tif (sps->vui.nal_hrd_parameters_present_flag || sps->vui.vcl_hrd_parameters_present_flag)\n\t\t\tsps->vui.low_delay_hrd_flag = gf_bs_read_int_log(bs, 1, \"low_delay_hrd_flag\");",
"\t\tsps->vui.pic_struct_present_flag = gf_bs_read_int_log(bs, 1, \"pic_struct_present_flag\");\n\t}\n\t/*end of seq_parameter_set_data*/",
"\tif (subseq_sps) {\n\t\tif ((profile_idc == 83) || (profile_idc == 86)) {\n\t\t\tu8 extended_spatial_scalability_idc;\n\t\t\t/*parsing seq_parameter_set_svc_extension*/",
"\t\t\tgf_bs_read_int_log(bs, 1, \"inter_layer_deblocking_filter_control_present_flag\");\n\t\t\textended_spatial_scalability_idc = gf_bs_read_int_log(bs, 2, \"extended_spatial_scalability_idc\");\n\t\t\tif (sps->ChromaArrayType == 1 || sps->ChromaArrayType == 2) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"chroma_phase_x_plus1_flag\");\n\t\t\t}\n\t\t\tif (sps->ChromaArrayType == 1) {\n\t\t\t\tgf_bs_read_int_log(bs, 2, \"chroma_phase_y_plus1\");\n\t\t\t}\n\t\t\tif (extended_spatial_scalability_idc == 1) {\n\t\t\t\tif (sps->ChromaArrayType > 0) {\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"seq_ref_layer_chroma_phase_x_plus1_flag\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 2, \"seq_ref_layer_chroma_phase_y_plus1\");\n\t\t\t\t}\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_left_offset\");\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_top_offset\");\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_right_offset\");\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_bottom_offset\");\n\t\t\t}\n\t\t\tif (gf_bs_read_int_log(bs, 1, \"seq_tcoeff_level_prediction_flag\")) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"adaptive_tcoeff_level_prediction_flag\");\n\t\t\t}\n\t\t\tgf_bs_read_int_log(bs, 1, \"slice_header_restriction_flag\");",
"\t\t\tif (gf_bs_read_int_log(bs, 1, \"svc_vui_parameters_present\")) {\n\t\t\t\tu32 vui_ext_num_entries_minus1 = gf_bs_read_ue_log(bs, \"vui_ext_num_entries_minus1\");",
"\t\t\t\tfor (i = 0; i <= vui_ext_num_entries_minus1; i++) {\n\t\t\t\t\tu8 vui_ext_nal_hrd_parameters_present_flag, vui_ext_vcl_hrd_parameters_present_flag, vui_ext_timing_info_present_flag;\n\t\t\t\t\tgf_bs_read_int_log(bs, 3, \"vui_ext_dependency_id\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 4, \"vui_ext_quality_id\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 3, \"vui_ext_temporal_id\");\n\t\t\t\t\tvui_ext_timing_info_present_flag = gf_bs_read_int_log(bs, 1, \"vui_ext_timing_info_present_flag\");\n\t\t\t\t\tif (vui_ext_timing_info_present_flag) {\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 32, \"vui_ext_num_units_in_tick\");\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 32, \"vui_ext_time_scale\");\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"vui_ext_fixed_frame_rate_flag\");\n\t\t\t\t\t}\n\t\t\t\t\tvui_ext_nal_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vui_ext_nal_hrd_parameters_present_flag\");\n\t\t\t\t\tif (vui_ext_nal_hrd_parameters_present_flag) {\n\t\t\t\t\t\t//hrd_parameters( )\n\t\t\t\t\t}\n\t\t\t\t\tvui_ext_vcl_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vui_ext_vcl_hrd_parameters_present_flag\");\n\t\t\t\t\tif (vui_ext_vcl_hrd_parameters_present_flag) {\n\t\t\t\t\t\t//hrd_parameters( )\n\t\t\t\t\t}\n\t\t\t\t\tif (vui_ext_nal_hrd_parameters_present_flag || vui_ext_vcl_hrd_parameters_present_flag) {\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"vui_ext_low_delay_hrd_flag\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"vui_ext_pic_struct_present_flag\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if ((profile_idc == 118) || (profile_idc == 128)) {\n\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CODING, (\"[avc-h264] MVC parsing not implemented - skipping parsing end of Subset SPS\\n\"));\n\t\t\treturn sps_id;\n\t\t}",
"\t\tif (gf_bs_read_int_log(bs, 1, \"additional_extension2\")) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] skipping parsing end of Subset SPS (additional_extension2)\\n\"));\n\t\t\treturn sps_id;\n\t\t}\n\t}\n\treturn sps_id;\n}",
"GF_EXPORT\ns32 gf_avc_read_sps_bs(GF_BitStream *bs, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos)\n{\n\treturn gf_avc_read_sps_bs_internal(bs, avc, subseq_sps, vui_flag_pos, 0);\n}",
"GF_EXPORT\ns32 gf_avc_read_sps(const u8 *sps_data, u32 sps_size, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos)\n{\n\ts32 sps_id = -1;\n\tGF_BitStream *bs;\n\tchar *sps_data_without_emulation_bytes = NULL;\n\tu32 sps_data_without_emulation_bytes_size = 0;",
"\tif (vui_flag_pos) {\n\t\t/*SPS still contains emulation bytes*/\n\t\tsps_data_without_emulation_bytes = gf_malloc(sps_size * sizeof(char));\n\t\tsps_data_without_emulation_bytes_size = gf_media_nalu_remove_emulation_bytes(sps_data, sps_data_without_emulation_bytes, sps_size);\n\t\tbs = gf_bs_new(sps_data_without_emulation_bytes, sps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);",
"\t\t*vui_flag_pos = 0;\n\t}\n\telse {\n\t\tbs = gf_bs_new(sps_data, sps_size, GF_BITSTREAM_READ);\n\t}",
"\tif (!bs) {\n\t\tsps_id = -1;\n\t\tgoto exit;\n\t}",
"\tsps_id = gf_avc_read_sps_bs(bs, avc, subseq_sps, vui_flag_pos);",
"exit:\n\tgf_bs_del(bs);\n\tif (sps_data_without_emulation_bytes) gf_free(sps_data_without_emulation_bytes);\n\treturn sps_id;\n}",
"static s32 gf_avc_read_pps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 nal_hdr)\n{\n\ts32 pps_id;\n\tAVC_PPS *pps;",
"\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tif (!nal_hdr) {\n\t\tgf_bs_read_int_log(bs, 1, \"forbidden_zero_bit\");\n\t\tgf_bs_read_int_log(bs, 2, \"nal_ref_idc\");\n\t\tgf_bs_read_int_log(bs, 5, \"nal_unit_type\");\n\t}\n\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\tif ((pps_id<0) || (pps_id >= 255)) {\n\t\treturn -1;\n\t}\n\tpps = &avc->pps[pps_id];\n\tpps->id = pps_id;",
"\tif (!pps->status) pps->status = 1;\n\tpps->sps_id = gf_bs_read_ue_log(bs, \"sps_id\");\n\tif ((pps->sps_id<0) || (pps->sps_id >= 32)) {\n\t\tpps->sps_id = 0;\n\t\treturn -1;\n\t}\n\t/*sps_id may be refer to regular SPS or subseq sps, depending on the coded slice referring to the pps*/\n\tif (!avc->sps[pps->sps_id].state && !avc->sps[pps->sps_id + GF_SVC_SSPS_ID_SHIFT].state) {\n\t\treturn -1;\n\t}\n\tavc->pps_active_idx = pps->id; /*set active sps*/\n\tavc->sps_active_idx = pps->sps_id; /*set active sps*/\n\tpps->entropy_coding_mode_flag = gf_bs_read_int_log(bs, 1, \"entropy_coding_mode_flag\");\n\tpps->pic_order_present = gf_bs_read_int_log(bs, 1, \"pic_order_present\");\n\tpps->slice_group_count = gf_bs_read_ue_log(bs, \"slice_group_count_minus1\") + 1;\n\tif (pps->slice_group_count > 1) {\n\t\tu32 iGroup;\n\t\tpps->mb_slice_group_map_type = gf_bs_read_ue_log(bs, \"mb_slice_group_map_type\");\n\t\tif (pps->mb_slice_group_map_type == 0) {\n\t\t\tfor (iGroup = 0; iGroup <= pps->slice_group_count - 1; iGroup++)\n\t\t\t\tgf_bs_read_ue_log_idx(bs, \"run_length_minus1\", iGroup);\n\t\t}\n\t\telse if (pps->mb_slice_group_map_type == 2) {\n\t\t\tfor (iGroup = 0; iGroup < pps->slice_group_count - 1; iGroup++) {\n\t\t\t\tgf_bs_read_ue_log_idx(bs, \"top_left\", iGroup);\n\t\t\t\tgf_bs_read_ue_log_idx(bs, \"bottom_right\", iGroup);\n\t\t\t}\n\t\t}\n\t\telse if (pps->mb_slice_group_map_type == 3 || pps->mb_slice_group_map_type == 4 || pps->mb_slice_group_map_type == 5) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"slice_group_change_direction_flag\");\n\t\t\tgf_bs_read_ue_log(bs, \"slice_group_change_rate_minus1\");\n\t\t}\n\t\telse if (pps->mb_slice_group_map_type == 6) {\n\t\t\tu32 i;\n\t\t\tpps->pic_size_in_map_units_minus1 = gf_bs_read_ue_log(bs, \"pic_size_in_map_units_minus1\");\n\t\t\tfor (i = 0; i <= pps->pic_size_in_map_units_minus1; i++) {\n\t\t\t\tgf_bs_read_int_log_idx(bs, (u32)ceil(log(pps->slice_group_count) / log(2)), \"slice_group_id\", i);\n\t\t\t}\n\t\t}\n\t}\n\tpps->num_ref_idx_l0_default_active_minus1 = gf_bs_read_ue_log(bs, \"num_ref_idx_l0_default_active_minus1\");\n\tpps->num_ref_idx_l1_default_active_minus1 = gf_bs_read_ue_log(bs, \"num_ref_idx_l1_default_active_minus1\");",
"\t/*\n\tif ((pps->ref_count[0] > 32) || (pps->ref_count[1] > 32)) goto exit;\n\t*/",
"\tpps->weighted_pred_flag = gf_bs_read_int_log(bs, 1, \"weighted_pred_flag\");\n\tgf_bs_read_int_log(bs, 2, \"weighted_bipred_idc\");\n\tgf_bs_read_se_log(bs, \"init_qp_minus26\");\n\tgf_bs_read_se_log(bs, \"init_qs_minus26\");\n\tgf_bs_read_se_log(bs, \"chroma_qp_index_offset\");\n\tpps->deblocking_filter_control_present_flag = gf_bs_read_int_log(bs, 1, \"deblocking_filter_control_present_flag\");\n\tgf_bs_read_int_log(bs, 1, \"constrained_intra_pred\");\n\tpps->redundant_pic_cnt_present = gf_bs_read_int_log(bs, 1, \"redundant_pic_cnt_present\");",
"\treturn pps_id;\n}",
"GF_EXPORT\ns32 gf_avc_read_pps_bs(GF_BitStream *bs, AVCState *avc)\n{\n\treturn gf_avc_read_pps_bs_internal(bs, avc, 0);\n}",
"GF_EXPORT\ns32 gf_avc_read_pps(const u8 *pps_data, u32 pps_size, AVCState *avc)\n{\n\tGF_BitStream *bs;\n\ts32 pps_id;",
"\t/*PPS still contains emulation bytes*/\n\tbs = gf_bs_new(pps_data, pps_size, GF_BITSTREAM_READ);\n\tif (!bs) {\n\t\treturn -1;\n\t}\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\tpps_id = gf_avc_read_pps_bs(bs, avc);\n\tgf_bs_del(bs);\n\treturn pps_id;\n}",
"#if 0 //unused",
"s32 gf_avc_read_sps_ext(const char *spse_data, u32 spse_size)\n{\n\tGF_BitStream *bs;\n\ts32 sps_id;",
"\tbs = gf_bs_new(spse_data, spse_size, GF_BITSTREAM_READ);\n\tsps_id = gf_avc_read_sps_ext_bs(bs);",
"\tgf_bs_del(bs);\n\treturn sps_id;\n}\n#endif",
"static s32 SVC_ReadNal_header_extension(GF_BitStream *bs, SVC_NALUHeader *NalHeader)\n{\n\tgf_bs_read_int_log(bs, 1, \"reserved_one_bit\");\n\tNalHeader->idr_pic_flag = gf_bs_read_int_log(bs, 1, \"idr_flag\");\n\tNalHeader->priority_id = gf_bs_read_int_log(bs, 6, \"priority_id\");\n\tgf_bs_read_int_log(bs, 1, \"no_inter_layer_pred_flag\");\n\tNalHeader->dependency_id = gf_bs_read_int_log(bs, 3, \"DependencyId\");\n\tNalHeader->quality_id = gf_bs_read_int_log(bs, 4, \"quality_id\");\n\tNalHeader->temporal_id = gf_bs_read_int_log(bs, 3, \"temporal_id\");\n\tgf_bs_read_int_log(bs, 1, \"use_ref_base_pic_flag\");\n\tgf_bs_read_int_log(bs, 1, \"discardable_flag\");\n\tgf_bs_read_int_log(bs, 1, \"output_flag\");\n\tgf_bs_read_int_log(bs, 2, \"reserved_three_2bits\");\n\treturn 1;\n}",
"static void ref_pic_list_modification(GF_BitStream *bs, u32 slice_type) {\n\tif (slice_type % 5 != 2 && slice_type % 5 != 4) {\n\t\tif (gf_bs_read_int_log(bs, 1, \"ref_pic_list_modification_flag_l0\")) {\n\t\t\tu32 idx=0, modification_of_pic_nums_idc;\n\t\t\tdo {\n\t\t\t\tmodification_of_pic_nums_idc = gf_bs_read_ue_log_idx(bs, \"modification_of_pic_nums_idc\", idx);\n\t\t\t\tif (modification_of_pic_nums_idc == 0 || modification_of_pic_nums_idc == 1) {\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"abs_diff_pic_num_minus1\", idx);\n\t\t\t\t}\n\t\t\t\telse if (modification_of_pic_nums_idc == 2) {\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"long_term_pic_num\", idx);\n\t\t\t\t}\n\t\t\t\tidx++;\n\t\t\t} while ((modification_of_pic_nums_idc != 3) && gf_bs_available(bs));\n\t\t}\n\t}\n\tif (slice_type % 5 == 1) {\n\t\tif (gf_bs_read_int_log(bs, 1, \"ref_pic_list_modification_flag_l1\")) {\n\t\t\tu32 idx=0, modification_of_pic_nums_idc;\n\t\t\tdo {\n\t\t\t\tmodification_of_pic_nums_idc = gf_bs_read_ue_log_idx(bs, \"modification_of_pic_nums_idc\", idx);\n\t\t\t\tif (modification_of_pic_nums_idc == 0 || modification_of_pic_nums_idc == 1) {\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"abs_diff_pic_num_minus1\", idx);\n\t\t\t\t}\n\t\t\t\telse if (modification_of_pic_nums_idc == 2) {\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"long_term_pic_num\", idx);\n\t\t\t\t}\n\t\t\t\tidx++;\n\t\t\t} while ((modification_of_pic_nums_idc != 3) && gf_bs_available(bs));\n\t\t}\n\t}\n}",
"static void pred_weight_table(GF_BitStream *bs, u32 slice_type, u32 ChromaArrayType, u32 num_ref_idx_l0_active_minus1, u32 num_ref_idx_l1_active_minus1) {\n\tu32 i, j;\n\tgf_bs_read_ue_log(bs, \"luma_log2_weight_denom\");\n\tif (ChromaArrayType != 0) {\n\t\tgf_bs_read_ue_log(bs, \"chroma_log2_weight_denom\");\n\t}\n\tfor (i = 0; i <= num_ref_idx_l0_active_minus1; i++) {\n\t\tif (gf_bs_read_int_log_idx(bs, 1, \"luma_weight_l0_flag\", i)) {\n\t\t\tgf_bs_read_se_log_idx(bs, \"luma_weight_l0\", i);\n\t\t\tgf_bs_read_se_log_idx(bs, \"luma_offset_l0\", i);\n\t\t}\n\t\tif (ChromaArrayType != 0) {\n\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"chroma_weight_l0_flag\", i))\n\t\t\t\tfor (j = 0; j < 2; j++) {\n\t\t\t\t\tgf_bs_read_se_log_idx2(bs, \"chroma_weight_l0\", i, j);\n\t\t\t\t\tgf_bs_read_se_log_idx2(bs, \"chroma_offset_l0\", i, j);\n\t\t\t\t}\n\t\t}\n\t}\n\tif (slice_type % 5 == 1) {\n\t\tfor (i = 0; i <= num_ref_idx_l1_active_minus1; i++) {\n\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"luma_weight_l1_flag\", i)) {\n\t\t\t\tgf_bs_read_se_log_idx(bs, \"luma_weight_l1\", i);\n\t\t\t\tgf_bs_read_se_log_idx(bs, \"luma_offset_l1\", i);\n\t\t\t}\n\t\t\tif (ChromaArrayType != 0) {\n\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"chroma_weight_l1_flag\", i)) {\n\t\t\t\t\tfor (j = 0; j < 2; j++) {\n\t\t\t\t\t\tgf_bs_read_se_log_idx2(bs, \"chroma_weight_l1\", i, j);\n\t\t\t\t\t\tgf_bs_read_se_log_idx2(bs, \"chroma_offset_l1\", i, j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"static void dec_ref_pic_marking(GF_BitStream *bs, Bool IdrPicFlag) {\n\tif (IdrPicFlag) {\n\t\tgf_bs_read_int_log(bs, 1, \"no_output_of_prior_pics_flag\");\n\t\tgf_bs_read_int_log(bs, 1, \"long_term_reference_flag\");\n\t}\n\telse {\n\t\tif (gf_bs_read_int_log(bs, 1, \"adaptive_ref_pic_marking_mode_flag\")) {\n\t\t\tu32 idx=0, memory_management_control_operation;\n\t\t\tdo {\n\t\t\t\tmemory_management_control_operation = gf_bs_read_ue_log_idx(bs, \"memory_management_control_operation\", idx);\n\t\t\t\tif (memory_management_control_operation == 1 || memory_management_control_operation == 3)\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"difference_of_pic_nums_minus1\", idx);\n\t\t\t\tif (memory_management_control_operation == 2)\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"long_term_pic_num\", idx);\n\t\t\t\tif (memory_management_control_operation == 3 || memory_management_control_operation == 6)\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"long_term_frame_idx\", idx);\n\t\t\t\tif (memory_management_control_operation == 4)\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"max_long_term_frame_idx_plus1\", idx);\n\t\t\t\tidx++;\n\t\t\t} while (memory_management_control_operation != 0);\n\t\t}\n\t}\n}",
"static s32 avc_parse_slice(GF_BitStream *bs, AVCState *avc, Bool svc_idr_flag, AVCSliceInfo *si)\n{\n\ts32 pps_id, num_ref_idx_l0_active_minus1 = 0, num_ref_idx_l1_active_minus1 = 0;",
"\t/*s->current_picture.reference= h->nal_ref_idc != 0;*/\n\tgf_bs_read_ue_log(bs, \"first_mb_in_slice\");\n\tsi->slice_type = gf_bs_read_ue_log(bs, \"slice_type\");\n\tif (si->slice_type > 9) return -1;",
"\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\tif ((pps_id<0) || (pps_id > 255)) return -1;\n\tsi->pps = &avc->pps[pps_id];\n\tif (!si->pps->slice_group_count) return -2;\n\tsi->sps = &avc->sps[si->pps->sps_id];\n\tif (!si->sps->log2_max_frame_num) return -2;\n\tavc->sps_active_idx = si->pps->sps_id;\n\tavc->pps_active_idx = pps_id;",
"\tsi->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, \"frame_num\");",
"\tsi->field_pic_flag = 0;\n\tsi->bottom_field_flag = 0;\n\tif (!si->sps->frame_mbs_only_flag) {\n\t\tsi->field_pic_flag = gf_bs_read_int_log(bs, 1, \"field_pic_flag\");\n\t\tif (si->field_pic_flag)\n\t\t\tsi->bottom_field_flag = gf_bs_read_int_log(bs, 1, \"bottom_field_flag\");\n\t}",
"\tif ((si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) || svc_idr_flag)\n\t\tsi->idr_pic_id = gf_bs_read_ue_log(bs, \"idr_pic_id\");",
"\tif (si->sps->poc_type == 0) {\n\t\tsi->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, \"poc_lsb\");\n\t\tif (si->pps->pic_order_present && !si->field_pic_flag) {\n\t\t\tsi->delta_poc_bottom = gf_bs_read_se_log(bs, \"poc_lsb\");\n\t\t}\n\t}\n\telse if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) {\n\t\tsi->delta_poc[0] = gf_bs_read_se_log(bs, \"delta_poc0\");\n\t\tif ((si->pps->pic_order_present == 1) && !si->field_pic_flag)\n\t\t\tsi->delta_poc[1] = gf_bs_read_se_log(bs, \"delta_poc1\");\n\t}",
"\tif (si->pps->redundant_pic_cnt_present) {\n\t\tsi->redundant_pic_cnt = gf_bs_read_ue_log(bs, \"redundant_pic_cnt\");\n\t}",
"\tif (si->slice_type % 5 == GF_AVC_TYPE_B) {\n\t\tgf_bs_read_int_log(bs, 1, \"direct_spatial_mv_pred_flag\");\n\t}",
"\tnum_ref_idx_l0_active_minus1 = si->pps->num_ref_idx_l0_default_active_minus1;\n\tnum_ref_idx_l1_active_minus1 = si->pps->num_ref_idx_l1_default_active_minus1;",
"\tif (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_B) {\n\t\tBool num_ref_idx_active_override_flag = gf_bs_read_int_log(bs, 1, \"num_ref_idx_active_override_flag\");\n\t\tif (num_ref_idx_active_override_flag) {\n\t\t\tnum_ref_idx_l0_active_minus1 = gf_bs_read_ue_log(bs, \"num_ref_idx_l0_active_minus1\");\n\t\t\tif (si->slice_type % 5 == GF_AVC_TYPE_B) {\n\t\t\t\tnum_ref_idx_l1_active_minus1 = gf_bs_read_ue_log(bs, \"num_ref_idx_l1_active_minus1\");\n\t\t\t}\n\t\t}\n\t}",
"\tif (si->nal_unit_type == 20 || si->nal_unit_type == 21) {\n\t\t//ref_pic_list_mvc_modification(); /* specified in Annex H */\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[avc-h264] unimplemented ref_pic_list_mvc_modification() in slide header\\n\"));\n\t\tassert(0);\n\t\treturn -1;\n\t}\n\telse {\n\t\tref_pic_list_modification(bs, si->slice_type);\n\t}",
"\tif ((si->pps->weighted_pred_flag && (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP))\n\t\t|| (si->pps->weighted_bipred_idc == 1 && si->slice_type % 5 == GF_AVC_TYPE_B)) {\n\t\tpred_weight_table(bs, si->slice_type, si->sps->ChromaArrayType, num_ref_idx_l0_active_minus1, num_ref_idx_l1_active_minus1);\n\t}",
"\tif (si->nal_ref_idc != 0) {\n\t\tdec_ref_pic_marking(bs, (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE));\n\t}",
"\tif (si->pps->entropy_coding_mode_flag && si->slice_type % 5 != GF_AVC_TYPE_I && si->slice_type % 5 != GF_AVC_TYPE_SI) {\n\t\tgf_bs_read_ue_log(bs, \"cabac_init_idc\");\n\t}",
"\t/*slice_qp_delta = */gf_bs_read_se(bs);\n\tif (si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_SI) {\n\t\tif (si->slice_type % 5 == GF_AVC_TYPE_SP) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"sp_for_switch_flag\");\n\t\t}\n\t\tgf_bs_read_se_log(bs, \"slice_qs_delta\");\n\t}",
"\tif (si->pps->deblocking_filter_control_present_flag) {\n\t\tif (gf_bs_read_ue_log(bs, \"disable_deblocking_filter_idc\") != 1) {\n\t\t\tgf_bs_read_se_log(bs, \"slice_alpha_c0_offset_div2\");\n\t\t\tgf_bs_read_se_log(bs, \"slice_beta_offset_div2\");\n\t\t}\n\t}",
"\tif (si->pps->slice_group_count > 1 && si->pps->mb_slice_group_map_type >= 3 && si->pps->mb_slice_group_map_type <= 5) {\n\t\tgf_bs_read_int_log(bs, (u32)ceil(log1p((si->pps->pic_size_in_map_units_minus1 + 1) / (si->pps->slice_group_change_rate_minus1 + 1) ) / log(2)), \"slice_group_change_cycle\");\n\t}\n\treturn 0;\n}",
"\nstatic s32 svc_parse_slice(GF_BitStream *bs, AVCState *avc, AVCSliceInfo *si)\n{\n\ts32 pps_id;",
"\t/*s->current_picture.reference= h->nal_ref_idc != 0;*/\n\tgf_bs_read_ue_log(bs, \"first_mb_in_slice\");\n\tsi->slice_type = gf_bs_read_ue_log(bs, \"slice_type\");\n\tif (si->slice_type > 9) return -1;",
"\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");",
"\tif (pps_id > 255)",
"\t\treturn -1;\n\tsi->pps = &avc->pps[pps_id];\n\tsi->pps->id = pps_id;\n\tif (!si->pps->slice_group_count)\n\t\treturn -2;\n\tsi->sps = &avc->sps[si->pps->sps_id + GF_SVC_SSPS_ID_SHIFT];\n\tif (!si->sps->log2_max_frame_num)\n\t\treturn -2;",
"\tsi->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, \"frame_num\");",
"\tsi->field_pic_flag = 0;\n\tif (si->sps->frame_mbs_only_flag) {\n\t\t/*s->picture_structure= PICT_FRAME;*/\n\t}\n\telse {\n\t\tsi->field_pic_flag = gf_bs_read_int_log(bs, 1, \"field_pic_flag\");\n\t\tif (si->field_pic_flag) si->bottom_field_flag = gf_bs_read_int_log(bs, 1, \"bottom_field_flag\");\n\t}\n\tif (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE || si->NalHeader.idr_pic_flag)\n\t\tsi->idr_pic_id = gf_bs_read_ue_log(bs, \"idr_pic_id\");",
"\tif (si->sps->poc_type == 0) {\n\t\tsi->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, \"poc_lsb\");\n\t\tif (si->pps->pic_order_present && !si->field_pic_flag) {\n\t\t\tsi->delta_poc_bottom = gf_bs_read_se_log(bs, \"delta_poc_bottom\");\n\t\t}\n\t}\n\telse if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) {\n\t\tsi->delta_poc[0] = gf_bs_read_se_log(bs, \"delta_poc0\");\n\t\tif ((si->pps->pic_order_present == 1) && !si->field_pic_flag)\n\t\t\tsi->delta_poc[1] = gf_bs_read_se_log(bs, \"delta_poc1\");\n\t}\n\tif (si->pps->redundant_pic_cnt_present) {\n\t\tsi->redundant_pic_cnt = gf_bs_read_ue_log(bs, \"redundant_pic_cnt\");\n\t}\n\treturn 0;\n}",
"\nstatic s32 avc_parse_recovery_point_sei(GF_BitStream *bs, AVCState *avc)\n{\n\tAVCSeiRecoveryPoint *rp = &avc->sei.recovery_point;",
"\trp->frame_cnt = gf_bs_read_ue_log(bs, \"frame_cnt\");\n\trp->exact_match_flag = gf_bs_read_int_log(bs, 1, \"exact_match_flag\");\n\trp->broken_link_flag = gf_bs_read_int_log(bs, 1, \"broken_link_flag\");\n\trp->changing_slice_group_idc = gf_bs_read_int_log(bs, 2, \"changing_slice_group_idc\");\n\trp->valid = 1;",
"\treturn 0;\n}",
"/*for interpretation see ISO 14496-10 N.11084, table D-1*/\nstatic s32 avc_parse_pic_timing_sei(GF_BitStream *bs, AVCState *avc)\n{\n\tint sps_id = avc->sps_active_idx;\n\tconst char NumClockTS[] = { 1, 1, 1, 2, 2, 3, 3, 2, 3 };\n\tAVCSeiPicTiming *pt = &avc->sei.pic_timing;",
"\tif (sps_id < 0) {\n\t\t/*sps_active_idx equals -1 when no sps has been detected. In this case SEI should not be decoded.*/\n\t\tassert(0);\n\t\treturn 1;\n\t}\n\tif (avc->sps[sps_id].vui.nal_hrd_parameters_present_flag || avc->sps[sps_id].vui.vcl_hrd_parameters_present_flag) { /*CpbDpbDelaysPresentFlag, see 14496-10(2003) E.11*/\n\t\tgf_bs_read_int_log(bs, 1 + avc->sps[sps_id].vui.hrd.cpb_removal_delay_length_minus1, \"cpb_removal_delay_minus1\");\n\t\tgf_bs_read_int_log(bs, 1 + avc->sps[sps_id].vui.hrd.dpb_output_delay_length_minus1, \"dpb_output_delay_minus1\");\n\t}",
"\t/*ISO 14496-10 (2003), D.8.2: we need to get pic_struct in order to know if we display top field first or bottom field first*/\n\tif (avc->sps[sps_id].vui.pic_struct_present_flag) {\n\t\tint i;\n\t\tpt->pic_struct = gf_bs_read_int_log(bs, 4, \"pic_struct\");\n\t\tif (pt->pic_struct > 8) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[avc-h264] invalid pic_struct value %d\\n\", pt->pic_struct));\n\t\t\treturn 1;\n\t\t}",
"\t\tfor (i = 0; i < NumClockTS[pt->pic_struct]; i++) {\n\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"clock_timestamp_flag\", i)) {\n\t\t\t\tBool full_timestamp_flag;\n\t\t\t\tgf_bs_read_int_log_idx(bs, 2, \"ct_type\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 1, \"nuit_field_based_flag\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 5, \"counting_type\", i);\n\t\t\t\tfull_timestamp_flag = gf_bs_read_int_log_idx(bs, 1, \"full_timestamp_flag\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 1, \"discontinuity_flag\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 1, \"cnt_dropped_flag\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"n_frames\", i);\n\t\t\t\tif (full_timestamp_flag) {\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 6, \"seconds_value\", i);\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 6, \"minutes_value\", i);\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 5, \"hours_value\", i);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"seconds_flag\", i)) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 6, \"seconds_value\", i);\n\t\t\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"minutes_flag\", i)) {\n\t\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 6, \"minutes_value\", i);\n\t\t\t\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"hours_flag\", i)) {\n\t\t\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 5, \"hours_value\", i);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (avc->sps[sps_id].vui.hrd.time_offset_length > 0)\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, avc->sps[sps_id].vui.hrd.time_offset_length, \"time_offset\", i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\treturn 0;\n}",
"\n#if !defined(GPAC_DISABLE_HEVC)\nstatic void avc_parse_itu_t_t35_sei(GF_BitStream* bs, AVCSeiItuTT35DolbyVision *dovi)\n{\n\tu8 itu_t_t35_country_code = gf_bs_read_u8(bs);\n\tu16 terminal_provider_code = gf_bs_read_u16(bs);\n\tu32 user_id = gf_bs_read_u32(bs);\n\tu8 data_type_code = gf_bs_read_u8(bs);\n\tif (itu_t_t35_country_code == 0xB5 && terminal_provider_code == 0x31 && user_id == 0x47413934 && (data_type_code == 0x8 || data_type_code == 0x9)) {\n\t\tdovi->rpu_flag = GF_TRUE;\n\t}\n}\n#endif",
"static void avc_compute_poc(AVCSliceInfo *si)\n{\n\tenum {\n\t\tAVC_PIC_FRAME,\n\t\tAVC_PIC_FIELD_TOP,\n\t\tAVC_PIC_FIELD_BOTTOM,\n\t} pic_type;\n\ts32 field_poc[2] = { 0,0 };\n\ts32 max_frame_num;",
"\tif (!si->sps) return;",
"\tmax_frame_num = 1 << (si->sps->log2_max_frame_num);",
"\t/* picture type */\n\tif (si->sps->frame_mbs_only_flag || !si->field_pic_flag) pic_type = AVC_PIC_FRAME;\n\telse if (si->bottom_field_flag) pic_type = AVC_PIC_FIELD_BOTTOM;\n\telse pic_type = AVC_PIC_FIELD_TOP;",
"\t/* frame_num_offset */\n\tif (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) {\n\t\tsi->poc_lsb_prev = 0;\n\t\tsi->poc_msb_prev = 0;\n\t\tsi->frame_num_offset = 0;\n\t}\n\telse {\n\t\tif (si->frame_num < si->frame_num_prev)\n\t\t\tsi->frame_num_offset = si->frame_num_offset_prev + max_frame_num;\n\t\telse\n\t\t\tsi->frame_num_offset = si->frame_num_offset_prev;\n\t}",
"\t/*ISO 14496-10 N.11084 8.2.1.1*/\n\tif (si->sps->poc_type == 0)\n\t{\n\t\tconst u32 max_poc_lsb = 1 << (si->sps->log2_max_poc_lsb);",
"\t\t/*ISO 14496-10 N.11084 eq (8-3)*/\n\t\tif ((si->poc_lsb < si->poc_lsb_prev) &&\n\t\t\t(si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2))\n\t\t\tsi->poc_msb = si->poc_msb_prev + max_poc_lsb;\n\t\telse if ((si->poc_lsb > si->poc_lsb_prev) &&\n\t\t\t(si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))\n\t\t\tsi->poc_msb = si->poc_msb_prev - max_poc_lsb;\n\t\telse\n\t\t\tsi->poc_msb = si->poc_msb_prev;",
"\t\t/*ISO 14496-10 N.11084 eq (8-4)*/\n\t\tif (pic_type != AVC_PIC_FIELD_BOTTOM)\n\t\t\tfield_poc[0] = si->poc_msb + si->poc_lsb;",
"\t\t/*ISO 14496-10 N.11084 eq (8-5)*/\n\t\tif (pic_type != AVC_PIC_FIELD_TOP) {\n\t\t\tif (!si->field_pic_flag)\n\t\t\t\tfield_poc[1] = field_poc[0] + si->delta_poc_bottom;\n\t\t\telse\n\t\t\t\tfield_poc[1] = si->poc_msb + si->poc_lsb;\n\t\t}\n\t}\n\t/*ISO 14496-10 N.11084 8.2.1.2*/\n\telse if (si->sps->poc_type == 1)\n\t{\n\t\tu32 i;\n\t\ts32 abs_frame_num, expected_delta_per_poc_cycle, expected_poc;",
"\t\tif (si->sps->poc_cycle_length)\n\t\t\tabs_frame_num = si->frame_num_offset + si->frame_num;\n\t\telse\n\t\t\tabs_frame_num = 0;",
"\t\tif (!si->nal_ref_idc && (abs_frame_num > 0)) abs_frame_num--;",
"\t\texpected_delta_per_poc_cycle = 0;\n\t\tfor (i = 0; i < si->sps->poc_cycle_length; i++)\n\t\t\texpected_delta_per_poc_cycle += si->sps->offset_for_ref_frame[i];",
"\t\tif (abs_frame_num > 0) {\n\t\t\tconst u32 poc_cycle_cnt = (abs_frame_num - 1) / si->sps->poc_cycle_length;\n\t\t\tconst u32 frame_num_in_poc_cycle = (abs_frame_num - 1) % si->sps->poc_cycle_length;",
"\t\t\texpected_poc = poc_cycle_cnt * expected_delta_per_poc_cycle;\n\t\t\tfor (i = 0; i <= frame_num_in_poc_cycle; i++)\n\t\t\t\texpected_poc += si->sps->offset_for_ref_frame[i];\n\t\t}\n\t\telse {\n\t\t\texpected_poc = 0;\n\t\t}",
"\t\tif (!si->nal_ref_idc) expected_poc += si->sps->offset_for_non_ref_pic;",
"\t\tfield_poc[0] = expected_poc + si->delta_poc[0];\n\t\tfield_poc[1] = field_poc[0] + si->sps->offset_for_top_to_bottom_field;\n\t\tif (pic_type == AVC_PIC_FRAME) field_poc[1] += si->delta_poc[1];\n\t}\n\t/*ISO 14496-10 N.11084 8.2.1.3*/\n\telse if (si->sps->poc_type == 2)\n\t{\n\t\tint poc;\n\t\tif (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) {\n\t\t\tpoc = 0;\n\t\t}\n\t\telse {\n\t\t\tconst int abs_frame_num = si->frame_num_offset + si->frame_num;\n\t\t\tpoc = 2 * abs_frame_num;\n\t\t\tif (!si->nal_ref_idc) poc -= 1;\n\t\t}\n\t\tfield_poc[0] = poc;\n\t\tfield_poc[1] = poc;\n\t}",
"\t/*ISO 14496-10 N.11084 eq (8-1)*/\n\tif (pic_type == AVC_PIC_FRAME)\n\t\tsi->poc = MIN(field_poc[0], field_poc[1]);\n\telse if (pic_type == AVC_PIC_FIELD_TOP)\n\t\tsi->poc = field_poc[0];\n\telse\n\t\tsi->poc = field_poc[1];\n}",
"GF_EXPORT\ns32 gf_avc_parse_nalu(GF_BitStream *bs, AVCState *avc)\n{\n\tu8 idr_flag;\n\ts32 slice, ret;\n\tu32 nal_hdr;\n\tAVCSliceInfo n_state;",
"\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tnal_hdr = gf_bs_read_u8(bs);",
"\tslice = 0;\n\tmemcpy(&n_state, &avc->s_info, sizeof(AVCSliceInfo));\n\tavc->last_nal_type_parsed = n_state.nal_unit_type = nal_hdr & 0x1F;\n\tn_state.nal_ref_idc = (nal_hdr >> 5) & 0x3;",
"\tidr_flag = 0;",
"\tswitch (n_state.nal_unit_type) {\n\tcase GF_AVC_NALU_ACCESS_UNIT:\n\tcase GF_AVC_NALU_END_OF_SEQ:\n\tcase GF_AVC_NALU_END_OF_STREAM:\n\t\tret = 1;\n\t\tbreak;",
"\tcase GF_AVC_NALU_SVC_SLICE:\n\t\tSVC_ReadNal_header_extension(bs, &n_state.NalHeader);\n\t\t// slice buffer - read the info and compare.\n\t\t/*ret = */svc_parse_slice(bs, avc, &n_state);\n\t\tif (avc->s_info.nal_ref_idc) {\n\t\t\tn_state.poc_lsb_prev = avc->s_info.poc_lsb;\n\t\t\tn_state.poc_msb_prev = avc->s_info.poc_msb;\n\t\t}\n\t\tavc_compute_poc(&n_state);",
"\t\tif (avc->s_info.poc != n_state.poc) {\n\t\t\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\t\t\treturn 1;\n\t\t}\n\t\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\t\treturn 0;",
"\tcase GF_AVC_NALU_SVC_PREFIX_NALU:\n\t\tSVC_ReadNal_header_extension(bs, &n_state.NalHeader);\n\t\treturn 0;",
"\tcase GF_AVC_NALU_IDR_SLICE:\n\tcase GF_AVC_NALU_NON_IDR_SLICE:\n\tcase GF_AVC_NALU_DP_A_SLICE:\n\tcase GF_AVC_NALU_DP_B_SLICE:\n\tcase GF_AVC_NALU_DP_C_SLICE:\n\t\tslice = 1;\n\t\t/* slice buffer - read the info and compare.*/\n\t\tret = avc_parse_slice(bs, avc, idr_flag, &n_state);\n\t\tif (ret < 0) return ret;\n\t\tret = 0;\n\t\tif (\n\t\t\t((avc->s_info.nal_unit_type > GF_AVC_NALU_IDR_SLICE) || (avc->s_info.nal_unit_type < GF_AVC_NALU_NON_IDR_SLICE))\n\t\t\t&& (avc->s_info.nal_unit_type != GF_AVC_NALU_SVC_SLICE)\n\t\t\t) {\n\t\t\tbreak;\n\t\t}\n\t\tif (avc->s_info.frame_num != n_state.frame_num) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}",
"\t\tif (avc->s_info.field_pic_flag != n_state.field_pic_flag) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif ((avc->s_info.nal_ref_idc != n_state.nal_ref_idc) &&\n\t\t\t(!avc->s_info.nal_ref_idc || !n_state.nal_ref_idc)) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tassert(avc->s_info.sps);",
"\t\tif (avc->s_info.sps->poc_type == n_state.sps->poc_type) {\n\t\t\tif (!avc->s_info.sps->poc_type) {\n\t\t\t\tif (!n_state.bottom_field_flag && (avc->s_info.poc_lsb != n_state.poc_lsb)) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (avc->s_info.delta_poc_bottom != n_state.delta_poc_bottom) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (avc->s_info.sps->poc_type == 1) {\n\t\t\t\tif (avc->s_info.delta_poc[0] != n_state.delta_poc[0]) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (avc->s_info.delta_poc[1] != n_state.delta_poc[1]) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\tif (n_state.nal_unit_type == GF_AVC_NALU_IDR_SLICE) {\n\t\t\tif (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE) { /*IdrPicFlag differs in value*/\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (avc->s_info.idr_pic_id != n_state.idr_pic_id) { /*both IDR and idr_pic_id differs*/\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 0, NULL, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;",
"\tcase GF_AVC_NALU_PIC_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_pps_bs_internal(bs, avc, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\tcase GF_AVC_NALU_SVC_SUBSEQ_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 1, NULL, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\tcase GF_AVC_NALU_SEQ_PARAM_EXT:\n\t\tavc->last_ps_idx = (s32) gf_bs_read_ue(bs);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;",
"\tcase GF_AVC_NALU_SEI:\n\tcase GF_AVC_NALU_FILLER_DATA:\n\t\treturn 0;",
"\tdefault:\n\t\tif (avc->s_info.nal_unit_type <= GF_AVC_NALU_IDR_SLICE) ret = 1;\n\t\t//To detect change of AU when multiple sps and pps in stream\n\t\telse if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEI && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)\n\t\t\tret = 1;\n\t\telse if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEQ_PARAM && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)\n\t\t\tret = 1;\n\t\telse\n\t\t\tret = 0;\n\t\tbreak;\n\t}",
"\t/* save _prev values */\n\tif (ret && avc->s_info.sps) {\n\t\tn_state.frame_num_offset_prev = avc->s_info.frame_num_offset;\n\t\tif ((avc->s_info.sps->poc_type != 2) || (avc->s_info.nal_ref_idc != 0))\n\t\t\tn_state.frame_num_prev = avc->s_info.frame_num;\n\t\tif (avc->s_info.nal_ref_idc) {\n\t\t\tn_state.poc_lsb_prev = avc->s_info.poc_lsb;\n\t\t\tn_state.poc_msb_prev = avc->s_info.poc_msb;\n\t\t}\n\t}\n\tif (slice)\n\t\tavc_compute_poc(&n_state);\n\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\treturn ret;\n}",
"\nu32 gf_media_avc_reformat_sei(u8 *buffer, u32 nal_size, Bool isobmf_rewrite, AVCState *avc)\n{\n\tu32 ptype, psize, hdr, var;\n\tu32 start;\n\tGF_BitStream *bs;\n\tGF_BitStream *bs_dest = NULL;\n\tu8 nhdr;\n\tBool sei_removed = GF_FALSE;\n\tchar store;",
"\thdr = buffer[0];\n\tif ((hdr & 0x1F) != GF_AVC_NALU_SEI) return 0;",
"\tif (isobmf_rewrite) bs_dest = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);",
"\tbs = gf_bs_new(buffer, nal_size, GF_BITSTREAM_READ);\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tnhdr = gf_bs_read_int(bs, 8);\n\tif (bs_dest) gf_bs_write_int(bs_dest, nhdr, 8);",
"\t/*parse SEI*/\n\twhile (gf_bs_available(bs)) {\n\t\tBool do_copy;\n\t\tptype = 0;\n\t\twhile (1) {\n\t\t\tu8 v = gf_bs_read_int(bs, 8);\n\t\t\tptype += v;\n\t\t\tif (v != 0xFF) break;\n\t\t}",
"\t\tpsize = 0;\n\t\twhile (1) {\n\t\t\tu8 v = gf_bs_read_int(bs, 8);\n\t\t\tpsize += v;\n\t\t\tif (v != 0xFF) break;\n\t\t}",
"\t\tstart = (u32)gf_bs_get_position(bs);",
"\t\tdo_copy = 1;",
"\t\tif (start + psize >= nal_size) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] SEI user message type %d size error (%d but %d remain), keeping full SEI untouched\\n\", ptype, psize, nal_size - start));\n\t\t\tif (bs_dest) gf_bs_del(bs_dest);\n\t\t\treturn nal_size;\n\t\t}\n\t\tswitch (ptype) {\n\t\t\t/*remove SEI messages forbidden in MP4*/\n\t\tcase 3: /*filler data*/\n\t\tcase 10: /*sub_seq info*/\n\t\tcase 11: /*sub_seq_layer char*/\n\t\tcase 12: /*sub_seq char*/\n\t\t\tdo_copy = 0;\n\t\t\tsei_removed = GF_TRUE;\n\t\t\tbreak;\n\t\tcase 5: /*user unregistered */\n\t\t\tstore = buffer[start + psize];\n\t\t\tbuffer[start + psize] = 0;\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CODING, (\"[avc-h264] SEI user message %s\\n\", buffer + start + 16));\n\t\t\tbuffer[start + psize] = store;\n\t\t\tbreak;",
"\t\tcase 6: /*recovery point*/\n\t\t\tavc_parse_recovery_point_sei(bs, avc);\n\t\t\tbreak;",
"\t\tcase 1: /*pic_timing*/\n\t\t\tavc_parse_pic_timing_sei(bs, avc);\n\t\t\tbreak;",
"\t\tcase 0: /*buffering period*/\n\t\tcase 2: /*pan scan rect*/\n\t\tcase 4: /*user registered ITU t35*/\n\t\tcase 7: /*def_rec_pic_marking_repetition*/\n\t\tcase 8: /*spare_pic*/\n\t\tcase 9: /*scene info*/\n\t\tcase 13: /*full frame freeze*/\n\t\tcase 14: /*full frame freeze release*/\n\t\tcase 15: /*full frame snapshot*/\n\t\tcase 16: /*progressive refinement segment start*/\n\t\tcase 17: /*progressive refinement segment end*/\n\t\tcase 18: /*motion constrained slice group*/\n\t\tdefault: /*add all unknown SEIs*/\n\t\t\tbreak;\n\t\t}",
"\t\tif (do_copy && bs_dest) {\n\t\t\tvar = ptype;\n\t\t\twhile (var >= 255) {\n\t\t\t\tgf_bs_write_int(bs_dest, 0xFF, 8);\n\t\t\t\tvar -= 255;\n\t\t\t}\n\t\t\tgf_bs_write_int(bs_dest, var, 8);",
"\t\t\tvar = psize;\n\t\t\twhile (var >= 255) {\n\t\t\t\tgf_bs_write_int(bs_dest, 0xFF, 8);\n\t\t\t\tvar -= 255;\n\t\t\t}\n\t\t\tgf_bs_write_int(bs_dest, var, 8);\n\t\t\tgf_bs_seek(bs, start);",
"\t\t\t//bs_read_data does not skip EPB, read byte per byte\n\t\t\tvar = psize;\n\t\t\twhile (var) {\n\t\t\t\tgf_bs_write_u8(bs_dest, gf_bs_read_u8(bs));\n\t\t\t\tvar--;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tgf_bs_seek(bs, start);",
"\t\t\t//bs_skip_bytes does not skip EPB, skip byte per byte\n\t\t\twhile (psize) {\n\t\t\t\tgf_bs_read_u8(bs);\n\t\t\t\tpsize--;\n\t\t\t}\n\t\t}",
"\t\tif (gf_bs_available(bs) <= 2) {\n\t\t\tvar = gf_bs_read_int(bs, 8);\n\t\t\tif (var != 0x80) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] SEI user message has less than 2 bytes remaining but no end of sei found\\n\"));\n\t\t\t}\n\t\t\tif (bs_dest) gf_bs_write_int(bs_dest, 0x80, 8);\n\t\t\tbreak;\n\t\t}\n\t}\n\tgf_bs_del(bs);\n\t//we cannot compare final size and original size since original may have EPB and final does not yet have them\n\tif (bs_dest && sei_removed) {\n\t\tu8 *dst_no_epb = NULL;\n\t\tu32 dst_no_epb_size = 0;\n\t\tgf_bs_get_content(bs_dest, &dst_no_epb, &dst_no_epb_size);\n\t\tnal_size = gf_media_nalu_add_emulation_bytes(buffer, dst_no_epb, dst_no_epb_size);\n\t}\n\tif (bs_dest) gf_bs_del(bs_dest);\n\treturn nal_size;\n}",
"\nstatic u8 avc_hevc_get_sar_idx(u32 w, u32 h)\n{\n\tu32 i, count = GF_ARRAY_LENGTH(avc_hevc_sar);\n\tfor (i = 0; i < count; i++) {\n\t\tif ((avc_hevc_sar[i].w == w) && (avc_hevc_sar[i].h == h))\n\t\t\treturn i;\n\t}\n\treturn 0xFF;\n}",
"static void avc_hevc_rewrite_vui(GF_VUIInfo *vui_info, GF_BitStream *orig, GF_BitStream *mod)\n{\n\t/* VUI present flag*/\n\tBool vui_present_flag = gf_bs_read_int(orig, 1);",
"\t/*setup default values*/\n\tBool aspect_ratio_info_present_flag = 0;\n\ts32 aspect_ratio_idc = -1;\n\tu32 ar_n=0, ar_d=0;\n\tBool overscan_info_present_flag = 0;\n\tu32 overscan_info=0;\n\tu32 video_signal_type_present_flag=0;\n\tu32 video_format = 5;\n\tu32 video_full_range_flag = 0;\n\tu32 colour_description_present_flag = 0;\n\tu32 colour_primaries = 2;\n\tu32 transfer_characteristics = 2;\n\tu32 matrix_coefficients = 2;",
"\t//if VUI is present, read all SAR and overscan values\n\tif (vui_present_flag) { /* VUI found in input bitstream */\n\t\taspect_ratio_info_present_flag = gf_bs_read_int(orig, 1);\n\t\tif (aspect_ratio_info_present_flag) {\n\t\t\taspect_ratio_idc = gf_bs_read_int(orig, 8); /*aspect_ratio_idc*/\n\t\t\tif (aspect_ratio_idc == 255) {\n\t\t\t\tar_n = gf_bs_read_int(orig, 16); /*sar_width*/\n\t\t\t\tar_d = gf_bs_read_int(orig, 16); /*sar_height*/\n\t\t\t}\n\t\t}",
"\t\t/*overscan_info_present_flag */\n\t\toverscan_info_present_flag = gf_bs_read_int(orig, 1);\n\t\tif(overscan_info_present_flag) {\n\t\t\toverscan_info = gf_bs_read_int(orig, 1);\n\t\t}",
"\t\t/* read all video signal related flags first */\n\t\tvideo_signal_type_present_flag = gf_bs_read_int(orig, 1);\n\t\tif(video_signal_type_present_flag) {\n\t\t\tvideo_format = gf_bs_read_int(orig, 3);\n\t\t\tvideo_full_range_flag = gf_bs_read_int(orig, 1);\n\t\t\tcolour_description_present_flag = gf_bs_read_int(orig, 1);\n\t\t\tif(colour_description_present_flag) {\n\t\t\t\tcolour_primaries = gf_bs_read_int(orig, 8);\n\t\t\t\ttransfer_characteristics = gf_bs_read_int(orig, 8);\n\t\t\t\tmatrix_coefficients = gf_bs_read_int(orig, 8);\n\t\t\t}\n\t\t}\n\t}",
"\t//recompute values\n\t//no change\n\tif ((vui_info->ar_num<0) || (vui_info->ar_den<0)) {\n\t}\n\t//remove par\n\telse if ((vui_info->ar_num==0) || (vui_info->ar_den==0)) {\n\t\taspect_ratio_info_present_flag = 0;\n\t}\n\t//set par\n\telse {\n\t\taspect_ratio_info_present_flag = 1;\n\t\tar_n = vui_info->ar_num;\n\t\tar_d = vui_info->ar_den;\n\t\taspect_ratio_idc = avc_hevc_get_sar_idx((u32) ar_n, (u32) ar_d);\n\t}",
"\tif (vui_info->remove_video_info) {\n\t\tvideo_signal_type_present_flag = 0;\n\t}\n\t/* correct the values of each flags */\n\telse if ((vui_info->fullrange==0) && (vui_info->video_format==5) && (vui_info->color_prim==2) && (vui_info->color_tfc==2) && (vui_info->color_matrix==2)) {\n\t\tvideo_signal_type_present_flag = 0; /* all default, nothing to write*/\n\t} else {\n\t\tvideo_signal_type_present_flag = 1;\n\t\tvideo_format = (vui_info->video_format < 0) ? video_format : vui_info->video_format;\n\t\tvideo_full_range_flag = (vui_info->fullrange < 0) ? video_full_range_flag : vui_info->fullrange;\n\t\tif ((vui_info->color_prim==2) && (vui_info->color_tfc==2) && (vui_info->color_matrix==2)) {\n\t\t\tcolour_description_present_flag = 0;\n\t\t} else {\n\t\t\tcolour_description_present_flag = 1;\n\t\t\tcolour_primaries = (vui_info->color_prim < 0) ? colour_primaries : vui_info->color_prim;\n\t\t\ttransfer_characteristics = (vui_info->color_tfc < 0) ? transfer_characteristics : vui_info->color_tfc;\n\t\t\tmatrix_coefficients = (vui_info->color_matrix < 0) ? matrix_coefficients : vui_info->color_matrix;\n\t\t}\n\t\tif ((colour_primaries==2) && (transfer_characteristics==2) && (matrix_coefficients==2)) {\n\t\t\tcolour_description_present_flag = 0;\n\t\t\tif ((video_format==5) && (video_full_range_flag==0))\n\t\t\t\tvideo_signal_type_present_flag = 0;\n\t\t}\n\t}",
"\t//always rewrite VUI\n\tgf_bs_write_int(mod, 1, 1);\n\tgf_bs_write_int(mod, aspect_ratio_info_present_flag, 1);\n\tif (aspect_ratio_info_present_flag) {\n\t\tgf_bs_write_int(mod, aspect_ratio_idc, 8);\n\t\tif (aspect_ratio_idc == 255) {\n\t\t\tgf_bs_write_int(mod, ar_n, 16);\n\t\t\tgf_bs_write_int(mod, ar_d, 16);\n\t\t}\n\t\tif (vui_info->update) {\n\t\t\tvui_info->ar_num = ar_n;\n\t\t\tvui_info->ar_den = ar_d;\n\t\t}\n\t}\n\tgf_bs_write_int(mod, overscan_info_present_flag, 1);\n\tif (overscan_info_present_flag) {\n\t\tgf_bs_write_int(mod, overscan_info, 1);\n\t}",
"\tgf_bs_write_int(mod, video_signal_type_present_flag, 1);\n\tif (video_signal_type_present_flag) {\n\t\tgf_bs_write_int(mod, video_format, 3);\n\t\tgf_bs_write_int(mod, video_full_range_flag, 1);\n\t\tgf_bs_write_int(mod, colour_description_present_flag, 1);",
"\t\tif (colour_description_present_flag) {\n\t\t\tgf_bs_write_int(mod, colour_primaries, 8);\n\t\t\tgf_bs_write_int(mod, transfer_characteristics, 8);\n\t\t\tgf_bs_write_int(mod, matrix_coefficients, 8);\n\t\t}",
"\t\tif (vui_info->update) {\n\t\t\tvui_info->video_format = video_format;\n\t\t\tvui_info->fullrange = video_full_range_flag;\n\t\t\tif (colour_description_present_flag) {\n\t\t\t\tvui_info->color_prim = colour_primaries;\n\t\t\t\tvui_info->color_tfc = transfer_characteristics;\n\t\t\t\tvui_info->color_matrix = matrix_coefficients;\n\t\t\t}\n\t\t}\n\t}",
"\t/*no VUI in input bitstream but we just inserted one, set all remaining vui flags to 0*/\n\tif (!vui_present_flag) {\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*chroma_location_info_present_flag */\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*timing_info_present_flag*/\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*nal_hrd_parameters_present*/\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*vcl_hrd_parameters_present*/\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*pic_struct_present*/\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*bitstream_restriction*/\n\t}\n\t/*otherwise we copy over th bits from the input bitrate*/\n}",
"GF_Err gf_avc_change_vui(GF_AVCConfig *avcc, GF_VUIInfo *vui_info)\n{\n\tGF_BitStream *orig, *mod;\n\tAVCState avc;\n\tu32 i, bit_offset, flag;\n\ts32 idx;\n\tGF_AVCConfigSlot *slc;\n\torig = NULL;",
"\tmemset(&avc, 0, sizeof(AVCState));\n\tavc.sps_active_idx = -1;",
"\ti=0;\n\twhile ((slc = (GF_AVCConfigSlot *)gf_list_enum(avcc->sequenceParameterSets, &i))) {\n\t\tu8 *no_emulation_buf = NULL;\n\t\tu32 no_emulation_buf_size = 0, emulation_bytes = 0;\n\t\tidx = gf_avc_read_sps(slc->data, slc->size, &avc, 0, &bit_offset);\n\t\tif (idx<0) {\n\t\t\tif ( orig )\n\t\t\t\tgf_bs_del(orig);\n\t\t\tcontinue;\n\t\t}",
"\t\t/*SPS still contains emulation bytes*/\n\t\tno_emulation_buf = gf_malloc((slc->size - 1) * sizeof(char));\n\t\tno_emulation_buf_size = gf_media_nalu_remove_emulation_bytes(slc->data + 1, no_emulation_buf, slc->size - 1);",
"\t\torig = gf_bs_new(no_emulation_buf, no_emulation_buf_size, GF_BITSTREAM_READ);\n\t\tgf_bs_read_data(orig, no_emulation_buf, no_emulation_buf_size);\n\t\tgf_bs_seek(orig, 0);\n\t\tmod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);",
"\t\t/*copy over till vui flag*/\n\t\tassert(bit_offset >= 8);\n\t\twhile (bit_offset - 8/*bit_offset doesn't take care of the first byte (NALU type)*/) {\n\t\t\tflag = gf_bs_read_int(orig, 1);\n\t\t\tgf_bs_write_int(mod, flag, 1);\n\t\t\tbit_offset--;\n\t\t}",
"\t\tavc_hevc_rewrite_vui(vui_info, orig, mod);",
"\t\t/*finally copy over remaining*/\n\t\twhile (gf_bs_bits_available(orig)) {\n\t\t\tflag = gf_bs_read_int(orig, 1);\n\t\t\tgf_bs_write_int(mod, flag, 1);\n\t\t}\n\t\tgf_bs_del(orig);\n\t\torig = NULL;\n\t\tgf_free(no_emulation_buf);",
"\t\t/*set anti-emulation*/\n\t\tgf_bs_get_content(mod, &no_emulation_buf, &flag);\n\t\temulation_bytes = gf_media_nalu_emulation_bytes_add_count(no_emulation_buf, flag);\n\t\tif (flag+emulation_bytes+1>slc->size)\n\t\t\tslc->data = (char*)gf_realloc(slc->data, flag+emulation_bytes+1);\n\t\tslc->size = gf_media_nalu_add_emulation_bytes(no_emulation_buf, slc->data + 1, flag) + 1;",
"\t\tgf_bs_del(mod);\n\t\tgf_free(no_emulation_buf);\n\t}\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_media_avc_change_par(GF_AVCConfig *avcc, s32 ar_n, s32 ar_d)\n{\n\tGF_VUIInfo vuii;\n\tmemset(&vuii, 0, sizeof(GF_VUIInfo));\n\tvuii.ar_num = ar_n;\n\tvuii.ar_den = ar_d;\n\tvuii.fullrange = -1;\n\tvuii.video_format = -1;\n\tvuii.color_prim = -1;\n\tvuii.color_tfc = -1;\n\tvuii.color_matrix = -1;\n\treturn gf_avc_change_vui(avcc, &vuii);\n}",
"GF_EXPORT\nGF_Err gf_media_avc_change_color(GF_AVCConfig *avcc, s32 fullrange, s32 vidformat, s32 colorprim, s32 transfer, s32 colmatrix)\n{\n\tGF_VUIInfo vuii;\n\tmemset(&vuii, 0, sizeof(GF_VUIInfo));\n\tvuii.ar_num = -1;\n\tvuii.ar_den = -1;\n\tvuii.fullrange = fullrange;\n\tvuii.video_format = vidformat;\n\tvuii.color_prim = colorprim;\n\tvuii.color_tfc = transfer;\n\tvuii.color_matrix = colmatrix;\n\treturn gf_avc_change_vui(avcc, &vuii);\n}",
"\nGF_EXPORT\nGF_Err gf_avc_get_sps_info(u8 *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)\n{\n\tAVCState avc;\n\ts32 idx;\n\tmemset(&avc, 0, sizeof(AVCState));\n\tavc.sps_active_idx = -1;",
"\tidx = gf_avc_read_sps(sps_data, sps_size, &avc, 0, NULL);\n\tif (idx < 0) {\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\tif (sps_id) *sps_id = idx;",
"\tif (width) *width = avc.sps[idx].width;\n\tif (height) *height = avc.sps[idx].height;\n\tif (par_n) *par_n = avc.sps[idx].vui.par_num ? avc.sps[idx].vui.par_num : (u32)-1;\n\tif (par_d) *par_d = avc.sps[idx].vui.par_den ? avc.sps[idx].vui.par_den : (u32)-1;",
"\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_avc_get_pps_info(u8 *pps_data, u32 pps_size, u32 *pps_id, u32 *sps_id)\n{\n\tGF_BitStream *bs;\n\tGF_Err e = GF_OK;",
"\tbs = gf_bs_new(pps_data, pps_size, GF_BITSTREAM_READ);\n\tif (!bs) {\n\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\tgoto exit;\n\t}\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\t/*nal hdr*/ gf_bs_read_int(bs, 8);",
"\t*pps_id = gf_bs_read_ue(bs);\n\t*sps_id = gf_bs_read_ue(bs);",
"exit:\n\tgf_bs_del(bs);\n\treturn e;\n}",
"#ifndef GPAC_DISABLE_HEVC",
"/**********\nHEVC parsing\n**********/",
"Bool gf_hevc_slice_is_intra(HEVCState *hevc)\n{\n\tswitch (hevc->s_info.nal_unit_type) {\n\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\tcase GF_HEVC_NALU_SLICE_CRA:\n\t\treturn GF_TRUE;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n}",
"Bool gf_hevc_slice_is_IDR(HEVCState *hevc)\n{\n\tif (hevc->sei.recovery_point.valid)\n\t{\n\t\thevc->sei.recovery_point.valid = 0;\n\t\treturn GF_TRUE;\n\t}\n\tswitch (hevc->s_info.nal_unit_type) {\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\t\treturn GF_TRUE;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n}",
"static Bool hevc_parse_short_term_ref_pic_set(GF_BitStream *bs, HEVC_SPS *sps, u32 idx_rps)\n{\n\tu32 i;\n\tBool inter_ref_pic_set_prediction_flag = 0;\n\tif (idx_rps != 0)\n\t\tinter_ref_pic_set_prediction_flag = gf_bs_read_int_log_idx(bs, 1, \"inter_ref_pic_set_prediction_flag\", idx_rps);",
"\tif (inter_ref_pic_set_prediction_flag) {\n\t\tHEVC_ReferencePictureSets *ref_ps, *rps;\n\t\tu32 delta_idx_minus1 = 0;\n\t\tu32 ref_idx;\n\t\tu32 delta_rps_sign;\n\t\tu32 abs_delta_rps_minus1, nb_ref_pics;\n\t\ts32 deltaRPS;\n\t\tu32 k = 0, k0 = 0, k1 = 0;\n\t\tif (idx_rps == sps->num_short_term_ref_pic_sets)\n\t\t\tdelta_idx_minus1 = gf_bs_read_ue_log_idx(bs, \"delta_idx_minus1\", idx_rps);",
"\t\tassert(delta_idx_minus1 <= idx_rps - 1);\n\t\tref_idx = idx_rps - 1 - delta_idx_minus1;\n\t\tdelta_rps_sign = gf_bs_read_int_log_idx(bs, 1, \"delta_rps_sign\", idx_rps);\n\t\tabs_delta_rps_minus1 = gf_bs_read_ue_log_idx(bs, \"abs_delta_rps_minus1\", idx_rps);\n\t\tdeltaRPS = (1 - (delta_rps_sign << 1)) * (abs_delta_rps_minus1 + 1);",
"\t\trps = &sps->rps[idx_rps];\n\t\tref_ps = &sps->rps[ref_idx];\n\t\tnb_ref_pics = ref_ps->num_negative_pics + ref_ps->num_positive_pics;\n\t\tfor (i = 0; i <= nb_ref_pics; i++) {\n\t\t\ts32 ref_idc;\n\t\t\ts32 used_by_curr_pic_flag = gf_bs_read_int_log_idx2(bs, 1, \"used_by_curr_pic_flag\", idx_rps, i);\n\t\t\tref_idc = used_by_curr_pic_flag ? 1 : 0;\n\t\t\tif (!used_by_curr_pic_flag) {\n\t\t\t\tused_by_curr_pic_flag = gf_bs_read_int_log_idx2(bs, 1, \"used_by_curr_pic_flag\", idx_rps, i);\n\t\t\t\tref_idc = used_by_curr_pic_flag << 1;\n\t\t\t}\n\t\t\tif ((ref_idc == 1) || (ref_idc == 2)) {\n\t\t\t\ts32 deltaPOC = deltaRPS;\n\t\t\t\tif (i < nb_ref_pics)\n\t\t\t\t\tdeltaPOC += ref_ps->delta_poc[i];",
"\t\t\t\trps->delta_poc[k] = deltaPOC;",
"\t\t\t\tif (deltaPOC < 0) k0++;\n\t\t\t\telse k1++;",
"\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\trps->num_negative_pics = k0;\n\t\trps->num_positive_pics = k1;\n\t}\n\telse {\n\t\ts32 prev = 0, poc;\n\t\tsps->rps[idx_rps].num_negative_pics = gf_bs_read_ue_log_idx(bs, \"num_negative_pics\", idx_rps);\n\t\tsps->rps[idx_rps].num_positive_pics = gf_bs_read_ue_log_idx(bs, \"num_positive_pics\", idx_rps);\n\t\tif (sps->rps[idx_rps].num_negative_pics > 16)\n\t\t\treturn GF_FALSE;\n\t\tif (sps->rps[idx_rps].num_positive_pics > 16)\n\t\t\treturn GF_FALSE;\n\t\tfor (i = 0; i < sps->rps[idx_rps].num_negative_pics; i++) {\n\t\t\tu32 delta_poc_s0_minus1 = gf_bs_read_ue_log_idx2(bs, \"delta_poc_s0_minus1\", idx_rps, i);\n\t\t\tpoc = prev - delta_poc_s0_minus1 - 1;\n\t\t\tprev = poc;\n\t\t\tsps->rps[idx_rps].delta_poc[i] = poc;\n\t\t\tgf_bs_read_int_log_idx2(bs, 1, \"delta_poc_s0_minus1\", idx_rps, i);\n\t\t}\n\t\tfor (i = 0; i < sps->rps[idx_rps].num_positive_pics; i++) {\n\t\t\tu32 delta_poc_s1_minus1 = gf_bs_read_ue_log_idx2(bs, \"delta_poc_s1_minus1\" , idx_rps, i);\n\t\t\tpoc = prev + delta_poc_s1_minus1 + 1;\n\t\t\tprev = poc;\n\t\t\tsps->rps[idx_rps].delta_poc[i] = poc;\n\t\t\tgf_bs_read_int_log_idx2(bs, 1, \"used_by_curr_pic_s1_flag\", idx_rps, i);\n\t\t}\n\t}\n\treturn GF_TRUE;\n}",
"void hevc_pred_weight_table(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *si, HEVC_PPS *pps, HEVC_SPS *sps, u32 num_ref_idx_l0_active, u32 num_ref_idx_l1_active)\n{\n\tu32 i, num_ref_idx;\n\tBool first_pass = GF_TRUE;\n\tu8 luma_weights[20], chroma_weights[20];\n\tu32 ChromaArrayType = sps->separate_colour_plane_flag ? 0 : sps->chroma_format_idc;",
"\tnum_ref_idx = num_ref_idx_l0_active;",
"\tgf_bs_read_ue_log(bs, \"luma_log2_weight_denom\");\n\tif (ChromaArrayType != 0)\n\t\tgf_bs_read_se_log(bs, \"delta_chroma_log2_weight_denom\");",
"parse_weights:\n\tfor (i = 0; i < num_ref_idx; i++) {\n\t\tluma_weights[i] = gf_bs_read_int_log_idx(bs, 1, \"luma_weights\", i);\n\t\t//infered to be 0 if not present\n\t\tchroma_weights[i] = 0;\n\t}\n\tif (ChromaArrayType != 0) {\n\t\tfor (i = 0; i < num_ref_idx; i++) {\n\t\t\tchroma_weights[i] = gf_bs_read_int_log_idx(bs, 1, \"chroma_weights\", i);\n\t\t}\n\t}\n\tfor (i = 0; i < num_ref_idx; i++) {\n\t\tif (luma_weights[i]) {\n\t\t\tgf_bs_read_se_log_idx(bs, \"delta_luma_weight_l0\", i);\n\t\t\tgf_bs_read_se_log_idx(bs, \"luma_offset_l0\", i);\n\t\t}\n\t\tif (chroma_weights[i]) {\n\t\t\tgf_bs_read_se_log_idx(bs, \"delta_chroma_weight_l0_0\", i);\n\t\t\tgf_bs_read_se_log_idx(bs, \"delta_chroma_offset_l0_0\", i);",
"\t\t\tgf_bs_read_se_log_idx(bs, \"delta_chroma_weight_l0_1\", i);\n\t\t\tgf_bs_read_se_log_idx(bs, \"delta_chroma_offset_l0_1\", i);\n\t\t}\n\t}",
"\tif (si->slice_type == GF_HEVC_SLICE_TYPE_B) {\n\t\tif (!first_pass) return;\n\t\tfirst_pass = GF_FALSE;\n\t\tnum_ref_idx = num_ref_idx_l1_active;\n\t\tgoto parse_weights;\n\t}\n}",
"static\nBool ref_pic_lists_modification(GF_BitStream *bs, u32 slice_type, u32 num_ref_idx_l0_active, u32 num_ref_idx_l1_active)\n{\n\t//u32 i;\n\tBool ref_pic_list_modification_flag_l0 = gf_bs_read_int_log(bs, 1, \"ref_pic_list_modification_flag_l0\");\n\tif (ref_pic_list_modification_flag_l0) {\n\t\t/*for (i=0; i<num_ref_idx_l0_active; i++) {\n\t\t\tlist_entry_l0[i] = *//*gf_bs_read_int(bs, (u32)ceil(log(getNumPicTotalCurr())/log(2)));\n\t\t}*/\n\t\treturn GF_FALSE;\n\t}\n\tif (slice_type == GF_HEVC_SLICE_TYPE_B) {\n\t\tBool ref_pic_list_modification_flag_l1 = gf_bs_read_int_log(bs, 1, \"ref_pic_list_modification_flag_l1\");\n\t\tif (ref_pic_list_modification_flag_l1) {\n\t\t\t/*for (i=0; i<num_ref_idx_l1_active; i++) {\n\t\t\t\tlist_entry_l1[i] = *//*gf_bs_read_int(bs, (u32)ceil(log(getNumPicTotalCurr()) / log(2)));\n\t\t\t}*/\n\t\t\treturn GF_FALSE;\n\t\t}\n\t}",
"\treturn GF_TRUE;\n}",
"static\ns32 hevc_parse_slice_segment(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *si)\n{\n\tu32 i, j;\n\tu32 num_ref_idx_l0_active = 0, num_ref_idx_l1_active = 0;\n\tHEVC_PPS *pps;\n\tHEVC_SPS *sps;\n\ts32 pps_id;\n\tBool RapPicFlag = GF_FALSE;\n\tBool IDRPicFlag = GF_FALSE;",
"\tsi->first_slice_segment_in_pic_flag = gf_bs_read_int_log(bs, 1, \"first_slice_segment_in_pic_flag\");",
"\tswitch (si->nal_unit_type) {\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\t\tIDRPicFlag = GF_TRUE;\n\t\tRapPicFlag = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\tcase GF_HEVC_NALU_SLICE_CRA:\n\t\tRapPicFlag = GF_TRUE;\n\t\tbreak;\n\t}",
"\tif (RapPicFlag) {\n\t\tgf_bs_read_int_log(bs, 1, \"no_output_of_prior_pics_flag\");\n\t}",
"\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\tif ((pps_id<0) || (pps_id >= 64))\n\t\treturn -1;",
"\tpps = &hevc->pps[pps_id];\n\tsps = &hevc->sps[pps->sps_id];\n\tsi->sps = sps;\n\tsi->pps = pps;",
"\tif (!si->first_slice_segment_in_pic_flag && pps->dependent_slice_segments_enabled_flag) {\n\t\tsi->dependent_slice_segment_flag = gf_bs_read_int_log(bs, 1, \"dependent_slice_segment_flag\");\n\t}\n\telse {\n\t\tsi->dependent_slice_segment_flag = GF_FALSE;\n\t}",
"\tif (!si->first_slice_segment_in_pic_flag) {\n\t\tsi->slice_segment_address = gf_bs_read_int_log(bs, sps->bitsSliceSegmentAddress, \"slice_segment_address\");\n\t}\n\telse {\n\t\tsi->slice_segment_address = 0;\n\t}",
"\tif (!si->dependent_slice_segment_flag) {\n\t\tBool deblocking_filter_override_flag = 0;\n\t\tBool slice_temporal_mvp_enabled_flag = 0;\n\t\tBool slice_sao_luma_flag = 0;\n\t\tBool slice_sao_chroma_flag = 0;\n\t\tBool slice_deblocking_filter_disabled_flag = 0;",
"\t\t//\"slice_reserved_undetermined_flag[]\"\n\t\tgf_bs_read_int_log(bs, pps->num_extra_slice_header_bits, \"slice_reserved_undetermined_flag\");",
"\t\tsi->slice_type = gf_bs_read_ue_log(bs, \"slice_type\");",
"\t\tif (pps->output_flag_present_flag)\n\t\t\tgf_bs_read_int_log(bs, 1, \"pic_output_flag\");",
"\t\tif (sps->separate_colour_plane_flag == 1)\n\t\t\tgf_bs_read_int_log(bs, 2, \"colour_plane_id\");",
"\t\tif (IDRPicFlag) {\n\t\t\tsi->poc_lsb = 0;",
"\t\t\t//if not asked to parse full header, abort since we know the poc\n\t\t\tif (!hevc->full_slice_header_parse) return 0;",
"\t\t}\n\t\telse {\n\t\t\tsi->poc_lsb = gf_bs_read_int_log(bs, sps->log2_max_pic_order_cnt_lsb, \"poc_lsb\");",
"\t\t\t//if not asked to parse full header, abort once we have the poc\n\t\t\tif (!hevc->full_slice_header_parse) return 0;",
"\t\t\tif (gf_bs_read_int_log(bs, 1, \"short_term_ref_pic_set_sps_flag\") == 0) {\n\t\t\t\tBool ret = hevc_parse_short_term_ref_pic_set(bs, sps, sps->num_short_term_ref_pic_sets);\n\t\t\t\tif (!ret)\n\t\t\t\t\treturn -1;\n\t\t\t}\n\t\t\telse if (sps->num_short_term_ref_pic_sets > 1) {\n\t\t\t\tu32 numbits = 0;",
"\t\t\t\twhile ((u32)(1 << numbits) < sps->num_short_term_ref_pic_sets)\n\t\t\t\t\tnumbits++;\n\t\t\t\tif (numbits > 0)\n\t\t\t\t\tgf_bs_read_int_log(bs, numbits, \"short_term_ref_pic_set_idx\");\n\t\t\t\t/*else\n\t\t\t\t\tshort_term_ref_pic_set_idx = 0;*/\n\t\t\t}\n\t\t\tif (sps->long_term_ref_pics_present_flag) {\n\t\t\t\tu8 DeltaPocMsbCycleLt[32];\n\t\t\t\tu32 num_long_term_sps = 0;\n\t\t\t\tu32 num_long_term_pics = 0;",
"\t\t\t\tmemset(DeltaPocMsbCycleLt, 0, sizeof(u8) * 32);\n\t\t\t\t\n\t\t\t\tif (sps->num_long_term_ref_pic_sps > 0) {\n\t\t\t\t\tnum_long_term_sps = gf_bs_read_ue_log(bs, \"num_long_term_sps\");\n\t\t\t\t}\n\t\t\t\tnum_long_term_pics = gf_bs_read_ue_log(bs, \"num_long_term_pics\");",
"\t\t\t\tfor (i = 0; i < num_long_term_sps + num_long_term_pics; i++) {\n\t\t\t\t\tif (i < num_long_term_sps) {\n\t\t\t\t\t\tif (sps->num_long_term_ref_pic_sps > 1)\n\t\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, gf_get_bit_size(sps->num_long_term_ref_pic_sps), \"lt_idx_sps\", i);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, sps->log2_max_pic_order_cnt_lsb, \"PocLsbLt\", i);\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 1, \"UsedByCurrPicLt\", i);\n\t\t\t\t\t}\n\t\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"delta_poc_msb_present_flag\", i)) {\n\t\t\t\t\t\tif (i == 0 || i == num_long_term_sps)\n\t\t\t\t\t\t\tDeltaPocMsbCycleLt[i] = gf_bs_read_ue_log_idx(bs, \"DeltaPocMsbCycleLt\", i);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tDeltaPocMsbCycleLt[i] = gf_bs_read_ue_log_idx(bs, \"DeltaPocMsbCycleLt\", i) + DeltaPocMsbCycleLt[i - 1];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (sps->temporal_mvp_enable_flag)\n\t\t\t\tslice_temporal_mvp_enabled_flag = gf_bs_read_int_log(bs, 1, \"slice_temporal_mvp_enabled_flag\");\n\t\t}\n\t\tif (sps->sample_adaptive_offset_enabled_flag) {\n\t\t\tu32 ChromaArrayType = sps->separate_colour_plane_flag ? 0 : sps->chroma_format_idc;\n\t\t\tslice_sao_luma_flag = gf_bs_read_int_log(bs, 1, \"slice_sao_luma_flag\");\n\t\t\tif (ChromaArrayType != 0)\n\t\t\t\tslice_sao_chroma_flag = gf_bs_read_int_log(bs, 1, \"slice_sao_chroma_flag\");\n\t\t}",
"\t\tif (si->slice_type == GF_HEVC_SLICE_TYPE_P || si->slice_type == GF_HEVC_SLICE_TYPE_B) {\n\t\t\t//u32 NumPocTotalCurr;\n\t\t\tnum_ref_idx_l0_active = pps->num_ref_idx_l0_default_active;\n\t\t\tnum_ref_idx_l1_active = 0;\n\t\t\tif (si->slice_type == GF_HEVC_SLICE_TYPE_B)\n\t\t\t\tnum_ref_idx_l1_active = pps->num_ref_idx_l1_default_active;",
"\t\t\tif (gf_bs_read_int_log(bs, 1, \"num_ref_idx_active_override_flag\")) {\n\t\t\t\tnum_ref_idx_l0_active = 1 + gf_bs_read_ue_log(bs, \"num_ref_idx_l0_active\");\n\t\t\t\tif (si->slice_type == GF_HEVC_SLICE_TYPE_B)\n\t\t\t\t\tnum_ref_idx_l1_active = 1 + gf_bs_read_ue_log(bs, \"num_ref_idx_l1_active\");\n\t\t\t}",
"\t\t\tif (pps->lists_modification_present_flag /*TODO: && NumPicTotalCurr > 1*/) {\n\t\t\t\tif (!ref_pic_lists_modification(bs, si->slice_type, num_ref_idx_l0_active, num_ref_idx_l1_active)) {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[hevc] ref_pic_lists_modification( ) not implemented\\n\"));\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t}",
"\t\t\tif (si->slice_type == GF_HEVC_SLICE_TYPE_B)\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"mvd_l1_zero_flag\");\n\t\t\tif (pps->cabac_init_present_flag)\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"cabac_init_flag\");",
"\t\t\tif (slice_temporal_mvp_enabled_flag) {\n\t\t\t\t// When collocated_from_l0_flag is not present, it is inferred to be equal to 1.\n\t\t\t\tBool collocated_from_l0_flag = 1;\n\t\t\t\tif (si->slice_type == GF_HEVC_SLICE_TYPE_B)\n\t\t\t\t\tcollocated_from_l0_flag = gf_bs_read_int_log(bs, 1, \"collocated_from_l0_flag\");",
"\t\t\t\tif ((collocated_from_l0_flag && (num_ref_idx_l0_active > 1))\n\t\t\t\t\t|| (!collocated_from_l0_flag && (num_ref_idx_l1_active > 1))\n\t\t\t\t) {\n\t\t\t\t\tgf_bs_read_ue_log(bs, \"collocated_ref_idx\");\n\t\t\t\t}\n\t\t\t}",
"\t\t\tif ((pps->weighted_pred_flag && si->slice_type == GF_HEVC_SLICE_TYPE_P)\n\t\t\t\t|| (pps->weighted_bipred_flag && si->slice_type == GF_HEVC_SLICE_TYPE_B)\n\t\t\t\t) {\n\t\t\t\thevc_pred_weight_table(bs, hevc, si, pps, sps, num_ref_idx_l0_active, num_ref_idx_l1_active);\n\t\t\t}\n\t\t\tgf_bs_read_ue_log(bs, \"five_minus_max_num_merge_cand\");\n\t\t}\n\t\tsi->slice_qp_delta_start_bits = (s32) (gf_bs_get_position(bs) - 1) * 8 + gf_bs_get_bit_position(bs);\n\t\tsi->slice_qp_delta = gf_bs_read_se_log(bs, \"slice_qp_delta\");",
"\t\tif (pps->slice_chroma_qp_offsets_present_flag) {\n\t\t\tgf_bs_read_se_log(bs, \"slice_cb_qp_offset\");\n\t\t\tgf_bs_read_se_log(bs, \"slice_cr_qp_offset\");\n\t\t}\n\t\tif (pps->deblocking_filter_override_enabled_flag) {\n\t\t\tdeblocking_filter_override_flag = gf_bs_read_int_log(bs, 1, \"deblocking_filter_override_flag\");\n\t\t}",
"\t\tif (deblocking_filter_override_flag) {\n\t\t\tslice_deblocking_filter_disabled_flag = gf_bs_read_int_log(bs, 1, \"slice_deblocking_filter_disabled_flag\");\n\t\t\tif (!slice_deblocking_filter_disabled_flag) {\n\t\t\t\tgf_bs_read_se_log(bs, \"slice_beta_offset_div2\");\n\t\t\t\tgf_bs_read_se_log(bs, \"slice_tc_offset_div2\");\n\t\t\t}\n\t\t}\n\t\tif (pps->loop_filter_across_slices_enabled_flag\n\t\t\t&& (slice_sao_luma_flag || slice_sao_chroma_flag || !slice_deblocking_filter_disabled_flag)\n\t\t) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"slice_loop_filter_across_slices_enabled_flag\");\n\t\t}\n\t}\n\t//dependent slice segment\n\telse {\n\t\t//if not asked to parse full header, abort\n\t\tif (!hevc->full_slice_header_parse) return 0;\n\t}",
"\tsi->entry_point_start_bits = ((u32)gf_bs_get_position(bs) - 1) * 8 + gf_bs_get_bit_position(bs);",
"\tif (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag) {\n\t\tu32 num_entry_point_offsets = gf_bs_read_ue_log(bs, \"num_entry_point_offsets\");\n\t\tif (num_entry_point_offsets > 0) {\n\t\t\tu32 offset = gf_bs_read_ue_log(bs, \"offset\") + 1;\n\t\t\tu32 segments = offset >> 4;\n\t\t\ts32 remain = (offset & 15);",
"\t\t\tfor (i = 0; i < num_entry_point_offsets; i++) {\n\t\t\t\t//u32 res = 0;\n\t\t\t\tfor (j = 0; j < segments; j++) {\n\t\t\t\t\t//res <<= 16;\n\t\t\t\t\t/*res +=*/ gf_bs_read_int(bs, 16);\n\t\t\t\t}\n\t\t\t\tif (remain) {\n\t\t\t\t\t//res <<= remain;\n\t\t\t\t\t/* res += */ gf_bs_read_int(bs, remain);\n\t\t\t\t}\n\t\t\t\t// entry_point_offset = val + 1; // +1; // +1 to get the size\n\t\t\t}\n\t\t}\n\t}",
"\tif (pps->slice_segment_header_extension_present_flag) {\n\t\tu32 size_ext = gf_bs_read_ue_log(bs, \"size_ext\");\n\t\twhile (size_ext) {\n\t\t\tgf_bs_read_int(bs, 8);\n\t\t\tsize_ext--;\n\t\t}\n\t}",
"\tsi->header_size_bits = (gf_bs_get_position(bs) - 1) * 8 + gf_bs_get_bit_position(bs); // av_parser.c modified on 16 jan. 2019 ",
"\tif (gf_bs_read_int_log(bs, 1, \"byte_align\") == 0) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"Error parsing slice header: byte_align not found at end of header !\\n\"));\n\t}",
"\tgf_bs_align(bs);\n\tsi->payload_start_offset = (s32)gf_bs_get_position(bs);\n\treturn 0;\n}",
"static void gf_hevc_vvc_parse_sei(char *buffer, u32 nal_size, HEVCState *hevc, VVCState *vvc)\n{\n\tu32 ptype, psize, hdr;\n\tu64 start;\n\tGF_BitStream *bs;",
"\thdr = buffer[0];\n\tif (((hdr & 0x7e) >> 1) != GF_HEVC_NALU_SEI_PREFIX) return;",
"\tbs = gf_bs_new(buffer, nal_size, GF_BITSTREAM_READ);\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tgf_bs_read_int(bs, 16);",
"\t/*parse SEI*/\n\twhile (gf_bs_available(bs)) {\n\t\tu32 consumed;\n\t\tptype = 0;\n\t\twhile (gf_bs_peek_bits(bs, 8, 0)==0xFF) {\n\t\t\tgf_bs_read_int(bs, 8);\n\t\t\tptype += 255;\n\t\t}\n\t\tptype += gf_bs_read_int(bs, 8);\n\t\tpsize = 0;\n\t\twhile (gf_bs_peek_bits(bs, 8, 0)==0xFF) {\n\t\t\tgf_bs_read_int(bs, 8);\n\t\t\tpsize += 255;\n\t\t}\n\t\tpsize += gf_bs_read_int(bs, 8);",
"\t\tstart = gf_bs_get_position(bs);\n\t\tif (start+psize >= nal_size) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[%s] SEI user message type %d size error (%d but %d remain), skipping SEI message\\n\", hevc ? \"HEVC\" : \"VVC\", ptype, psize, nal_size-start));\n\t\t\tbreak;\n\t\t}",
"\t\tswitch (ptype) {\n\t\tcase 4: /*user registered ITU-T T35*/\n\t\t\tif (hevc) {\n\t\t\t\tavc_parse_itu_t_t35_sei(bs, &hevc->sei.dovi);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}",
"\t\tgf_bs_align(bs);\n\t\tconsumed = (u32) (gf_bs_get_position(bs) - start);\n\t\tpsize-=consumed;\n\t\tgf_bs_skip_bytes(bs, psize);\n\t\tif (gf_bs_available(bs) <= 2)\n\t\t\tbreak;\n\t}\n\tgf_bs_del(bs);\n}",
"void gf_hevc_parse_sei(char *buffer, u32 nal_size, HEVCState *hevc)\n{\n\tgf_hevc_vvc_parse_sei(buffer, nal_size, hevc, NULL);\n}",
"static void hevc_compute_poc(HEVCSliceInfo *si)\n{\n\tu32 max_poc_lsb = 1 << (si->sps->log2_max_pic_order_cnt_lsb);",
"\t/*POC reset for IDR frames, NOT for CRA*/\n\tswitch (si->nal_unit_type) {\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\t\tsi->poc_lsb_prev = 0;\n\t\tsi->poc_msb_prev = 0;\n\t\tbreak;\n\t}",
"\tif ((si->poc_lsb < si->poc_lsb_prev) && (si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2))\n\t\tsi->poc_msb = si->poc_msb_prev + max_poc_lsb;\n\telse if ((si->poc_lsb > si->poc_lsb_prev) && (si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))\n\t\tsi->poc_msb = si->poc_msb_prev - max_poc_lsb;\n\telse\n\t\tsi->poc_msb = si->poc_msb_prev;",
"\tswitch (si->nal_unit_type) {\n\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\t\tsi->poc_msb = 0;\n\t\tbreak;\n\t}\n\tsi->poc = si->poc_msb + si->poc_lsb;\n}",
"\nstatic Bool hevc_parse_nal_header(GF_BitStream *bs, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tu32 val;\n\tval = gf_bs_read_int_log(bs, 1, \"forbidden_zero\");\n\tif (val) return GF_FALSE;",
"\tval = gf_bs_read_int_log(bs, 6, \"nuh_type\");\n\tif (nal_unit_type) *nal_unit_type = val;",
"\tval = gf_bs_read_int_log(bs, 6, \"layerID\");\n\tif (layer_id) *layer_id = val;",
"\tval = gf_bs_read_int_log(bs, 3, \"temporalID\");\n\tif (!val)\n\t\treturn GF_FALSE;\n\tval -= 1;\n\tif (temporal_id) *temporal_id = val;\n\treturn GF_TRUE;\n}",
"\nvoid hevc_profile_tier_level(GF_BitStream *bs, Bool ProfilePresentFlag, u8 MaxNumSubLayersMinus1, HEVC_ProfileTierLevel *ptl, u32 idx)\n{\n\tu32 i;\n\tif (ProfilePresentFlag) {\n\t\tptl->profile_space = gf_bs_read_int_log_idx(bs, 2, \"profile_space\", idx);\n\t\tptl->tier_flag = gf_bs_read_int_log_idx(bs, 1, \"tier_flag\", idx);\n\t\tptl->profile_idc = gf_bs_read_int_log_idx(bs, 5, \"profile_idc\", idx);",
"\t\tptl->profile_compatibility_flag = gf_bs_read_int_log_idx(bs, 32, \"profile_compatibility_flag\", idx);",
"\t\tptl->general_progressive_source_flag = gf_bs_read_int_log_idx(bs, 1, \"general_progressive_source_flag\", idx);\n\t\tptl->general_interlaced_source_flag = gf_bs_read_int_log_idx(bs, 1, \"general_interlaced_source_flag\", idx);\n\t\tptl->general_non_packed_constraint_flag = gf_bs_read_int_log_idx(bs, 1, \"general_non_packed_constraint_flag\", idx);\n\t\tptl->general_frame_only_constraint_flag = gf_bs_read_int_log_idx(bs, 1, \"general_frame_only_constraint_flag\", idx);\n\t\tptl->general_reserved_44bits = gf_bs_read_long_int(bs, 44);\n\t}\n\tptl->level_idc = gf_bs_read_int_log(bs, 8, \"level_idc\");\n\tfor (i = 0; i < MaxNumSubLayersMinus1; i++) {\n\t\tptl->sub_ptl[i].profile_present_flag = gf_bs_read_int_log_idx2(bs, 1, \"profile_present_flag\", idx, i);\n\t\tptl->sub_ptl[i].level_present_flag = gf_bs_read_int_log_idx2(bs, 1, \"level_present_flag\", idx, i);\n\t}\n\tif (MaxNumSubLayersMinus1 > 0) {\n\t\tfor (i = MaxNumSubLayersMinus1; i < 8; i++) {\n\t\t\t/*reserved_zero_2bits*/gf_bs_read_int(bs, 2);\n\t\t}\n\t}",
"\tfor (i = 0; i < MaxNumSubLayersMinus1; i++) {\n\t\tif (ptl->sub_ptl[i].profile_present_flag) {\n\t\t\tptl->sub_ptl[i].profile_space = gf_bs_read_int_log_idx2(bs, 2, \"sublayer_profile_space\", idx, i);\n\t\t\tptl->sub_ptl[i].tier_flag = gf_bs_read_int_log_idx2(bs, 1, \"sublayer_tier_flag\", idx, i);\n\t\t\tptl->sub_ptl[i].profile_idc = gf_bs_read_int_log_idx2(bs, 5, \"sublayer_profile_idc\", idx, i);\n\t\t\tptl->sub_ptl[i].profile_compatibility_flag = gf_bs_read_int_log_idx2(bs, 32, \"sublayer_profile_compatibility_flag\", idx, i);\n\t\t\t/*ptl->sub_ptl[i].progressive_source_flag =*/ gf_bs_read_int_log_idx2(bs, 1, \"sublayer_progressive_source_flag\", idx, i);\n\t\t\t/*ptl->sub_ptl[i].interlaced_source_flag =*/ gf_bs_read_int_log_idx2(bs, 1, \"sublayer_interlaced_source_flag\", idx, i);\n\t\t\t/*ptl->sub_ptl[i].non_packed_constraint_flag =*/ gf_bs_read_int_log_idx2(bs, 1, \"sublayer_non_packed_constraint_flag\", idx, i);\n\t\t\t/*ptl->sub_ptl[i].frame_only_constraint_flag =*/ gf_bs_read_int_log_idx2(bs, 1, \"sublayer_frame_only_constraint_flag\", idx, i);\n\t\t\t/*ptl->sub_ptl[i].reserved_44bits =*/ gf_bs_read_long_int(bs, 44);\n\t\t}\n\t\tif (ptl->sub_ptl[i].level_present_flag)\n\t\t\tptl->sub_ptl[i].level_idc = gf_bs_read_int_log_idx2(bs, 8, \"sublayer_level_idc\", idx, i);\n\t}\n}",
"static u32 scalability_type_to_idx(HEVC_VPS *vps, u32 scalability_type)\n{\n\tu32 idx = 0, type;\n\tfor (type = 0; type < scalability_type; type++) {\n\t\tidx += (vps->scalability_mask[type] ? 1 : 0);\n\t}\n\treturn idx;\n}",
"#define LHVC_VIEW_ORDER_INDEX 1\n#define LHVC_SCALABILITY_INDEX\t2",
"static u32 lhvc_get_scalability_id(HEVC_VPS *vps, u32 layer_id_in_vps, u32 scalability_type)\n{\n\tu32 idx;\n\tif (!vps->scalability_mask[scalability_type]) return 0;\n\tidx = scalability_type_to_idx(vps, scalability_type);\n\treturn vps->dimension_id[layer_id_in_vps][idx];\n}",
"static u32 lhvc_get_view_index(HEVC_VPS *vps, u32 id)\n{\n\treturn lhvc_get_scalability_id(vps, vps->layer_id_in_vps[id], LHVC_VIEW_ORDER_INDEX);\n}",
"static u32 lhvc_get_num_views(HEVC_VPS *vps)\n{\n\tu32 numViews = 1, i;\n\tfor (i = 0; i < vps->max_layers; i++) {\n\t\tu32 layer_id = vps->layer_id_in_nuh[i];\n\t\tif (i > 0 && (lhvc_get_view_index(vps, layer_id) != lhvc_get_scalability_id(vps, i - 1, LHVC_VIEW_ORDER_INDEX))) {\n\t\t\tnumViews++;\n\t\t}\n\t}\n\treturn numViews;\n}",
"static void lhvc_parse_rep_format(HEVC_RepFormat *fmt, GF_BitStream *bs, u32 idx)\n{\n\tu8 chroma_bitdepth_present_flag;\n\tfmt->pic_width_luma_samples = gf_bs_read_int_log_idx(bs, 16, \"pic_width_luma_samples\", idx);\n\tfmt->pic_height_luma_samples = gf_bs_read_int_log_idx(bs, 16, \"pic_height_luma_samples\", idx);\n\tchroma_bitdepth_present_flag = gf_bs_read_int_log_idx(bs, 1, \"chroma_bitdepth_present_flag\", idx);\n\tif (chroma_bitdepth_present_flag) {\n\t\tfmt->chroma_format_idc = gf_bs_read_int_log_idx(bs, 2, \"chroma_format_idc\", idx);",
"\t\tif (fmt->chroma_format_idc == 3)\n\t\t\tfmt->separate_colour_plane_flag = gf_bs_read_int_log_idx(bs, 1, \"separate_colour_plane_flag\", idx);\n\t\tfmt->bit_depth_luma = 8 + gf_bs_read_int_log_idx(bs, 4, \"bit_depth_luma_minus8\", idx);\n\t\tfmt->bit_depth_chroma = 8 + gf_bs_read_int_log_idx(bs, 4, \"bit_depth_chroma_minus8\", idx);\n\t}\n\tif (gf_bs_read_int_log_idx(bs, 1, \"conformance_window_vps_flag\", idx)) {\n\t\tgf_bs_read_ue_log_idx(bs, \"conf_win_vps_left_offset\", idx);\n\t\tgf_bs_read_ue_log_idx(bs, \"conf_win_vps_right_offset\", idx);\n\t\tgf_bs_read_ue_log_idx(bs, \"conf_win_vps_top_offset\", idx);\n\t\tgf_bs_read_ue_log_idx(bs, \"conf_win_vps_bottom_offset\", idx);\n\t}\n}",
"\nstatic Bool hevc_parse_vps_extension(HEVC_VPS *vps, GF_BitStream *bs)\n{\n\tu8 splitting_flag, vps_nuh_layer_id_present_flag, view_id_len;\n\tu32 i, j, num_scalability_types, num_add_olss, num_add_layer_set, num_indepentdent_layers, nb_bits, default_output_layer_idc = 0;\n\tu8 dimension_id_len[16], dim_bit_offset[16];\n\tu8 /*avc_base_layer_flag, */NumLayerSets, /*default_one_target_output_layer_flag, */rep_format_idx_present_flag, ols_ids_to_ls_idx;\n\tu8 layer_set_idx_for_ols_minus1[MAX_LHVC_LAYERS];\n\tu8 nb_output_layers_in_output_layer_set[MAX_LHVC_LAYERS + 1];\n\tu8 ols_highest_output_layer_id[MAX_LHVC_LAYERS + 1];",
"\tu32 k, d, r, p, iNuhLId, jNuhLId;\n\tu8 num_direct_ref_layers[64], num_pred_layers[64], num_layers_in_tree_partition[MAX_LHVC_LAYERS];\n\tu8 dependency_flag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS], id_pred_layers[64][MAX_LHVC_LAYERS];\n\t//\tu8 num_ref_layers[64];\n\t//\tu8 tree_partition_layer_id[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];\n\t//\tu8 id_ref_layers[64][MAX_LHVC_LAYERS];\n\t//\tu8 id_direct_ref_layers[64][MAX_LHVC_LAYERS];\n\tu8 layer_id_in_list_flag[64];\n\tBool OutputLayerFlag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];",
"\tvps->vps_extension_found = 1;\n\tif ((vps->max_layers > 1) && vps->base_layer_internal_flag)\n\t\thevc_profile_tier_level(bs, 0, vps->max_sub_layers - 1, &vps->ext_ptl[0], 0);",
"\tsplitting_flag = gf_bs_read_int_log(bs, 1, \"splitting_flag\");\n\tnum_scalability_types = 0;\n\tfor (i = 0; i < 16; i++) {\n\t\tvps->scalability_mask[i] = gf_bs_read_int_log_idx(bs, 1, \"scalability_mask\", i);\n\t\tnum_scalability_types += vps->scalability_mask[i];\n\t}\n\tif (num_scalability_types >= 16) {\n\t\tnum_scalability_types = 16;\n\t}\n\tdimension_id_len[0] = 0;\n\tfor (i = 0; i < (num_scalability_types - splitting_flag); i++) {\n\t\tdimension_id_len[i] = 1 + gf_bs_read_int_log_idx(bs, 3, \"dimension_id_len_minus1\", i);\n\t}",
"\tif (splitting_flag) {\n\t\tfor (i = 0; i < num_scalability_types; i++) {\n\t\t\tdim_bit_offset[i] = 0;\n\t\t\tfor (j = 0; j < i; j++)\n\t\t\t\tdim_bit_offset[i] += dimension_id_len[j];\n\t\t}\n\t\tdimension_id_len[num_scalability_types - 1] = 1 + (5 - dim_bit_offset[num_scalability_types - 1]);\n\t\tdim_bit_offset[num_scalability_types] = 6;\n\t}",
"\tvps_nuh_layer_id_present_flag = gf_bs_read_int_log(bs, 1, \"vps_nuh_layer_id_present_flag\");\n\tvps->layer_id_in_nuh[0] = 0;\n\tvps->layer_id_in_vps[0] = 0;\n\tfor (i = 1; i < vps->max_layers; i++) {\n\t\tif (vps_nuh_layer_id_present_flag) {\n\t\t\tvps->layer_id_in_nuh[i] = gf_bs_read_int_log_idx(bs, 6, \"layer_id_in_nuh\", i);\n\t\t}\n\t\telse {\n\t\t\tvps->layer_id_in_nuh[i] = i;\n\t\t}\n\t\tvps->layer_id_in_vps[vps->layer_id_in_nuh[i]] = i;",
"\t\tif (!splitting_flag) {\n\t\t\tfor (j = 0; j < num_scalability_types; j++) {\n\t\t\t\tvps->dimension_id[i][j] = gf_bs_read_int_log_idx2(bs, dimension_id_len[j], \"dimension_id\", i, j);\n\t\t\t}\n\t\t}\n\t}",
"\tif (splitting_flag) {\n\t\tfor (i = 0; i < vps->max_layers; i++)\n\t\t\tfor (j = 0; j < num_scalability_types; j++)\n\t\t\t\tvps->dimension_id[i][j] = ((vps->layer_id_in_nuh[i] & ((1 << dim_bit_offset[j + 1]) - 1)) >> dim_bit_offset[j]);\n\t}\n\telse {\n\t\tfor (j = 0; j < num_scalability_types; j++)\n\t\t\tvps->dimension_id[0][j] = 0;\n\t}",
"\tview_id_len = gf_bs_read_int_log(bs, 4, \"view_id_len\");\n\tif (view_id_len > 0) {\n\t\tfor (i = 0; i < lhvc_get_num_views(vps); i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, view_id_len, \"view_id_val\", i);\n\t\t}\n\t}",
"\tfor (i = 1; i < vps->max_layers; i++) {\n\t\tfor (j = 0; j < i; j++) {\n\t\t\tvps->direct_dependency_flag[i][j] = gf_bs_read_int_log_idx(bs, 1, \"direct_dependency_flag\", i);\n\t\t}\n\t}",
"\t//we do the test on MAX_LHVC_LAYERS and break in the loop to avoid a wrong GCC 4.8 warning on array bounds\n\tfor (i = 0; i < MAX_LHVC_LAYERS; i++) {\n\t\tif (i >= vps->max_layers) break;\n\t\tfor (j = 0; j < vps->max_layers; j++) {\n\t\t\tdependency_flag[i][j] = vps->direct_dependency_flag[i][j];\n\t\t\tfor (k = 0; k < i; k++)\n\t\t\t\tif (vps->direct_dependency_flag[i][k] && vps->direct_dependency_flag[k][j])\n\t\t\t\t\tdependency_flag[i][j] = 1;\n\t\t}\n\t}",
"\tfor (i = 0; i < vps->max_layers; i++) {\n\t\tiNuhLId = vps->layer_id_in_nuh[i];\n\t\td = r = p = 0;\n\t\tfor (j = 0; j < vps->max_layers; j++) {\n\t\t\tjNuhLId = vps->layer_id_in_nuh[j];\n\t\t\tif (vps->direct_dependency_flag[i][j]) {\n\t\t\t\t//\t\t\t\tid_direct_ref_layers[iNuhLId][d] = jNuhLId;\n\t\t\t\td++;\n\t\t\t}\n\t\t\tif (dependency_flag[i][j]) {\n\t\t\t\t//\t\t\t\tid_ref_layers[iNuhLId][r] = jNuhLId;\n\t\t\t\tr++;\n\t\t\t}",
"\t\t\tif (dependency_flag[j][i])\n\t\t\t\tid_pred_layers[iNuhLId][p++] = jNuhLId;\n\t\t}\n\t\tnum_direct_ref_layers[iNuhLId] = d;\n\t\t//\t\tnum_ref_layers[iNuhLId] = r;\n\t\tnum_pred_layers[iNuhLId] = p;\n\t}",
"\tmemset(layer_id_in_list_flag, 0, 64 * sizeof(u8));\n\tk = 0; //num_indepentdent_layers\n\tfor (i = 0; i < vps->max_layers; i++) {\n\t\tiNuhLId = vps->layer_id_in_nuh[i];\n\t\tif (!num_direct_ref_layers[iNuhLId]) {\n\t\t\tu32 h = 1;\n\t\t\t//tree_partition_layer_id[k][0] = iNuhLId;\n\t\t\tfor (j = 0; j < num_pred_layers[iNuhLId]; j++) {\n\t\t\t\tu32 predLId = id_pred_layers[iNuhLId][j];\n\t\t\t\tif (!layer_id_in_list_flag[predLId]) {\n\t\t\t\t\t//tree_partition_layer_id[k][h++] = predLId;\n\t\t\t\t\tlayer_id_in_list_flag[predLId] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnum_layers_in_tree_partition[k++] = h;\n\t\t}\n\t}\n\tnum_indepentdent_layers = k;",
"\tnum_add_layer_set = 0;\n\tif (num_indepentdent_layers > 1)\n\t\tnum_add_layer_set = gf_bs_read_ue_log(bs, \"num_add_layer_set\");",
"\tfor (i = 0; i < num_add_layer_set; i++)\n\t\tfor (j = 1; j < num_indepentdent_layers; j++) {\n\t\t\tnb_bits = 1;\n\t\t\twhile ((1 << nb_bits) < (num_layers_in_tree_partition[j] + 1))\n\t\t\t\tnb_bits++;\n\t\t\tgf_bs_read_int_log_idx2(bs, nb_bits, \"highest_layer_idx_plus1\", i, j);\n\t\t}",
"\n\tif (gf_bs_read_int_log(bs, 1, \"vps_sub_layers_max_minus1_present_flag\")) {\n\t\tfor (i = 0; i < vps->max_layers; i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, 3, \"sub_layers_vps_max_minus1\", i);\n\t\t}\n\t}",
"\tif (gf_bs_read_int_log(bs, 1, \"max_tid_ref_present_flag\")) {\n\t\tfor (i = 0; i < (vps->max_layers - 1); i++) {\n\t\t\tfor (j = i + 1; j < vps->max_layers; j++) {\n\t\t\t\tif (vps->direct_dependency_flag[j][i])\n\t\t\t\t\tgf_bs_read_int_log_idx2(bs, 3, \"max_tid_il_ref_pics_plus1\", i, j);\n\t\t\t}\n\t\t}\n\t}\n\tgf_bs_read_int_log(bs, 1, \"default_ref_layers_active_flag\");",
"\tvps->num_profile_tier_level = 1 + gf_bs_read_ue_log(bs, \"num_profile_tier_level\");\n\tif (vps->num_profile_tier_level > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Wrong number of PTLs in VPS %d\\n\", vps->num_profile_tier_level));\n\t\tvps->num_profile_tier_level = 1;\n\t\treturn GF_FALSE;\n\t}",
"\tfor (i = vps->base_layer_internal_flag ? 2 : 1; i < vps->num_profile_tier_level; i++) {\n\t\tBool vps_profile_present_flag = gf_bs_read_int_log_idx(bs, 1, \"vps_profile_present_flag\", i);\n\t\thevc_profile_tier_level(bs, vps_profile_present_flag, vps->max_sub_layers - 1, &vps->ext_ptl[i - 1], i-1);\n\t}",
"\tNumLayerSets = vps->num_layer_sets + num_add_layer_set;\n\tnum_add_olss = 0;",
"\tif (NumLayerSets > 1) {\n\t\tnum_add_olss = gf_bs_read_ue_log(bs, \"num_add_olss\");\n\t\tdefault_output_layer_idc = gf_bs_read_int_log(bs, 2, \"default_output_layer_idc\");\n\t\tdefault_output_layer_idc = default_output_layer_idc < 2 ? default_output_layer_idc : 2;\n\t}\n\tvps->num_output_layer_sets = num_add_olss + NumLayerSets;",
"\tif (vps->num_output_layer_sets > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Wrong number of output layer sets in VPS %d, max %d supported\\n\", vps->num_output_layer_sets, MAX_LHVC_LAYERS));\n\t\tvps->num_output_layer_sets = 1;\n\t\treturn GF_FALSE;\n\t}",
"\tlayer_set_idx_for_ols_minus1[0] = 1;\n\tvps->output_layer_flag[0][0] = 1;",
"\tfor (i = 0; i < vps->num_output_layer_sets; i++) {\n\t\tif ((NumLayerSets > 2) && (i >= NumLayerSets)) {\n\t\t\tnb_bits = 1;\n\t\t\twhile ((1 << nb_bits) < (NumLayerSets - 1))\n\t\t\t\tnb_bits++;\n\t\t\tlayer_set_idx_for_ols_minus1[i] = gf_bs_read_int_log_idx(bs, nb_bits, \"layer_set_idx_for_ols_minus1\", i);\n\t\t}\n\t\telse\n\t\t\tlayer_set_idx_for_ols_minus1[i] = 0;\n\t\tols_ids_to_ls_idx = i < NumLayerSets ? i : layer_set_idx_for_ols_minus1[i] + 1;",
"\t\tif ((i > (vps->num_layer_sets - 1)) || (default_output_layer_idc == 2)) {\n\t\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)\n\t\t\t\tvps->output_layer_flag[i][j] = gf_bs_read_int_log_idx2(bs, 1, \"output_layer_flag\", i, j);\n\t\t}",
"\t\tif ((default_output_layer_idc == 0) || (default_output_layer_idc == 1)) {\n\t\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\t\tif ((default_output_layer_idc == 0) || (vps->LayerSetLayerIdList[i][j] == vps->LayerSetLayerIdListMax[i]))\n\t\t\t\t\tOutputLayerFlag[i][j] = GF_TRUE;\n\t\t\t\telse\n\t\t\t\t\tOutputLayerFlag[i][j] = GF_FALSE;\n\t\t\t}\n\t\t}",
"\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\tif (OutputLayerFlag[i][j]) {\n\t\t\t\tu32 curLayerID;\n\t\t\t\tvps->necessary_layers_flag[i][j] = GF_TRUE;\n\t\t\t\tcurLayerID = vps->LayerSetLayerIdList[i][j];\n\t\t\t\tfor (k = 0; k < j; k++) {\n\t\t\t\t\tu32 refLayerId = vps->LayerSetLayerIdList[i][k];\n\t\t\t\t\tif (dependency_flag[vps->layer_id_in_vps[curLayerID]][vps->layer_id_in_vps[refLayerId]])\n\t\t\t\t\t\tvps->necessary_layers_flag[i][k] = GF_TRUE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvps->num_necessary_layers[i] = 0;\n\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\tif (vps->necessary_layers_flag[i][j])\n\t\t\t\tvps->num_necessary_layers[i] += 1;\n\t\t}",
"\t\tif (i == 0) {\n\t\t\tif (vps->base_layer_internal_flag) {\n\t\t\t\tif (vps->max_layers > 1)\n\t\t\t\t\tvps->profile_tier_level_idx[0][0] = 1;\n\t\t\t\telse\n\t\t\t\t\tvps->profile_tier_level_idx[0][0] = 0;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tnb_bits = 1;\n\t\twhile ((u32)(1 << nb_bits) < vps->num_profile_tier_level)\n\t\t\tnb_bits++;\n\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)\n\t\t\tif (vps->necessary_layers_flag[i][j] && vps->num_profile_tier_level)\n\t\t\t\tvps->profile_tier_level_idx[i][j] = gf_bs_read_int_log_idx2(bs, nb_bits, \"profile_tier_level_idx\", i, j);\n\t\t\telse\n\t\t\t\tvps->profile_tier_level_idx[i][j] = 0;",
"\n\t\tnb_output_layers_in_output_layer_set[i] = 0;\n\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\tnb_output_layers_in_output_layer_set[i] += OutputLayerFlag[i][j];\n\t\t\tif (OutputLayerFlag[i][j]) {\n\t\t\t\tols_highest_output_layer_id[i] = vps->LayerSetLayerIdList[ols_ids_to_ls_idx][j];\n\t\t\t}\n\t\t}\n\t\tif (nb_output_layers_in_output_layer_set[i] == 1 && ols_highest_output_layer_id[i] > 0)\n\t\t\tvps->alt_output_layer_flag[i] = gf_bs_read_int_log_idx(bs, 1, \"alt_output_layer_flag\", i);\n\t}",
"\tvps->num_rep_formats = 1 + gf_bs_read_ue_log(bs, \"num_rep_formats_minus1\");\n\tif (vps->num_rep_formats > 16) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Wrong number of rep formats in VPS %d\\n\", vps->num_rep_formats));\n\t\tvps->num_rep_formats = 0;\n\t\treturn GF_FALSE;\n\t}",
"\tfor (i = 0; i < vps->num_rep_formats; i++) {\n\t\tlhvc_parse_rep_format(&vps->rep_formats[i], bs, i);\n\t}\n\tif (vps->num_rep_formats > 1)\n\t\trep_format_idx_present_flag = gf_bs_read_int_log(bs, 1, \"rep_format_idx_present_flag\");\n\telse\n\t\trep_format_idx_present_flag = 0;",
"\tvps->rep_format_idx[0] = 0;\n\tnb_bits = 1;\n\twhile ((u32)(1 << nb_bits) < vps->num_rep_formats)\n\t\tnb_bits++;\n\tfor (i = vps->base_layer_internal_flag ? 1 : 0; i < vps->max_layers; i++) {\n\t\tif (rep_format_idx_present_flag) {\n\t\t\tvps->rep_format_idx[i] = gf_bs_read_int_log_idx(bs, nb_bits, \"rep_format_idx\", i);\n\t\t}\n\t\telse {\n\t\t\tvps->rep_format_idx[i] = i < vps->num_rep_formats - 1 ? i : vps->num_rep_formats - 1;\n\t\t}\n\t}\n\t//TODO - we don't use the rest ...",
"\treturn GF_TRUE;\n}",
"static void sub_layer_hrd_parameters(GF_BitStream *bs, int subLayerId, u32 cpb_cnt, Bool sub_pic_hrd_params_present_flag, u32 idx1, u32 idx2)\n{\n\tu32 i;\n\tif (!gf_bs_available(bs)) return;",
"\tfor (i = 0; i <= cpb_cnt; i++) {\n\t\tgf_bs_read_ue_log_idx3(bs, \"bit_rate_value_minus1\", idx1, idx2, i);\n\t\tgf_bs_read_ue_log_idx3(bs, \"cpb_size_value_minus1\", idx1, idx2, i);\n\t\tif (sub_pic_hrd_params_present_flag) {\n\t\t\tgf_bs_read_ue_log_idx3(bs, \"cpb_size_du_value_minus1\", idx1, idx2, i);\n\t\t\tgf_bs_read_ue_log_idx3(bs, \"bit_rate_du_value_minus1\", idx1, idx2, i);\n\t\t}\n\t\tgf_bs_read_int_log_idx3(bs, 1, \"cbr_flag\", idx1, idx2, i);\n\t}\n}",
"static void hevc_parse_hrd_parameters(GF_BitStream *bs, Bool commonInfPresentFlag, int maxNumSubLayersMinus1, u32 idx)\n{\n\tint i;\n\tBool nal_hrd_parameters_present_flag = GF_FALSE;\n\tBool vcl_hrd_parameters_present_flag = GF_FALSE;\n\tBool sub_pic_hrd_params_present_flag = GF_FALSE;",
"\tif (commonInfPresentFlag) {\n\t\tnal_hrd_parameters_present_flag = gf_bs_read_int_log_idx(bs, 1, \"nal_hrd_parameters_present_flag\", idx);\n\t\tvcl_hrd_parameters_present_flag = gf_bs_read_int_log_idx(bs, 1, \"vcl_hrd_parameters_present_flag\", idx);\n\t\tif (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {\n\t\t\tsub_pic_hrd_params_present_flag = gf_bs_read_int_log_idx(bs, 1, \"sub_pic_hrd_params_present_flag\", idx);\n\t\t\tif (sub_pic_hrd_params_present_flag) {\n\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"tick_divisor_minus2\", idx);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 5, \"du_cpb_removal_delay_increment_length_minus1\", idx);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 1, \"sub_pic_cpb_params_in_pic_timing_sei_flag\", idx);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 5, \"dpb_output_delay_du_length_minus1\", idx);\n\t\t\t}\n\t\t\tgf_bs_read_int_log_idx(bs, 4, \"bit_rate_scale\", idx);\n\t\t\tgf_bs_read_int_log_idx(bs, 4, \"cpb_size_scale\", idx);\n\t\t\tif (sub_pic_hrd_params_present_flag) {\n\t\t\t\tgf_bs_read_int_log_idx(bs, 4, \"cpb_size_du_scale\", idx);\n\t\t\t}\n\t\t\tgf_bs_read_int_log_idx(bs, 5, \"initial_cpb_removal_delay_length_minus1\", idx);\n\t\t\tgf_bs_read_int_log_idx(bs, 5, \"au_cpb_removal_delay_length_minus1\", idx);\n\t\t\tgf_bs_read_int_log_idx(bs, 5, \"dpb_output_delay_length_minus1\", idx);\n\t\t}\n\t}\n\tfor (i = 0; i <= maxNumSubLayersMinus1; i++) {\n\t\tBool fixed_pic_rate_general_flag_i = gf_bs_read_int_log_idx(bs, 1, \"fixed_pic_rate_general_flag\", idx);\n\t\tBool fixed_pic_rate_within_cvs_flag_i = GF_TRUE;\n\t\tBool low_delay_hrd_flag_i = GF_FALSE;\n\t\tu32 cpb_cnt_minus1_i = 0;\n\t\tif (!fixed_pic_rate_general_flag_i) {\n\t\t\tfixed_pic_rate_within_cvs_flag_i = gf_bs_read_int_log_idx(bs, 1, \"fixed_pic_rate_within_cvs_flag\", idx);\n\t\t}\n\t\tif (fixed_pic_rate_within_cvs_flag_i)\n\t\t\tgf_bs_read_ue_log_idx(bs, \"elemental_duration_in_tc_minus1\", idx);\n\t\telse\n\t\t\tlow_delay_hrd_flag_i = gf_bs_read_int_log_idx(bs, 1, \"low_delay_hrd_flag\", idx);\n\t\tif (!low_delay_hrd_flag_i) {\n\t\t\tcpb_cnt_minus1_i = gf_bs_read_ue_log_idx(bs, \"cpb_cnt_minus1\", idx);\n\t\t}\n\t\tif (nal_hrd_parameters_present_flag) {\n\t\t\tsub_layer_hrd_parameters(bs, i, cpb_cnt_minus1_i, sub_pic_hrd_params_present_flag, idx, i);\n\t\t}\n\t\tif (vcl_hrd_parameters_present_flag) {\n\t\t\tsub_layer_hrd_parameters(bs, i, cpb_cnt_minus1_i, sub_pic_hrd_params_present_flag, idx, i);\n\t\t}\n\t}\n}",
"static s32 gf_hevc_read_vps_bs_internal(GF_BitStream *bs, HEVCState *hevc, Bool stop_at_vps_ext)\n{\n\tu8 vps_sub_layer_ordering_info_present_flag, vps_extension_flag;\n\tu32 i, j;\n\ts32 vps_id;\n\tHEVC_VPS *vps;\n\tu8 layer_id_included_flag[MAX_LHVC_LAYERS][64];",
"\t//nalu header already parsed\n\tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");",
"\tif ((vps_id<0) || (vps_id >= 16)) return -1;",
"\tvps = &hevc->vps[vps_id];\n\tvps->bit_pos_vps_extensions = -1;\n\tif (!vps->state) {\n\t\tvps->id = vps_id;\n\t\tvps->state = 1;\n\t}",
"\tvps->base_layer_internal_flag = gf_bs_read_int_log(bs, 1, \"base_layer_internal_flag\");\n\tvps->base_layer_available_flag = gf_bs_read_int_log(bs, 1, \"base_layer_available_flag\");\n\tvps->max_layers = 1 + gf_bs_read_int_log(bs, 6, \"max_layers_minus1\");\n\tif (vps->max_layers > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] sorry, %d layers in VPS but only %d supported\\n\", vps->max_layers, MAX_LHVC_LAYERS));\n\t\treturn -1;\n\t}\n\tvps->max_sub_layers = gf_bs_read_int_log(bs, 3, \"max_sub_layers_minus1\") + 1;\n\tvps->temporal_id_nesting = gf_bs_read_int_log(bs, 1, \"temporal_id_nesting\");\n\tgf_bs_read_int_log(bs, 16, \"vps_reserved_ffff_16bits\");\n\thevc_profile_tier_level(bs, 1, vps->max_sub_layers - 1, &vps->ptl, 0);",
"\tvps_sub_layer_ordering_info_present_flag = gf_bs_read_int_log(bs, 1, \"vps_sub_layer_ordering_info_present_flag\");\n\tfor (i = (vps_sub_layer_ordering_info_present_flag ? 0 : vps->max_sub_layers - 1); i < vps->max_sub_layers; i++) {\n\t\tgf_bs_read_ue_log_idx(bs, \"vps_max_dec_pic_buffering_minus1\", i);\n\t\tgf_bs_read_ue_log_idx(bs, \"vps_max_num_reorder_pics\", i);\n\t\tgf_bs_read_ue_log_idx(bs, \"vps_max_latency_increase_plus1\", i);\n\t}\n\tvps->max_layer_id = gf_bs_read_int_log(bs, 6, \"max_layer_id\");\n\tif (vps->max_layer_id > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] VPS max layer ID %u but GPAC only supports %u\\n\", vps->max_layer_id, MAX_LHVC_LAYERS));\n\t\treturn -1;\n\t}\n\tvps->num_layer_sets = gf_bs_read_ue_log(bs, \"num_layer_sets_minus1\") + 1;\n\tif (vps->num_layer_sets > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Wrong number of layer sets in VPS %d\\n\", vps->num_layer_sets));\n\t\treturn -1;\n\t}\n\tfor (i = 1; i < vps->num_layer_sets; i++) {\n\t\tfor (j = 0; j <= vps->max_layer_id; j++) {\n\t\t\tlayer_id_included_flag[i][j] = gf_bs_read_int_log_idx2(bs, 1, \"layer_id_included_flag\", i, j);\n\t\t}\n\t}\n\tvps->num_layers_in_id_list[0] = 1;\n\tfor (i = 1; i < vps->num_layer_sets; i++) {\n\t\tu32 n, m;\n\t\tn = 0;\n\t\tfor (m = 0; m <= vps->max_layer_id; m++) {\n\t\t\tif (layer_id_included_flag[i][m]) {\n\t\t\t\tvps->LayerSetLayerIdList[i][n++] = m;\n\t\t\t\tif (vps->LayerSetLayerIdListMax[i] < m)\n\t\t\t\t\tvps->LayerSetLayerIdListMax[i] = m;\n\t\t\t}\n\t\t}\n\t\tvps->num_layers_in_id_list[i] = n;\n\t}\n\tif (gf_bs_read_int_log(bs, 1, \"vps_timing_info_present_flag\")) {\n\t\tu32 vps_num_hrd_parameters;\n\t\tgf_bs_read_int_log(bs, 32, \"vps_num_units_in_tick\");\n\t\tgf_bs_read_int_log(bs, 32, \"vps_time_scale\");\n\t\tif (gf_bs_read_int_log(bs, 1, \"vps_poc_proportional_to_timing_flag\")) {\n\t\t\tgf_bs_read_ue_log(bs, \"vps_num_ticks_poc_diff_one_minus1\");\n\t\t}\n\t\tvps_num_hrd_parameters = gf_bs_read_ue_log(bs, \"vps_num_hrd_parameters\");\n\t\tfor (i = 0; i < vps_num_hrd_parameters; i++) {\n\t\t\tBool cprms_present_flag = GF_TRUE;\n\t\t\tgf_bs_read_ue_log_idx(bs, \"hrd_layer_set_idx\", i);\n\t\t\tif (i > 0)\n\t\t\t\tcprms_present_flag = gf_bs_read_int_log(bs, 1, \"cprms_present_flag\");\n\t\t\thevc_parse_hrd_parameters(bs, cprms_present_flag, vps->max_sub_layers - 1, i);\n\t\t}\n\t}\n\tif (stop_at_vps_ext) {\n\t\treturn vps_id;\n\t}",
"\tvps_extension_flag = gf_bs_read_int_log(bs, 1, \"vps_extension_flag\");\n\tif (vps_extension_flag) {\n\t\tBool res;\n\t\tgf_bs_align(bs);\n\t\tres = hevc_parse_vps_extension(vps, bs);\n\t\tif (res != GF_TRUE) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Failed to parse VPS extensions\\n\"));\n\t\t\treturn -1;\n\t\t}\n\t\tif (gf_bs_read_int_log(bs, 1, \"vps_extension2_flag\")) {\n#if 0\n\t\t\twhile (gf_bs_available(bs)) {\n\t\t\t\t/*vps_extension_data_flag */ gf_bs_read_int(bs, 1);\n\t\t\t}\n#endif",
"\t\t}\n\t}\n\treturn vps_id;\n}",
"GF_EXPORT\ns32 gf_hevc_read_vps_ex(u8 *data, u32 *size, HEVCState *hevc, Bool remove_extensions)\n{\n\tGF_BitStream *bs;\n\tchar *data_without_emulation_bytes = NULL;\n\tu32 data_without_emulation_bytes_size = 0;\n\ts32 vps_id = -1;",
"\t/*still contains emulation bytes*/\n\tdata_without_emulation_bytes_size = remove_extensions ? gf_media_nalu_emulation_bytes_remove_count(data, (*size)) : 0;\n\tif (!data_without_emulation_bytes_size) {\n\t\tbs = gf_bs_new(data, (*size), GF_BITSTREAM_READ);\n\t\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\t}\n\t//when removing VPS ext, we have to get the full buffer without emulation prevention bytes becuase we do a bit-by-bit copy of the vps\n\telse {\n\t\tdata_without_emulation_bytes = gf_malloc((*size) * sizeof(char));\n\t\tdata_without_emulation_bytes_size = gf_media_nalu_remove_emulation_bytes(data, data_without_emulation_bytes, (*size));\n\t\tbs = gf_bs_new(data_without_emulation_bytes, data_without_emulation_bytes_size, GF_BITSTREAM_READ);\n\t}\n\tif (!bs) goto exit;",
"\n\tif (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) goto exit;",
"\tvps_id = gf_hevc_read_vps_bs_internal(bs, hevc, remove_extensions);\n\tif (vps_id < 0) goto exit;",
"\tif (remove_extensions) {\n\t\tu8 *new_vps;\n\t\tu32 new_vps_size, emulation_bytes;\n\t\tu32 bit_pos = gf_bs_get_bit_offset(bs);\n\t\tGF_BitStream *w_bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\t\tgf_bs_seek(bs, 0);\n\t\tgf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );\n\t\tgf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );\n\t\tgf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );\n\t\tgf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );\n\t\tgf_bs_write_u16(w_bs, gf_bs_read_u16(bs) );\n\t\tbit_pos -= 48;\n\t\twhile (bit_pos) {\n\t\t\tu32 v = gf_bs_read_int(bs, 1);\n\t\t\tgf_bs_write_int(w_bs, v, 1);\n\t\t\tbit_pos--;\n\t\t}\n\t\t/*vps extension flag*/\n\t\tgf_bs_write_int(w_bs, 0, 1);\n\t\tnew_vps = NULL;\n\t\tgf_bs_get_content(w_bs, &new_vps, &new_vps_size);\n\t\tgf_bs_del(w_bs);",
"\t\temulation_bytes = gf_media_nalu_emulation_bytes_add_count(new_vps, new_vps_size);\n\t\tif (emulation_bytes + new_vps_size > *size) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"Buffer too small to rewrite VPS - skipping rewrite\\n\"));\n\t\t}\n\t\telse {\n\t\t\t*size = gf_media_nalu_add_emulation_bytes(new_vps, data, new_vps_size);\n\t\t}\n\t\tif (new_vps)\n\t\t\tgf_free(new_vps);\n\t}",
"exit:\n\tif (bs)\n\t\tgf_bs_del(bs);\n\tif (data_without_emulation_bytes) gf_free(data_without_emulation_bytes);\n\treturn vps_id;\n}",
"GF_EXPORT\ns32 gf_hevc_read_vps(u8 *data, u32 size, HEVCState *hevc)\n{\n\treturn gf_hevc_read_vps_ex(data, &size, hevc, GF_FALSE);\n}",
"GF_EXPORT\ns32 gf_hevc_read_vps_bs(GF_BitStream *bs, HEVCState *hevc)\n{\n\tif (!bs || !hevc) return -1;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\tif (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) return -1;\n\treturn gf_hevc_read_vps_bs_internal(bs, hevc, GF_FALSE);\n}",
"static void hevc_scaling_list_data(GF_BitStream *bs)\n{\n\tu32 i, sizeId, matrixId;\n\tfor (sizeId = 0; sizeId < 4; sizeId++) {\n\t\tfor (matrixId = 0; matrixId < 6; matrixId += (sizeId == 3) ? 3 : 1) {\n\t\t\tu32 idx = sizeId*100 + 10*matrixId;\n\t\t\tu32 scaling_list_pred_mode_flag_sizeId_matrixId = gf_bs_read_int_log_idx(bs, 1, \"scaling_list_pred_mode_flag_sizeId_matrixId\", idx);\n\t\t\tif (!scaling_list_pred_mode_flag_sizeId_matrixId) {\n\t\t\t\tgf_bs_read_ue_log_idx(bs, \"scaling_list_pred_matrix_id_delta\", idx);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//u32 nextCoef = 8;\n\t\t\t\tu32 coefNum = MIN(64, (1 << (4 + (sizeId << 1))));\n\t\t\t\tif (sizeId > 1) {\n\t\t\t\t\tgf_bs_read_se_log_idx(bs, \"scaling_list_dc_coef_minus8\", idx);\n\t\t\t\t}\n\t\t\t\tfor (i = 0; i < coefNum; i++) {\n\t\t\t\t\tgf_bs_read_se_log_idx2(bs, \"scaling_list_delta_coef\", idx, i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"\nstatic const struct {\n\tu32 w, h;\n} hevc_sar[17] =\n{\n\t{ 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 },\n\t{ 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },\n\t{ 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },\n\t{ 64, 33 }, { 160,99 }, { 4,3}, { 3,2}, { 2,1}\n};",
"static s32 gf_hevc_read_sps_bs_internal(GF_BitStream *bs, HEVCState *hevc, u8 layer_id, u32 *vui_flag_pos)\n{\n\ts32 vps_id, sps_id = -1;\n\tu32 i, nb_CTUs, depth;\n\tHEVC_SPS *sps;\n\tHEVC_VPS *vps;\n\tHEVC_ProfileTierLevel ptl;\n\tBool multiLayerExtSpsFlag;\n\tu8 sps_ext_or_max_sub_layers_minus1, max_sub_layers_minus1;",
"\tif (vui_flag_pos) *vui_flag_pos = 0;",
"\t//nalu header already parsed\n\tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n\tif ((vps_id<0) || (vps_id >= 16)) {\n\t\treturn -1;\n\t}\n\tmemset(&ptl, 0, sizeof(ptl));\n\tmax_sub_layers_minus1 = 0;\n\tsps_ext_or_max_sub_layers_minus1 = 0;\n\tif (layer_id == 0)\n\t\tmax_sub_layers_minus1 = gf_bs_read_int_log(bs, 3, \"max_sub_layers_minus1\");\n\telse\n\t\tsps_ext_or_max_sub_layers_minus1 = gf_bs_read_int_log(bs, 3, \"sps_ext_or_max_sub_layers_minus1\");\n\tmultiLayerExtSpsFlag = (layer_id != 0) && (sps_ext_or_max_sub_layers_minus1 == 7);\n\tif (!multiLayerExtSpsFlag) {\n\t\tgf_bs_read_int_log(bs, 1, \"temporal_id_nesting_flag\");\n\t\thevc_profile_tier_level(bs, 1, max_sub_layers_minus1, &ptl, 0);\n\t}",
"\tsps_id = gf_bs_read_ue_log(bs, \"sps_id\");\n\tif ((sps_id < 0) || (sps_id >= 16)) {\n\t\treturn -1;\n\t}",
"\tsps = &hevc->sps[sps_id];\n\tif (!sps->state) {\n\t\tsps->state = 1;\n\t\tsps->id = sps_id;\n\t\tsps->vps_id = vps_id;\n\t}\n\tsps->ptl = ptl;\n\tvps = &hevc->vps[vps_id];\n\tsps->max_sub_layers_minus1 = 0;\n\tsps->sps_ext_or_max_sub_layers_minus1 = 0;",
"\t/* default values */\n\tsps->colour_primaries = 2;\n\tsps->transfer_characteristic = 2;\n\tsps->matrix_coeffs = 2;",
"\t//sps_rep_format_idx = 0;\n\tif (multiLayerExtSpsFlag) {\n\t\tsps->update_rep_format_flag = gf_bs_read_int_log(bs, 1, \"update_rep_format_flag\");\n\t\tif (sps->update_rep_format_flag) {\n\t\t\tsps->rep_format_idx = gf_bs_read_int_log(bs, 8, \"rep_format_idx\");\n\t\t}\n\t\telse {\n\t\t\tsps->rep_format_idx = vps->rep_format_idx[layer_id];\n\t\t}\n\t\tsps->width = vps->rep_formats[sps->rep_format_idx].pic_width_luma_samples;\n\t\tsps->height = vps->rep_formats[sps->rep_format_idx].pic_height_luma_samples;\n\t\tsps->chroma_format_idc = vps->rep_formats[sps->rep_format_idx].chroma_format_idc;\n\t\tsps->bit_depth_luma = vps->rep_formats[sps->rep_format_idx].bit_depth_luma;\n\t\tsps->bit_depth_chroma = vps->rep_formats[sps->rep_format_idx].bit_depth_chroma;\n\t\tsps->separate_colour_plane_flag = vps->rep_formats[sps->rep_format_idx].separate_colour_plane_flag;",
"\t\t//TODO this is crude ...\n\t\tsps->ptl = vps->ext_ptl[0];\n\t}\n\telse {\n\t\tsps->chroma_format_idc = gf_bs_read_ue_log(bs, \"chroma_format_idc\");\n\t\tif (sps->chroma_format_idc == 3)\n\t\t\tsps->separate_colour_plane_flag = gf_bs_read_int_log(bs, 1, \"separate_colour_plane_flag\");\n\t\tsps->width = gf_bs_read_ue_log(bs, \"width\");\n\t\tsps->height = gf_bs_read_ue_log(bs, \"height\");\n\t\tif ((sps->cw_flag = gf_bs_read_int_log(bs, 1, \"conformance_window_flag\"))) {\n\t\t\tu32 SubWidthC, SubHeightC;",
"\t\t\tif (sps->chroma_format_idc == 1) {\n\t\t\t\tSubWidthC = SubHeightC = 2;\n\t\t\t}\n\t\t\telse if (sps->chroma_format_idc == 2) {\n\t\t\t\tSubWidthC = 2;\n\t\t\t\tSubHeightC = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSubWidthC = SubHeightC = 1;\n\t\t\t}",
"\t\t\tsps->cw_left = gf_bs_read_ue_log(bs, \"conformance_window_left\");\n\t\t\tsps->cw_right = gf_bs_read_ue_log(bs, \"conformance_window_right\");\n\t\t\tsps->cw_top = gf_bs_read_ue_log(bs, \"conformance_window_top\");\n\t\t\tsps->cw_bottom = gf_bs_read_ue_log(bs, \"conformance_window_bottom\");",
"\t\t\tsps->width -= SubWidthC * (sps->cw_left + sps->cw_right);\n\t\t\tsps->height -= SubHeightC * (sps->cw_top + sps->cw_bottom);\n\t\t}\n\t\tsps->bit_depth_luma = 8 + gf_bs_read_ue_log(bs, \"bit_depth_luma_minus8\");\n\t\tsps->bit_depth_chroma = 8 + gf_bs_read_ue_log(bs, \"bit_depth_chroma_minus8\");\n\t}",
"\tsps->log2_max_pic_order_cnt_lsb = 4 + gf_bs_read_ue_log(bs, \"log2_max_pic_order_cnt_lsb_minus4\");",
"\tif (!multiLayerExtSpsFlag) {\n\t\tsps->sub_layer_ordering_info_present_flag = gf_bs_read_int_log(bs, 1, \"sub_layer_ordering_info_present_flag\");\n\t\tfor (i = sps->sub_layer_ordering_info_present_flag ? 0 : sps->max_sub_layers_minus1; i <= sps->max_sub_layers_minus1; i++) {\n\t\t\tgf_bs_read_ue_log_idx(bs, \"max_dec_pic_buffering\", i);\n\t\t\tgf_bs_read_ue_log_idx(bs, \"num_reorder_pics\", i);\n\t\t\tgf_bs_read_ue_log_idx(bs, \"max_latency_increase\", i);\n\t\t}\n\t}",
"\tsps->log2_min_luma_coding_block_size = 3 + gf_bs_read_ue_log(bs, \"log2_min_luma_coding_block_size_minus3\");\n\tsps->log2_diff_max_min_luma_coding_block_size = gf_bs_read_ue_log(bs, \"log2_diff_max_min_luma_coding_block_size\");\n\tsps->max_CU_width = (1 << (sps->log2_min_luma_coding_block_size + sps->log2_diff_max_min_luma_coding_block_size));\n\tsps->max_CU_height = (1 << (sps->log2_min_luma_coding_block_size + sps->log2_diff_max_min_luma_coding_block_size));",
"\tsps->log2_min_transform_block_size = 2 + gf_bs_read_ue_log(bs, \"log2_min_transform_block_size_minus2\");\n\tsps->log2_max_transform_block_size = sps->log2_min_transform_block_size + gf_bs_read_ue_log(bs, \"log2_max_transform_block_size\");",
"\tdepth = 0;\n\tsps->max_transform_hierarchy_depth_inter = gf_bs_read_ue_log(bs, \"max_transform_hierarchy_depth_inter\");\n\tsps->max_transform_hierarchy_depth_intra = gf_bs_read_ue_log(bs, \"max_transform_hierarchy_depth_intra\");\n\twhile ((u32)(sps->max_CU_width >> sps->log2_diff_max_min_luma_coding_block_size) > (u32)(1 << (sps->log2_min_transform_block_size + depth)))\n\t{\n\t\tdepth++;\n\t}\n\tsps->max_CU_depth = sps->log2_diff_max_min_luma_coding_block_size + depth;",
"\tnb_CTUs = ((sps->width + sps->max_CU_width - 1) / sps->max_CU_width) * ((sps->height + sps->max_CU_height - 1) / sps->max_CU_height);\n\tsps->bitsSliceSegmentAddress = 0;\n\twhile (nb_CTUs > (u32)(1 << sps->bitsSliceSegmentAddress)) {\n\t\tsps->bitsSliceSegmentAddress++;\n\t}",
"\tsps->scaling_list_enable_flag = gf_bs_read_int_log(bs, 1, \"scaling_list_enable_flag\");\n\tif (sps->scaling_list_enable_flag) {\n\t\tsps->infer_scaling_list_flag = 0;\n\t\tsps->scaling_list_ref_layer_id = 0;\n\t\tif (multiLayerExtSpsFlag) {\n\t\t\tsps->infer_scaling_list_flag = gf_bs_read_int_log(bs, 1, \"infer_scaling_list_flag\");\n\t\t}\n\t\tif (sps->infer_scaling_list_flag) {\n\t\t\tsps->scaling_list_ref_layer_id = gf_bs_read_int_log(bs, 6, \"scaling_list_ref_layer_id\");\n\t\t}\n\t\telse {\n\t\t\tsps->scaling_list_data_present_flag = gf_bs_read_int_log(bs, 1, \"scaling_list_data_present_flag\");\n\t\t\tif (sps->scaling_list_data_present_flag) {\n\t\t\t\thevc_scaling_list_data(bs);\n\t\t\t}\n\t\t}\n\t}\n\tsps->asymmetric_motion_partitions_enabled_flag = gf_bs_read_int_log(bs, 1, \"asymmetric_motion_partitions_enabled_flag\");\n\tsps->sample_adaptive_offset_enabled_flag = gf_bs_read_int_log(bs, 1, \"sample_adaptive_offset_enabled_flag\");\n\tif ( (sps->pcm_enabled_flag = gf_bs_read_int_log(bs, 1, \"pcm_enabled_flag\")) ) {\n\t\tsps->pcm_sample_bit_depth_luma_minus1 = gf_bs_read_int_log(bs, 4, \"pcm_sample_bit_depth_luma_minus1\");\n\t\tsps->pcm_sample_bit_depth_chroma_minus1 = gf_bs_read_int_log(bs, 4, \"pcm_sample_bit_depth_chroma_minus1\");\n\t\tsps->log2_min_pcm_luma_coding_block_size_minus3 = gf_bs_read_ue_log(bs, \"log2_min_pcm_luma_coding_block_size_minus3\");\n\t\tsps->log2_diff_max_min_pcm_luma_coding_block_size = gf_bs_read_ue_log(bs, \"log2_diff_max_min_pcm_luma_coding_block_size\");\n\t\tsps->pcm_loop_filter_disable_flag = gf_bs_read_int_log(bs, 1, \"pcm_loop_filter_disable_flag\");\n\t}\n\tsps->num_short_term_ref_pic_sets = gf_bs_read_ue_log(bs, \"num_short_term_ref_pic_sets\");\n\tif (sps->num_short_term_ref_pic_sets > 64) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Invalid number of short term reference picture sets %d\\n\", sps->num_short_term_ref_pic_sets));\n\t\treturn -1;\n\t}",
"\tfor (i = 0; i < sps->num_short_term_ref_pic_sets; i++) {\n\t\tBool ret = hevc_parse_short_term_ref_pic_set(bs, sps, i);\n\t\t/*cannot parse short_term_ref_pic_set, skip VUI parsing*/\n\t\tif (!ret) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Invalid short_term_ref_pic_set\\n\"));\n\t\t\treturn -1;\n\t\t}\n\t}\n\tsps->long_term_ref_pics_present_flag = gf_bs_read_int_log(bs, 1, \"long_term_ref_pics_present_flag\");\n\tif (sps->long_term_ref_pics_present_flag) {\n\t\tsps->num_long_term_ref_pic_sps = gf_bs_read_ue_log(bs, \"num_long_term_ref_pic_sps\");\n\t\tfor (i = 0; i < sps->num_long_term_ref_pic_sps; i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, sps->log2_max_pic_order_cnt_lsb, \"lt_ref_pic_poc_lsb_sps\", i);\n\t\t\tgf_bs_read_int_log_idx(bs, 1, \"used_by_curr_pic_lt_sps_flag\", i);\n\t\t}\n\t}\n\tsps->temporal_mvp_enable_flag = gf_bs_read_int_log(bs, 1, \"temporal_mvp_enable_flag\");\n\tsps->strong_intra_smoothing_enable_flag = gf_bs_read_int_log(bs, 1, \"strong_intra_smoothing_enable_flag\");",
"\tif (vui_flag_pos)\n\t\t*vui_flag_pos = (u32)gf_bs_get_bit_offset(bs);",
"\tif ((sps->vui_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vui_parameters_present_flag\")) ) {\n\t\tsps->aspect_ratio_info_present_flag = gf_bs_read_int_log(bs, 1, \"aspect_ratio_info_present_flag\");\n\t\tif (sps->aspect_ratio_info_present_flag) {\n\t\t\tsps->sar_idc = gf_bs_read_int_log(bs, 8, \"aspect_ratio_idc\");\n\t\t\tif (sps->sar_idc == 255) {\n\t\t\t\tsps->sar_width = gf_bs_read_int_log(bs, 16, \"aspect_ratio_width\");\n\t\t\t\tsps->sar_height = gf_bs_read_int_log(bs, 16, \"aspect_ratio_height\");\n\t\t\t}\n\t\t\telse if (sps->sar_idc < 17) {\n\t\t\t\tsps->sar_width = hevc_sar[sps->sar_idc].w;\n\t\t\t\tsps->sar_height = hevc_sar[sps->sar_idc].h;\n\t\t\t}\n\t\t}",
"\t\tif ((sps->overscan_info_present = gf_bs_read_int_log(bs, 1, \"overscan_info_present\")))\n\t\t\tsps->overscan_appropriate = gf_bs_read_int_log(bs, 1, \"overscan_appropriate\");",
"\t\tsps->video_signal_type_present_flag = gf_bs_read_int_log(bs, 1, \"video_signal_type_present_flag\");\n\t\tif (sps->video_signal_type_present_flag) {\n\t\t\tsps->video_format = gf_bs_read_int_log(bs, 3, \"video_format\");\n\t\t\tsps->video_full_range_flag = gf_bs_read_int_log(bs, 1, \"video_full_range_flag\");\n\t\t\tif ((sps->colour_description_present_flag = gf_bs_read_int_log(bs, 1, \"colour_description_present_flag\"))) {\n\t\t\t\tsps->colour_primaries = gf_bs_read_int_log(bs, 8, \"colour_primaries\");\n\t\t\t\tsps->transfer_characteristic = gf_bs_read_int_log(bs, 8, \"transfer_characteristic\");\n\t\t\t\tsps->matrix_coeffs = gf_bs_read_int_log(bs, 8, \"matrix_coefficients\");\n\t\t\t}\n\t\t}",
"\t\tif ((sps->chroma_loc_info_present_flag = gf_bs_read_int_log(bs, 1, \"chroma_loc_info_present_flag\"))) {\n\t\t\tsps->chroma_sample_loc_type_top_field = gf_bs_read_ue_log(bs, \"chroma_sample_loc_type_top_field\");\n\t\t\tsps->chroma_sample_loc_type_bottom_field = gf_bs_read_ue_log(bs, \"chroma_sample_loc_type_bottom_field\");\n\t\t}",
"\t\tsps->neutra_chroma_indication_flag = gf_bs_read_int_log(bs, 1, \"neutra_chroma_indication_flag\");\n\t\tsps->field_seq_flag = gf_bs_read_int_log(bs, 1, \"field_seq_flag\");\n\t\tsps->frame_field_info_present_flag = gf_bs_read_int_log(bs, 1, \"frame_field_info_present_flag\");",
"\t\tif ((sps->default_display_window_flag = gf_bs_read_int_log(bs, 1, \"default_display_window_flag\"))) {\n\t\t\tsps->left_offset = gf_bs_read_ue_log(bs, \"display_window_left_offset\");\n\t\t\tsps->right_offset = gf_bs_read_ue_log(bs, \"display_window_right_offset\");\n\t\t\tsps->top_offset = gf_bs_read_ue_log(bs, \"display_window_top_offset\");\n\t\t\tsps->bottom_offset = gf_bs_read_ue_log(bs, \"display_window_bottom_offset\");\n\t\t}",
"\t\tsps->has_timing_info = gf_bs_read_int_log(bs, 1, \"has_timing_info\");\n\t\tif (sps->has_timing_info) {\n\t\t\tsps->num_units_in_tick = gf_bs_read_int_log(bs, 32, \"num_units_in_tick\");\n\t\t\tsps->time_scale = gf_bs_read_int_log(bs, 32, \"time_scale\");\n\t\t\tsps->poc_proportional_to_timing_flag = gf_bs_read_int_log(bs, 1, \"poc_proportional_to_timing_flag\");\n\t\t\tif (sps->poc_proportional_to_timing_flag)\n\t\t\t\tsps->num_ticks_poc_diff_one_minus1 = gf_bs_read_ue_log(bs, \"num_ticks_poc_diff_one_minus1\");\n\t\t\tif ((sps->hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"hrd_parameters_present_flag\"))) {\n\t\t\t\t//\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CODING, (\"[HEVC] HRD param parsing not implemented\\n\"));\n\t\t\t\treturn sps_id;\n\t\t\t}\n\t\t}",
"\t\tif (gf_bs_read_int_log(bs, 1, \"bitstream_restriction_flag\")) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"tiles_fixed_structure_flag\");\n\t\t\tgf_bs_read_int_log(bs, 1, \"motion_vectors_over_pic_boundaries_flag\");\n\t\t\tgf_bs_read_int_log(bs, 1, \"restricted_ref_pic_lists_flag\");\n\t\t\tgf_bs_read_ue_log(bs, \"min_spatial_segmentation_idc\");\n\t\t\tgf_bs_read_ue_log(bs, \"max_bytes_per_pic_denom\");\n\t\t\tgf_bs_read_ue_log(bs, \"max_bits_per_min_cu_denom\");\n\t\t\tgf_bs_read_ue_log(bs, \"log2_max_mv_length_horizontal\");\n\t\t\tgf_bs_read_ue_log(bs, \"log2_max_mv_length_vertical\");\n\t\t}\n\t}",
"\tif (gf_bs_read_int_log(bs, 1, \"sps_extension_flag\")) {\n#if 0\n\t\twhile (gf_bs_available(bs)) {\n\t\t\t/*sps_extension_data_flag */ gf_bs_read_int(bs, 1);\n\t\t}\n#endif",
"\t}",
"\treturn sps_id;\n}",
"GF_EXPORT\ns32 gf_hevc_read_sps_ex(char *data, u32 size, HEVCState *hevc, u32 *vui_flag_pos)\n{\n\tGF_BitStream *bs;\n\ts32 sps_id = -1;\n\tu8 layer_id;",
"\tif (vui_flag_pos) *vui_flag_pos = 0;",
"\tbs = gf_bs_new(data, size, GF_BITSTREAM_READ);\n\tif (!bs) goto exit;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tif (!hevc_parse_nal_header(bs, NULL, NULL, &layer_id)) goto exit;\n\tsps_id = gf_hevc_read_sps_bs_internal(bs, hevc, layer_id, vui_flag_pos);",
"exit:\n\tif (bs) gf_bs_del(bs);\n\treturn sps_id;\n}",
"GF_EXPORT\ns32 gf_hevc_read_sps(u8 *data, u32 size, HEVCState *hevc)\n{\n\treturn gf_hevc_read_sps_ex(data, size, hevc, NULL);\n}",
"GF_EXPORT\ns32 gf_hevc_read_sps_bs(GF_BitStream *bs, HEVCState *hevc)\n{\n\tu8 layer_id;\n\tif (!bs || !hevc) return -1;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\tif (!hevc_parse_nal_header(bs, NULL, NULL, &layer_id)) return -1;\n\treturn gf_hevc_read_sps_bs_internal(bs, hevc, layer_id, NULL);\n}",
"\nstatic s32 gf_hevc_read_pps_bs_internal(GF_BitStream *bs, HEVCState *hevc)\n{\n\tu32 i;\n\ts32 pps_id;\n\tHEVC_PPS *pps;",
"\t//NAL header already read\n\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");",
"\tif ((pps_id < 0) || (pps_id >= 64)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] wrong PPS ID %d in PPS\\n\", pps_id));\n\t\treturn -1;\n\t}\n\tpps = &hevc->pps[pps_id];",
"\tif (!pps->state) {\n\t\tpps->id = pps_id;\n\t\tpps->state = 1;\n\t}\n\tpps->sps_id = gf_bs_read_ue_log(bs, \"sps_id\");\n\tif (((s32)pps->sps_id<0) || (pps->sps_id >= 16)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] wrong SPS ID %d in PPS\\n\", pps->sps_id));\n\t\tpps->sps_id=0;\n\t\treturn -1;\n\t}\n\thevc->sps_active_idx = pps->sps_id; /*set active sps*/\n\tpps->dependent_slice_segments_enabled_flag = gf_bs_read_int_log(bs, 1, \"dependent_slice_segments_enabled_flag\");",
"\tpps->output_flag_present_flag = gf_bs_read_int_log(bs, 1, \"output_flag_present_flag\");\n\tpps->num_extra_slice_header_bits = gf_bs_read_int_log(bs, 3, \"num_extra_slice_header_bits\");\n\tpps->sign_data_hiding_flag = gf_bs_read_int_log(bs, 1, \"sign_data_hiding_flag\");\n\tpps->cabac_init_present_flag = gf_bs_read_int_log(bs, 1, \"cabac_init_present_flag\");\n\tpps->num_ref_idx_l0_default_active = 1 + gf_bs_read_ue_log(bs, \"num_ref_idx_l0_default_active\");\n\tpps->num_ref_idx_l1_default_active = 1 + gf_bs_read_ue_log(bs, \"num_ref_idx_l1_default_active\");\n\tpps->pic_init_qp_minus26 = gf_bs_read_se_log(bs, \"pic_init_qp_minus26\");\n\tpps->constrained_intra_pred_flag = gf_bs_read_int_log(bs, 1, \"constrained_intra_pred_flag\");\n\tpps->transform_skip_enabled_flag = gf_bs_read_int_log(bs, 1, \"transform_skip_enabled_flag\");\n\tif ((pps->cu_qp_delta_enabled_flag = gf_bs_read_int_log(bs, 1, \"cu_qp_delta_enabled_flag\")))\n\t\tpps->diff_cu_qp_delta_depth = gf_bs_read_ue_log(bs, \"diff_cu_qp_delta_depth\");",
"\tpps->pic_cb_qp_offset = gf_bs_read_se_log(bs, \"pic_cb_qp_offset\");\n\tpps->pic_cr_qp_offset = gf_bs_read_se_log(bs, \"pic_cr_qp_offset\");\n\tpps->slice_chroma_qp_offsets_present_flag = gf_bs_read_int_log(bs, 1, \"slice_chroma_qp_offsets_present_flag\");\n\tpps->weighted_pred_flag = gf_bs_read_int_log(bs, 1, \"weighted_pred_flag\");\n\tpps->weighted_bipred_flag = gf_bs_read_int_log(bs, 1, \"weighted_bipred_flag\");\n\tpps->transquant_bypass_enable_flag = gf_bs_read_int_log(bs, 1, \"transquant_bypass_enable_flag\");\n\tpps->tiles_enabled_flag = gf_bs_read_int_log(bs, 1, \"tiles_enabled_flag\");\n\tpps->entropy_coding_sync_enabled_flag = gf_bs_read_int_log(bs, 1, \"entropy_coding_sync_enabled_flag\");\n\tif (pps->tiles_enabled_flag) {\n\t\tpps->num_tile_columns = 1 + gf_bs_read_ue_log(bs, \"num_tile_columns_minus1\");\n\t\tpps->num_tile_rows = 1 + gf_bs_read_ue_log(bs, \"num_tile_rows_minus1\");\n\t\tpps->uniform_spacing_flag = gf_bs_read_int_log(bs, 1, \"uniform_spacing_flag\");\n\t\tif (!pps->uniform_spacing_flag) {\n\t\t\tfor (i = 0; i < pps->num_tile_columns - 1; i++) {\n\t\t\t\tpps->column_width[i] = 1 + gf_bs_read_ue_log_idx(bs, \"column_width_minus1\", i);\n\t\t\t}\n\t\t\tfor (i = 0; i < pps->num_tile_rows - 1; i++) {\n\t\t\t\tpps->row_height[i] = 1 + gf_bs_read_ue_log_idx(bs, \"row_height_minus1\", i);\n\t\t\t}\n\t\t}\n\t\tpps->loop_filter_across_tiles_enabled_flag = gf_bs_read_int_log(bs, 1, \"loop_filter_across_tiles_enabled_flag\");\n\t}\n\tpps->loop_filter_across_slices_enabled_flag = gf_bs_read_int_log(bs, 1, \"loop_filter_across_slices_enabled_flag\");\n\tif ((pps->deblocking_filter_control_present_flag = gf_bs_read_int_log(bs, 1, \"deblocking_filter_control_present_flag\"))) {\n\t\tpps->deblocking_filter_override_enabled_flag = gf_bs_read_int_log(bs, 1, \"deblocking_filter_override_enabled_flag\");\n\t\tif (! (pps->pic_disable_deblocking_filter_flag = gf_bs_read_int_log(bs, 1, \"pic_disable_deblocking_filter_flag\"))) {\n\t\t\tpps->beta_offset_div2 = gf_bs_read_se_log(bs, \"beta_offset_div2\");\n\t\t\tpps->tc_offset_div2 = gf_bs_read_se_log(bs, \"tc_offset_div2\");\n\t\t}\n\t}\n\tif ((pps->pic_scaling_list_data_present_flag = gf_bs_read_int_log(bs, 1, \"pic_scaling_list_data_present_flag\"))) {\n\t\thevc_scaling_list_data(bs);\n\t}\n\tpps->lists_modification_present_flag = gf_bs_read_int_log(bs, 1, \"lists_modification_present_flag\");\n\tpps->log2_parallel_merge_level_minus2 = gf_bs_read_ue_log(bs, \"log2_parallel_merge_level_minus2\");\n\tpps->slice_segment_header_extension_present_flag = gf_bs_read_int_log(bs, 1, \"slice_segment_header_extension_present_flag\");\n\tif (gf_bs_read_int_log(bs, 1, \"pps_extension_flag\")) {\n#if 0\n\t\twhile (gf_bs_available(bs)) {\n\t\t\t/*pps_extension_data_flag */ gf_bs_read_int(bs, 1);\n\t\t}\n#endif",
"\t}\n\treturn pps_id;\n}",
"\nGF_EXPORT\ns32 gf_hevc_read_pps(u8 *data, u32 size, HEVCState *hevc)\n{\n\tGF_BitStream *bs;\n\ts32 pps_id = -1;",
"\tbs = gf_bs_new(data, size, GF_BITSTREAM_READ);\n\tif (!bs) goto exit;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tif (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) goto exit;",
"\tpps_id = gf_hevc_read_pps_bs_internal(bs, hevc);",
"exit:\n\tif (bs) gf_bs_del(bs);\n\treturn pps_id;\n}",
"GF_EXPORT\ns32 gf_hevc_read_pps_bs(GF_BitStream *bs, HEVCState *hevc)\n{\n\tif (!bs || !hevc) return -1;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\tif (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) return -1;\n\treturn gf_hevc_read_pps_bs_internal(bs, hevc);\n}",
"GF_EXPORT\ns32 gf_hevc_parse_nalu_bs(GF_BitStream *bs, HEVCState *hevc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tBool is_slice = GF_FALSE;\n\ts32 ret = -1;\n\tHEVCSliceInfo n_state;",
"\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tmemcpy(&n_state, &hevc->s_info, sizeof(HEVCSliceInfo));\n\tif (!hevc_parse_nal_header(bs, nal_unit_type, temporal_id, layer_id)) return -1;",
"\tn_state.nal_unit_type = *nal_unit_type;",
"\tswitch (n_state.nal_unit_type) {\n\tcase GF_HEVC_NALU_ACCESS_UNIT:\n\tcase GF_HEVC_NALU_END_OF_SEQ:\n\tcase GF_HEVC_NALU_END_OF_STREAM:\n\t\tret = 1;\n\t\tbreak;",
"\t\t/*slice_segment_layer_rbsp*/\n\tcase GF_HEVC_NALU_SLICE_TRAIL_N:\n\tcase GF_HEVC_NALU_SLICE_TRAIL_R:\n\tcase GF_HEVC_NALU_SLICE_TSA_N:\n\tcase GF_HEVC_NALU_SLICE_TSA_R:\n\tcase GF_HEVC_NALU_SLICE_STSA_N:\n\tcase GF_HEVC_NALU_SLICE_STSA_R:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\tcase GF_HEVC_NALU_SLICE_CRA:\n\tcase GF_HEVC_NALU_SLICE_RADL_N:\n\tcase GF_HEVC_NALU_SLICE_RADL_R:\n\tcase GF_HEVC_NALU_SLICE_RASL_N:\n\tcase GF_HEVC_NALU_SLICE_RASL_R:\n\t\tis_slice = GF_TRUE;\n\t\t/* slice - read the info and compare.*/\n\t\tret = hevc_parse_slice_segment(bs, hevc, &n_state);\n\t\tif (ret < 0) return ret;",
"\t\thevc_compute_poc(&n_state);",
"\t\tret = 0;",
"\t\tif (hevc->s_info.poc != n_state.poc) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (n_state.first_slice_segment_in_pic_flag) {\n\t\t\tif (!(*layer_id) || (n_state.prev_layer_id_plus1 && ((*layer_id) <= n_state.prev_layer_id_plus1 - 1))) {\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase GF_HEVC_NALU_SEQ_PARAM:\n\t\thevc->last_parsed_sps_id = gf_hevc_read_sps_bs_internal(bs, hevc, *layer_id, NULL);\n\t\tret = (hevc->last_parsed_sps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tcase GF_HEVC_NALU_PIC_PARAM:\n\t\thevc->last_parsed_pps_id = gf_hevc_read_pps_bs_internal(bs, hevc);\n\t\tret = (hevc->last_parsed_pps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tcase GF_HEVC_NALU_VID_PARAM:\n\t\thevc->last_parsed_vps_id = gf_hevc_read_vps_bs_internal(bs, hevc, GF_FALSE);\n\t\tret = (hevc->last_parsed_vps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tdefault:\n\t\tret = 0;\n\t\tbreak;\n\t}",
"\t/* save _prev values */\n\tif ((ret>0) && hevc->s_info.sps) {\n\t\tn_state.frame_num_offset_prev = hevc->s_info.frame_num_offset;\n\t\tn_state.frame_num_prev = hevc->s_info.frame_num;",
"\t\tn_state.poc_lsb_prev = hevc->s_info.poc_lsb;\n\t\tn_state.poc_msb_prev = hevc->s_info.poc_msb;\n\t\tif (is_slice)\n\t\t\tn_state.prev_layer_id_plus1 = *layer_id + 1;\n\t}\n\tif (is_slice) hevc_compute_poc(&n_state);\n\tmemcpy(&hevc->s_info, &n_state, sizeof(HEVCSliceInfo));",
"\treturn ret;\n}",
"GF_EXPORT\ns32 gf_hevc_parse_nalu(u8 *data, u32 size, HEVCState *hevc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tGF_BitStream *bs = NULL;\n\ts32 ret = -1;",
"\tif (!hevc) {\n\t\tif (nal_unit_type) (*nal_unit_type) = (data[0] & 0x7E) >> 1;\n\t\tif (layer_id) {\n\t\t\tu8 id = data[0] & 1;\n\t\t\tid <<= 5;\n\t\t\tid |= (data[1] >> 3) & 0x1F;\n\t\t\t(*layer_id) = id;\n\t\t}\n\t\tif (temporal_id) (*temporal_id) = (data[1] & 0x7);\n\t\treturn -1;\n\t}",
"\tbs = gf_bs_new(data, size, GF_BITSTREAM_READ);\n\tif (!bs) return -1;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tret = gf_hevc_parse_nalu_bs(bs, hevc, nal_unit_type, temporal_id, layer_id);",
"\tgf_bs_del(bs);\n\treturn ret;\n}",
"GF_EXPORT\nGF_Err gf_hevc_change_vui(GF_HEVCConfig *hvcc, GF_VUIInfo *vui_info)\n{\n\tGF_BitStream *orig, *mod;\n\tHEVCState hevc;\n\tu32 i, bit_offset, flag;\n\ts32 idx;\n\tGF_NALUFFParamArray *spss;\n\tGF_NALUFFParam *slc;\n\torig = NULL;",
"\tmemset(&hevc, 0, sizeof(HEVCState));\n\thevc.sps_active_idx = -1;",
"\ti = 0;\n\tspss = NULL;\n\twhile ((spss = (GF_NALUFFParamArray *)gf_list_enum(hvcc->param_array, &i))) {\n\t\tif (spss->type == GF_HEVC_NALU_SEQ_PARAM)\n\t\t\tbreak;\n\t\tspss = NULL;\n\t}\n\tif (!spss) return GF_NON_COMPLIANT_BITSTREAM;",
"\ti = 0;\n\twhile ((slc = (GF_NALUFFParam *)gf_list_enum(spss->nalus, &i))) {\n\t\tu8 *no_emulation_buf;\n\t\tu32 no_emulation_buf_size, emulation_bytes;",
"\t\t/*SPS may still contains emulation bytes*/\n\t\tno_emulation_buf = gf_malloc((slc->size) * sizeof(char));\n\t\tno_emulation_buf_size = gf_media_nalu_remove_emulation_bytes(slc->data, no_emulation_buf, slc->size);",
"\t\tidx = gf_hevc_read_sps_ex(no_emulation_buf, no_emulation_buf_size, &hevc, &bit_offset);\n\t\tif (idx < 0) {\n\t\t\tif (orig)\n\t\t\t\tgf_bs_del(orig);\n\t\t\tgf_free(no_emulation_buf);\n\t\t\tcontinue;\n\t\t}",
"\t\torig = gf_bs_new(no_emulation_buf, no_emulation_buf_size, GF_BITSTREAM_READ);\n\t\tmod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);",
"\t\t/*copy over till vui flag*/\n\t\tassert(bit_offset >= 0);\n\t\twhile (bit_offset) {\n\t\t\tflag = gf_bs_read_int(orig, 1);\n\t\t\tgf_bs_write_int(mod, flag, 1);\n\t\t\tbit_offset--;\n\t\t}",
"\t\tavc_hevc_rewrite_vui(vui_info, orig, mod);",
"\t\t/*finally copy over remaining*/\n\t\twhile (gf_bs_bits_available(orig)) {\n\t\t\tflag = gf_bs_read_int(orig, 1);\n\t\t\tgf_bs_write_int(mod, flag, 1);\n\t\t}\n\t\tgf_bs_del(orig);\n\t\torig = NULL;\n\t\tgf_free(no_emulation_buf);",
"\t\t/*set anti-emulation*/\n\t\tgf_bs_get_content(mod, &no_emulation_buf, &no_emulation_buf_size);\n\t\temulation_bytes = gf_media_nalu_emulation_bytes_add_count(no_emulation_buf, no_emulation_buf_size);\n\t\tif (no_emulation_buf_size + emulation_bytes > slc->size)\n\t\t\tslc->data = (char*)gf_realloc(slc->data, no_emulation_buf_size + emulation_bytes);",
"\t\tslc->size = gf_media_nalu_add_emulation_bytes(no_emulation_buf, slc->data, no_emulation_buf_size);",
"\t\tgf_bs_del(mod);\n\t\tgf_free(no_emulation_buf);\n\t}\n\treturn GF_OK;\n}",
"\nGF_EXPORT\nGF_Err gf_hevc_change_par(GF_HEVCConfig *hvcc, s32 ar_n, s32 ar_d)\n{\n\tGF_VUIInfo vuii;\n\tmemset(&vuii, 0, sizeof(GF_VUIInfo));\n\tvuii.ar_num = ar_n;\n\tvuii.ar_den = ar_d;\n\tvuii.fullrange = -1;\n\tvuii.video_format = -1;\n\tvuii.color_prim = -1;\n\tvuii.color_tfc = -1;\n\tvuii.color_matrix = -1;\n\treturn gf_hevc_change_vui(hvcc, &vuii);\n}",
"GF_EXPORT\nGF_Err gf_hevc_change_color(GF_HEVCConfig *hvcc, s32 fullrange, s32 vidformat, s32 colorprim, s32 transfer, s32 colmatrix)\n{\n\tGF_VUIInfo vuii;\n\tmemset(&vuii, 0, sizeof(GF_VUIInfo));\n\tvuii.ar_num = -1;\n\tvuii.ar_den = -1;\n\tvuii.fullrange = fullrange;\n\tvuii.video_format = vidformat;\n\tvuii.color_prim = colorprim;\n\tvuii.color_tfc = transfer;\n\tvuii.color_matrix = colmatrix;\n\treturn gf_hevc_change_vui(hvcc, &vuii);\n}",
"\nGF_EXPORT\nGF_Err gf_hevc_get_sps_info_with_state(HEVCState *hevc, u8 *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)\n{\n\ts32 idx;\n\tidx = gf_hevc_read_sps(sps_data, sps_size, hevc);\n\tif (idx < 0) {\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\tif (sps_id) *sps_id = idx;",
"\tif (width) *width = hevc->sps[idx].width;\n\tif (height) *height = hevc->sps[idx].height;\n\tif (par_n) *par_n = hevc->sps[idx].aspect_ratio_info_present_flag ? hevc->sps[idx].sar_width : (u32)-1;\n\tif (par_d) *par_d = hevc->sps[idx].aspect_ratio_info_present_flag ? hevc->sps[idx].sar_height : (u32)-1;\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_hevc_get_sps_info(u8 *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)\n{\n\tHEVCState hevc;\n\tmemset(&hevc, 0, sizeof(HEVCState));\n\thevc.sps_active_idx = -1;\n\treturn gf_hevc_get_sps_info_with_state(&hevc, sps_data, sps_size, sps_id, width, height, par_n, par_d);\n}",
"\n#endif //GPAC_DISABLE_HEVC",
"static u32 AC3_FindSyncCode(u8 *buf, u32 buflen)\n{\n\tu32 end = buflen - 6;\n\tu32 offset = 0;\n\twhile (offset <= end) {\n\t\tif (buf[offset] == 0x0b && buf[offset + 1] == 0x77) {\n\t\t\treturn offset;\n\t\t}\n\t\toffset++;\n\t}\n\treturn buflen;\n}",
"\nstatic Bool AC3_FindSyncCodeBS(GF_BitStream *bs)\n{\n\tu8 b1;\n\tu64 pos = gf_bs_get_position(bs);\n\tu64 end = gf_bs_get_size(bs);",
"\tpos += 1;\n\tb1 = gf_bs_read_u8(bs);\n\twhile (pos + 1 <= end) {\n\t\tu8 b2 = gf_bs_read_u8(bs);\n\t\tif ((b1 == 0x0b) && (b2 == 0x77)) {\n\t\t\tgf_bs_seek(bs, pos - 1);\n\t\t\treturn GF_TRUE;\n\t\t}\n\t\tpos++;\n\t\tb1 = b2;\n\t}\n\treturn GF_FALSE;\n}",
"static const u32 ac3_sizecod_to_bitrate[] = {\n\t32000, 40000, 48000, 56000, 64000, 80000, 96000,\n\t112000, 128000, 160000, 192000, 224000, 256000,\n\t320000, 384000, 448000, 512000, 576000, 640000\n};",
"static const u32 ac3_sizecod2_to_framesize[] = {\n\t96, 120, 144, 168, 192, 240, 288, 336, 384, 480, 576, 672,\n\t768, 960, 1152, 1344, 1536, 1728, 1920\n};",
"static const u32 ac3_sizecod1_to_framesize[] = {\n\t69, 87, 104, 121, 139, 174, 208, 243, 278, 348, 417, 487,\n\t557, 696, 835, 975, 1114, 1253, 1393\n};\nstatic const u32 ac3_sizecod0_to_framesize[] = {\n\t64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448,\n\t512, 640, 768, 896, 1024, 1152, 1280\n};",
"static const u32 ac3_mod_to_chans[] = {\n\t2, 1, 2, 3, 3, 4, 4, 5\n};",
"GF_EXPORT\nu32 gf_ac3_get_channels(u32 acmod)\n{\n\tu32 nb_ch;\n\tnb_ch = ac3_mod_to_chans[acmod];\n\treturn nb_ch;\n}",
"GF_EXPORT\nu32 gf_ac3_get_bitrate(u32 brcode)\n{\n\treturn ac3_sizecod_to_bitrate[brcode];\n}",
"Bool gf_ac3_parser(u8 *buf, u32 buflen, u32 *pos, GF_AC3Config *hdr, Bool full_parse)\n{\n\tGF_BitStream *bs;\n\tBool ret;",
"\tif (buflen < 6) return GF_FALSE;\n\t(*pos) = AC3_FindSyncCode(buf, buflen);\n\tif (*pos >= buflen) return GF_FALSE;",
"\tbs = gf_bs_new((const char*)(buf + *pos), buflen, GF_BITSTREAM_READ);\n\tret = gf_ac3_parser_bs(bs, hdr, full_parse);\n\tgf_bs_del(bs);",
"\treturn ret;\n}",
"GF_EXPORT\nBool gf_ac3_parser_bs(GF_BitStream *bs, GF_AC3Config *hdr, Bool full_parse)\n{\n\tu32 fscod, frmsizecod, bsid, ac3_mod, freq, framesize, bsmod, syncword;\n\tu64 pos;\n\tif (!hdr || (gf_bs_available(bs) < 6)) return GF_FALSE;\n\tif (!AC3_FindSyncCodeBS(bs)) return GF_FALSE;",
"\tpos = gf_bs_get_position(bs);",
"\tsyncword = gf_bs_read_u16(bs);\n\tif (syncword != 0x0B77) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AC3] Wrong sync word detected (0x%X - expecting 0x0B77).\\n\", syncword));\n\t\treturn GF_FALSE;\n\t}\n\tgf_bs_read_int_log(bs, 16, \"crc1\");\n\tfscod = gf_bs_read_int_log(bs, 2, \"fscod\");\n\tfrmsizecod = gf_bs_read_int_log(bs, 6, \"frmsizecod\");\n\tbsid = gf_bs_read_int_log(bs, 5, \"bsid\");\n\tbsmod = gf_bs_read_int_log(bs, 3, \"bsmod\");\n\tac3_mod = gf_bs_read_int_log(bs, 3, \"ac3_mod\");\n\tif (frmsizecod >= 2 * sizeof(ac3_sizecod_to_bitrate) / sizeof(u32))\n\t\treturn GF_FALSE;",
"\thdr->bitrate = ac3_sizecod_to_bitrate[frmsizecod / 2];\n\tif (bsid > 8) hdr->bitrate = hdr->bitrate >> (bsid - 8);",
"\tswitch (fscod) {\n\tcase 0:\n\t\tif (frmsizecod >= 2 * sizeof(ac3_sizecod0_to_framesize) / sizeof(u32))\n\t\t\treturn GF_FALSE;\n\t\tfreq = 48000;\n\t\tframesize = ac3_sizecod0_to_framesize[frmsizecod / 2] * 2;\n\t\tbreak;\n\tcase 1:\n\t\tif (frmsizecod >= 2 * sizeof(ac3_sizecod1_to_framesize) / sizeof(u32))\n\t\t\treturn GF_FALSE;\n\t\tfreq = 44100;\n\t\tframesize = (ac3_sizecod1_to_framesize[frmsizecod / 2] + (frmsizecod & 0x1)) * 2;\n\t\tbreak;\n\tcase 2:\n\t\tif (frmsizecod >= 2 * sizeof(ac3_sizecod2_to_framesize) / sizeof(u32))\n\t\t\treturn GF_FALSE;\n\t\tfreq = 32000;\n\t\tframesize = ac3_sizecod2_to_framesize[frmsizecod / 2] * 2;\n\t\tbreak;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n\thdr->sample_rate = freq;\n\thdr->framesize = framesize;",
"\tif (full_parse) {\n\t\thdr->streams[0].bsid = bsid;\n\t\thdr->streams[0].bsmod = bsmod;\n\t\thdr->streams[0].acmod = ac3_mod;\n\t\thdr->streams[0].lfon = 0;\n\t\thdr->streams[0].fscod = fscod;\n\t\thdr->brcode = frmsizecod / 2;\n\t}\n\tif (ac3_mod >= 2 * sizeof(ac3_mod_to_chans) / sizeof(u32))\n\t\treturn GF_FALSE;",
"\thdr->channels = ac3_mod_to_chans[ac3_mod];\n\tif ((ac3_mod & 0x1) && (ac3_mod != 1)) gf_bs_read_int_log(bs, 2, \"cmixlev\");\n\tif (ac3_mod & 0x4) gf_bs_read_int_log(bs, 2, \"surmixlev\");\n\tif (ac3_mod == 0x2) gf_bs_read_int_log(bs, 2, \"dsurmod\");",
"\tif (gf_bs_read_int_log(bs, 1, \"lfeon\")) {\n\t\thdr->channels += 1;\n\t\thdr->streams[0].lfon = 1;\n\t}",
"\tgf_bs_seek(bs, pos);",
"\treturn GF_TRUE;\n}",
"GF_EXPORT\nBool gf_eac3_parser_bs(GF_BitStream *bs, GF_AC3Config *hdr, Bool full_parse)\n{\n\tu32 fscod, bsid, ac3_mod, freq, framesize, syncword, substreamid, lfon, channels, numblkscod, strmtyp, frmsiz;\n\tu64 pos;\n\tu16 chanmap;\n\tstatic u32 numblks[4] = {1, 2, 3, 6};",
"\tif (!hdr || (gf_bs_available(bs) < 6))\n\t\treturn GF_FALSE;\n\tif (!AC3_FindSyncCodeBS(bs))\n\t\treturn GF_FALSE;",
"\tpos = gf_bs_get_position(bs);\n\tframesize = 0;\n\tnumblkscod = 0;\n\tmemset(hdr, 0, sizeof(GF_AC3Config));",
"block:\n\tsyncword = gf_bs_read_u16(bs);\n\tif (syncword != 0x0B77) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[E-AC3] Wrong sync word detected (0x%X - expecting 0x0B77).\\n\", syncword));\n\t\treturn GF_FALSE;\n\t}",
"\tstrmtyp = gf_bs_read_int_log(bs, 2, \"strmtyp\");\n\tsubstreamid = gf_bs_read_int_log(bs, 3, \"substreamid\");\n\t//next main (independent) AU, done with this frame\n\tif ((strmtyp!=0x1) && ((hdr->substreams >> substreamid) & 0x1)) {\n\t\thdr->framesize = framesize;\n\t\tgf_bs_seek(bs, pos);\n\t\treturn GF_TRUE;\n\t}",
"\tfrmsiz = gf_bs_read_int_log(bs, 11, \"frmsiz\");\n\tframesize += 2 * (1 + frmsiz);\n\tfscod = gf_bs_read_int_log(bs, 2, \"fscod\");\n\tif (fscod == 0x3) {\n\t\tfscod = gf_bs_read_int_log(bs, 2, \"fscod2\");\n\t\tnumblkscod += 6;\n\t}\n\telse {\n\t\tnumblkscod += gf_bs_read_int_log(bs, 2, \"numblkscod\");\n\t}\n\tassert(numblkscod <= 9);",
"\n\tif ((hdr->substreams >> substreamid) & 0x1) {\n\t\t//we still have sync frames following\n\t\tif (substreamid) {\n\t\t\tif (gf_bs_seek(bs, pos + framesize) != GF_OK) {\n\t\t\t\tgf_bs_seek(bs, pos);\n\t\t\t\treturn GF_FALSE;\n\t\t\t}\n\t\t\tif ((gf_bs_available(bs) < 6) || !AC3_FindSyncCodeBS(bs)) {\n\t\t\t\tgf_bs_seek(bs, pos);\n\t\t\t\treturn GF_FALSE;\n\t\t\t}\n\t\t\tgoto block;\n\t\t}\n\t}",
"\thdr->substreams |= (1 << substreamid);",
"\tswitch (fscod) {\n\tcase 0:\n\t\tfreq = 48000;\n\t\tbreak;\n\tcase 1:\n\t\tfreq = 44100;\n\t\tbreak;\n\tcase 2:\n\t\tfreq = 32000;\n\t\tbreak;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}",
"\tac3_mod = gf_bs_read_int_log(bs, 3, \"ac3_mod\");\n\tlfon = gf_bs_read_int_log(bs, 1, \"lfon\");\n\tbsid = gf_bs_read_int_log(bs, 5, \"bsid\");\n\tif (!substreamid && (bsid != 16/*E-AC3*/))\n\t\treturn GF_FALSE;\n\tgf_bs_read_int_log(bs, 5, \"dialnorm\");\n\tif (gf_bs_read_int_log(bs, 1, \"compre\")) {\n\t\tgf_bs_read_int_log(bs, 8, \"compr\");\n\t}\n\tif (ac3_mod==0) {\n\t\tgf_bs_read_int_log(bs, 5, \"dialnorm2\");\n\t\tif (gf_bs_read_int_log(bs, 1, \"compr2e\")) {\n\t\t\tgf_bs_read_int_log(bs, 8, \"compr2\");\n\t\t}\n\t}\n\tchanmap = 0;\n\tif (strmtyp==0x1) {\n\t\tif (gf_bs_read_int_log(bs, 1, \"chanmape\")) {\n\t\t\tchanmap = gf_bs_read_int_log(bs, 16, \"chanmap\");\n\t\t}\n\t}",
"\tchannels = ac3_mod_to_chans[ac3_mod];\n\tif (lfon)\n\t\tchannels += 1;",
"\thdr->bitrate = 0;\n\thdr->sample_rate = freq;\n\thdr->framesize = framesize;\n\tif (strmtyp != 1) {\n\t\thdr->channels = channels;\n\t\thdr->streams[substreamid].lfon = lfon;\n\t\tif (full_parse) {\n\t\t\thdr->streams[substreamid].bsid = bsid;\n\t\t\thdr->streams[substreamid].bsmod = 0;\n\t\t\thdr->streams[substreamid].acmod = ac3_mod;\n\t\t\thdr->streams[substreamid].fscod = fscod;\n\t\t\thdr->brcode = 0;\n\t\t}\n\t\thdr->nb_streams++;\n\t\t//not clear if this is only for the independent streams\n\t\thdr->brcode += ((frmsiz+1) * freq) / (numblks[numblkscod]*16) / 1000;",
"\t\tif (lfon)\n\t\t\thdr->channels += 1;",
"\t} else {\n\t\thdr->streams[substreamid].nb_dep_sub = substreamid;\n\t\thdr->streams[substreamid].chan_loc |= chanmap;\n\t}",
"\tif (numblkscod < 6) { //we need 6 blocks to make a sample\n\t\tif (gf_bs_seek(bs, pos + framesize) != GF_OK) {\n\t\t\tgf_bs_seek(bs, pos);\n\t\t\treturn GF_FALSE;\n\t\t}",
"\t\tif ((gf_bs_available(bs) < 6) || !AC3_FindSyncCodeBS(bs))\n\t\t\treturn GF_FALSE;\n\t\tgoto block;\n\t}",
"\tgf_bs_seek(bs, pos);",
"\treturn GF_TRUE;\n}",
"#endif /*GPAC_DISABLE_AV_PARSERS*/",
"u32 gf_id3_read_size(GF_BitStream *bs)\n{\n\tu32 size = 0;\n\tgf_bs_read_int(bs, 1);\n\tsize |= gf_bs_read_int(bs, 7);\n\tsize<<=7;\n\tgf_bs_read_int(bs, 1);\n\tsize |= gf_bs_read_int(bs, 7);\n\tsize<<=7;\n\tgf_bs_read_int(bs, 1);\n\tsize |= gf_bs_read_int(bs, 7);\n\tsize<<=7;\n\tgf_bs_read_int(bs, 1);\n\tsize |= gf_bs_read_int(bs, 7);\n\treturn size;\n}",
"\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined (GPAC_DISABLE_OGG)",
"/*\n\tVorbis parser\n*/",
"static u32 vorbis_book_maptype1_quantvals(u32 entries, u32 dim)\n{\n\tu32 vals = (u32)floor(pow(entries, 1.0 / dim));\n\twhile (1) {\n\t\tu32 acc = 1;\n\t\tu32 acc1 = 1;\n\t\tu32 i;\n\t\tfor (i = 0; i < dim; i++) {\n\t\t\tacc *= vals;\n\t\t\tacc1 *= vals + 1;\n\t\t}\n\t\tif (acc <= entries && acc1 > entries) return (vals);\n\t\telse {\n\t\t\tif (acc > entries) vals--;\n\t\t\telse vals++;\n\t\t}\n\t}\n}",
"static u32 ilog(u32 v, Bool dec)\n{\n\tu32 ret = 0;\n\tif (dec && v) --v;\n\twhile (v) {\n\t\tret++;\n\t\tv >>= 1;\n\t}\n\treturn (ret);\n}",
"static u32 icount(u32 v)\n{\n\tu32 ret = 0;\n\twhile (v) {\n\t\tret += v & 1;\n\t\tv >>= 1;\n\t}\n\treturn(ret);\n}",
"\nGF_EXPORT\nBool gf_vorbis_parse_header(GF_VorbisParser *vp, u8 *data, u32 data_len)\n{\n\tu32 pack_type, i, j, k, times, nb_part, nb_books, nb_modes;\n\tu32 l;\n\tchar szNAME[8];\n\toggpack_buffer opb;",
"\toggpack_readinit(&opb, (u8*)data, data_len);\n\tpack_type = oggpack_read(&opb, 8);\n\ti = 0;\n\twhile (i < 6) {\n\t\tszNAME[i] = oggpack_read(&opb, 8);\n\t\ti++;\n\t}\n\tszNAME[i] = 0;\n\tif (strcmp(szNAME, \"vorbis\")) {\n\t\treturn GF_FALSE;\n\t}",
"\tswitch (pack_type) {\n\tcase 0x01:\n\t\tvp->version = oggpack_read(&opb, 32);\n\t\tif (vp->version != 0) {\n\t\t\treturn GF_FALSE;\n\t\t}\n\t\tvp->channels = oggpack_read(&opb, 8);\n\t\tvp->sample_rate = oggpack_read(&opb, 32);\n\t\tvp->max_r = oggpack_read(&opb, 32);\n\t\tvp->avg_r = oggpack_read(&opb, 32);\n\t\tvp->low_r = oggpack_read(&opb, 32);",
"\t\tvp->min_block = 1<<oggpack_read(&opb, 4);\n\t\tvp->max_block = 1<<oggpack_read(&opb, 4);\n\t\tif (vp->sample_rate < 1 || vp->channels < 1 || vp->min_block < 8 || vp->max_block < vp->min_block\n\t\t || oggpack_read(&opb, 1) != 1) {\n\t\t\treturn GF_FALSE;\n\t\t}\n\t\tvp->nb_init=1;\n\t\treturn GF_TRUE;",
"\tcase 0x03:\n\t\t/*trash comments*/\n\t\tvp->nb_init++;\n\t\treturn GF_TRUE;\n\tcase 0x05:\n\t\t/*need at least bitstream header to make sure we're parsing the right thing*/\n\t\tif (!vp->nb_init) return GF_FALSE;\n\t\tbreak;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n\t/*OK parse codebook*/\n\tnb_books = oggpack_read(&opb, 8) + 1;\n\t/*skip vorbis static books*/\n\tfor (i = 0; i < nb_books; i++) {\n\t\tu32 map_type, qb, qq;\n\t\tu32 entries, dim;\n\t\toggpack_read(&opb, 24);\n\t\tdim = oggpack_read(&opb, 16);\n\t\tentries = oggpack_read(&opb, 24);\n\t\tif ((s32)entries < 0) entries = 0;\n\t\tif (oggpack_read(&opb, 1) == 0) {\n\t\t\tif (oggpack_read(&opb, 1)) {\n\t\t\t\tfor (j = 0; j < entries; j++) {\n\t\t\t\t\tif (oggpack_read(&opb, 1)) {\n\t\t\t\t\t\toggpack_read(&opb, 5);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (j = 0; j < entries; j++)\n\t\t\t\t\toggpack_read(&opb, 5);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\toggpack_read(&opb, 5);\n\t\t\tfor (j = 0; j < entries;) {\n\t\t\t\tu32 num = oggpack_read(&opb, ilog(entries - j, GF_FALSE));\n\t\t\t\tfor (k = 0; k < num && j < entries; k++, j++) {\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tswitch ((map_type = oggpack_read(&opb, 4))) {\n\t\tcase 0:\n\t\t\tbreak;\n\t\tcase 1:\n\t\tcase 2:\n\t\t\toggpack_read(&opb, 32);\n\t\t\toggpack_read(&opb, 32);\n\t\t\tqq = oggpack_read(&opb, 4) + 1;\n\t\t\toggpack_read(&opb, 1);\n\t\t\tif (map_type == 1) qb = vorbis_book_maptype1_quantvals(entries, dim);\n\t\t\telse if (map_type == 2) qb = entries * dim;\n\t\t\telse qb = 0;\n\t\t\tfor (j = 0; j < qb; j++) oggpack_read(&opb, qq);\n\t\t\tbreak;\n\t\t}\n\t}\n\ttimes = oggpack_read(&opb, 6) + 1;\n\tfor (i = 0; i < times; i++) oggpack_read(&opb, 16);\n\ttimes = oggpack_read(&opb, 6) + 1;\n\tfor (i = 0; i < times; i++) {\n\t\tu32 type = oggpack_read(&opb, 16);\n\t\tif (type) {\n\t\t\tu32 *parts, *class_dims, count, rangebits;\n\t\t\tu32 max_class = 0;\n\t\t\tnb_part = oggpack_read(&opb, 5);\n\t\t\tparts = (u32*)gf_malloc(sizeof(u32) * nb_part);\n\t\t\tfor (j = 0; j < nb_part; j++) {\n\t\t\t\tparts[j] = oggpack_read(&opb, 4);\n\t\t\t\tif (max_class < parts[j]) max_class = parts[j];\n\t\t\t}\n\t\t\tclass_dims = (u32*)gf_malloc(sizeof(u32) * (max_class + 1));\n\t\t\tfor (j = 0; j < max_class + 1; j++) {\n\t\t\t\tu32 class_sub;\n\t\t\t\tclass_dims[j] = oggpack_read(&opb, 3) + 1;\n\t\t\t\tclass_sub = oggpack_read(&opb, 2);\n\t\t\t\tif (class_sub) oggpack_read(&opb, 8);\n\t\t\t\tfor (k = 0; k < (u32)(1 << class_sub); k++) oggpack_read(&opb, 8);\n\t\t\t}\n\t\t\toggpack_read(&opb, 2);\n\t\t\trangebits = oggpack_read(&opb, 4);\n\t\t\tcount = 0;\n\t\t\tfor (j = 0, k = 0; j < nb_part; j++) {\n\t\t\t\tcount += class_dims[parts[j]];\n\t\t\t\tfor (; k < count; k++) oggpack_read(&opb, rangebits);\n\t\t\t}\n\t\t\tgf_free(parts);\n\t\t\tgf_free(class_dims);\n\t\t}\n\t\telse {\n\t\t\toggpack_read(&opb, 8 + 16 + 16 + 6 + 8);\n\t\t\tnb_books = oggpack_read(&opb, 4) + 1;\n\t\t\tfor (j = 0; j < nb_books; j++)\n\t\t\t\toggpack_read(&opb, 8);\n\t\t}\n\t}\n\ttimes = oggpack_read(&opb, 6) + 1;\n\tfor (i = 0; i < times; i++) {\n\t\tu32 acc = 0;\n\t\toggpack_read(&opb, 16);/*type*/\n\t\toggpack_read(&opb, 24);\n\t\toggpack_read(&opb, 24);\n\t\toggpack_read(&opb, 24);\n\t\tnb_part = oggpack_read(&opb, 6) + 1;\n\t\toggpack_read(&opb, 8);\n\t\tfor (j = 0; j < nb_part; j++) {\n\t\t\tu32 cascade = oggpack_read(&opb, 3);\n\t\t\tif (oggpack_read(&opb, 1)) cascade |= (oggpack_read(&opb, 5) << 3);\n\t\t\tacc += icount(cascade);\n\t\t}\n\t\tfor (j = 0; j < acc; j++) oggpack_read(&opb, 8);\n\t}\n\ttimes = oggpack_read(&opb, 6) + 1;\n\tfor (i = 0; i < times; i++) {\n\t\tu32 sub_maps = 1;\n\t\toggpack_read(&opb, 16);\n\t\tif (oggpack_read(&opb, 1)) sub_maps = oggpack_read(&opb, 4) + 1;\n\t\tif (oggpack_read(&opb, 1)) {\n\t\t\tu32 nb_steps = oggpack_read(&opb, 8) + 1;\n\t\t\tfor (j = 0; j < nb_steps; j++) {\n\t\t\t\toggpack_read(&opb, ilog(vp->channels, GF_TRUE));\n\t\t\t\toggpack_read(&opb, ilog(vp->channels, GF_TRUE));\n\t\t\t}\n\t\t}\n\t\toggpack_read(&opb, 2);\n\t\tif (sub_maps>1) {\n\t\t\tfor(l=0; l<vp->channels; l++)\n\t\t\t\toggpack_read(&opb, 4);\n\t\t}\n\t\tfor (j = 0; j < sub_maps; j++) {\n\t\t\toggpack_read(&opb, 8);\n\t\t\toggpack_read(&opb, 8);\n\t\t\toggpack_read(&opb, 8);\n\t\t}\n\t}\n\tnb_modes = oggpack_read(&opb, 6) + 1;\n\tfor (i = 0; i < nb_modes; i++) {\n\t\tvp->mode_flag[i] = oggpack_read(&opb, 1);\n\t\toggpack_read(&opb, 16);\n\t\toggpack_read(&opb, 16);\n\t\toggpack_read(&opb, 8);\n\t}",
"\tvp->modebits = 0;\n\tj = nb_modes;\n\twhile (j > 1) {\n\t\tvp->modebits++;\n\t\tj >>= 1;\n\t}",
"\treturn GF_TRUE;\n}",
"GF_EXPORT\nu32 gf_vorbis_check_frame(GF_VorbisParser *vp, u8 *data, u32 data_length)\n{\n\ts32 block_size;\n\toggpack_buffer opb;\n\tif (!vp) return 0;\n\toggpack_readinit(&opb, (unsigned char*)data, data_length);\n\t/*not audio*/\n\tif (oggpack_read(&opb, 1) != 0) return 0;\n\tblock_size = oggpack_read(&opb, vp->modebits);\n\tif (block_size == -1) return 0;\n\treturn ((vp->mode_flag[block_size]) ? vp->max_block : vp->min_block) / (2);\n}",
"/*call with vorbis header packets - initializes the parser on success, leave it to NULL otherwise\nreturns 1 if success, 0 if error.*/\nBool gf_opus_parse_header(GF_OpusParser *opus, u8 *data, u32 data_len)\n{\n\tchar tag[9];\n\tGF_BitStream *bs = gf_bs_new(data, data_len, GF_BITSTREAM_READ);\n\tgf_bs_read_data(bs, tag, 8);\n\ttag[8]=0;",
"\tif (memcmp(data, \"OpusHead\", sizeof(char)*8)) {\n\t\tgf_bs_del(bs);\n\t\treturn GF_FALSE;\n\t}\n\t/*Identification Header*/\n\topus->version = gf_bs_read_u8(bs); /*version*/\n\tif (opus->version != 1) {\n\t\tgf_bs_del(bs);\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[Opus] Unsupported version %d\\n\", opus->version));\n\t\treturn GF_FALSE;\n\t}\n\topus->OutputChannelCount = gf_bs_read_u8(bs);\n\topus->PreSkip = gf_bs_read_u16_le(bs);\n\topus->InputSampleRate = gf_bs_read_u32_le(bs);\n\topus->OutputGain = gf_bs_read_u16_le(bs);\n\topus->ChannelMappingFamily = gf_bs_read_u8(bs);\n\tif (opus->ChannelMappingFamily != 0) {\n\t\topus->StreamCount = gf_bs_read_u8(bs);\n\t\topus->CoupledCount = gf_bs_read_u8(bs);\n\t\tgf_bs_read_data(bs, (char *) opus->ChannelMapping, opus->OutputChannelCount);\n\t}\n\tgf_bs_del(bs);\n\treturn GF_TRUE;\n}",
"/*returns 0 if init error or not a vorbis frame, otherwise returns the number of audio samples\nin this frame*/\nu32 gf_opus_check_frame(GF_OpusParser *op, u8 *data, u32 data_length)\n{\n\tu32 block_size;",
"\tif (!memcmp(data, \"OpusHead\", sizeof(char)*8))\n\t\treturn 0;\n\tif (!memcmp(data, \"OpusTags\", sizeof(char)*8))\n\t\treturn 0;",
"\t/*consider the whole packet as Ogg packets and ISOBMFF samples for Opus are framed similarly*/\n\tstatic const int OpusFrameDurIn48k[] = { 480, 960, 1920, 2880, 480, 960, 1920, 2880, 480, 960, 1920, 2880,\n\t\t480, 960, 480, 960,\n\t\t120, 240, 480, 960, 120, 240, 480, 960, 120, 240, 480, 960, 120, 240, 480, 960,\n\t};\n\tint TOC_config = (data[0] & 0xf8) >> 3;\n\t//int s = (data[0] & 0x04) >> 2;\n\tblock_size = OpusFrameDurIn48k[TOC_config];",
"\tint c = data[0] & 0x03;\n\tif (c == 1 || c == 2) {\n\t\tblock_size *= 2;\n\t} else if (c == 3) {\n\t\t/*unknown number of frames*/\n\t\tint num_frames = data[1] & 0x3f;\n\t\tblock_size *= num_frames;\n\t}\n\treturn block_size;\n}",
"#endif /*!defined(GPAC_DISABLE_AV_PARSERS) && !defined (GPAC_DISABLE_OGG)*/",
"u64 gf_mpegh_escaped_value(GF_BitStream *bs, u32 nBits1, u32 nBits2, u32 nBits3)\n{\n\tu64 value = gf_bs_read_int(bs, nBits1);\n\tif (value == (1<<nBits1)-1) {\n\t\tu32 vadd = gf_bs_read_int(bs, nBits2);\n\t\tvalue += vadd;\n\t\tif (vadd == (1<<nBits2)-1) {\n\t\t\tvadd = gf_bs_read_int(bs, nBits3);\n\t\t\tvalue += vadd;\n\t\t}\n\t}\n\treturn value;\n}",
"GF_EXPORT\ns32 gf_mpegh_get_mhas_pl(u8 *ptr, u32 size, u64 *ch_layout)\n{\n\ts32 PL = -1;\n\tGF_BitStream *bs;\n\tu32 i;\n\ts32 sync_pos=-1;",
"\tif (!ptr || !size) return 0;\n\t\n\tfor (i=0; i<size-3; i++) {\n\t\tif ((ptr[i]==0xC0) && (ptr[i+1]== 0x01) && (ptr[i+2]==0xA5)) {\n\t\t\tsync_pos = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (sync_pos<0) return 0;\n\tif (ch_layout) *ch_layout = 0;\n\tbs = gf_bs_new(ptr, size, GF_BITSTREAM_READ);\n\tgf_bs_skip_bytes(bs, sync_pos);",
"\twhile (gf_bs_available(bs)) {\n\t\tu32 type = (u32) gf_mpegh_escaped_value(bs, 3, 8, 8);\n\t\t/*u64 label = */gf_mpegh_escaped_value(bs, 2, 8, 32);\n\t\tu64 mh_size = gf_mpegh_escaped_value(bs, 11, 24, 24);\n\t\tif (mh_size > gf_bs_available(bs))\n\t\t\tbreak;\n\t\t//MHAS config\n\t\tif (type==1) {\n\t\t\tPL = gf_bs_read_int(bs, 8);\n\t\t\tif (ch_layout) {\n\t\t\t\tu32 idx = gf_bs_read_int(bs, 5);\n\t\t\t\tif (idx==0x1f)\n\t\t\t\t\tgf_bs_read_int(bs, 24);\n\t\t\t\t/*idx = */gf_bs_read_int(bs, 3);\n\t\t\t\tgf_bs_read_int(bs, 1);\n\t\t\t\tgf_bs_read_int(bs, 1);",
"\t\t\t\t//speaker config\n\t\t\t\tidx = gf_bs_read_int(bs, 2);\n\t\t\t\tif (idx == 0) {\n\t\t\t\t\t*ch_layout = gf_audio_fmt_get_layout_from_cicp( gf_bs_read_int(bs, 6) );\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tgf_bs_skip_bytes(bs, mh_size);\n\t}\n\tgf_bs_del(bs);\n\treturn PL;\n}",
"\nGF_EXPORT\nvoid gf_media_vvc_parse_sei(char *buffer, u32 nal_size, VVCState *vvc)\n{\n\tgf_hevc_vvc_parse_sei(buffer, nal_size, NULL, vvc);\n}",
"static Bool vvc_parse_nal_header(GF_BitStream *bs, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tu32 val;\n\tval = gf_bs_read_int_log(bs, 1, \"forbidden_zero\");\n\tif (val) return GF_FALSE;\n\tval = gf_bs_read_int_log(bs, 1, \"resevred0\");\n\tif (val) return GF_FALSE;",
"\tval = gf_bs_read_int_log(bs, 6, \"layerID\");\n\tif (layer_id) *layer_id = val;",
"\tval = gf_bs_read_int_log(bs, 5, \"nuh_type\");\n\tif (nal_unit_type) *nal_unit_type = val;",
"\tval = gf_bs_read_int_log(bs, 3, \"temporalID\");\n\tif (!val) return GF_FALSE;\n\tval -= 1;\n\tif (temporal_id) *temporal_id = val;\n\treturn GF_TRUE;\n}",
"static void vvc_profile_tier_level(GF_BitStream *bs, VVC_ProfileTierLevel *ptl, u32 idx)\n{\n\tu32 i;\n\tif (ptl->pt_present) {\n\t\tptl->general_profile_idc = gf_bs_read_int_log_idx(bs, 7, \"general_profile_idc\", idx);\n\t\tptl->general_tier_flag = gf_bs_read_int_log_idx(bs, 1, \"general_tier_flag\", idx);\n\t}\n\tptl->general_level_idc = gf_bs_read_int_log_idx(bs, 8, \"general_level_idc\", idx);\n\tptl->frame_only_constraint = gf_bs_read_int_log_idx(bs, 1, \"frame_only_constraint\", idx);\n\tptl->multilayer_enabled = gf_bs_read_int_log_idx(bs, 1, \"multilayer_enabled\", idx);\n\t//general constraints info - max size if 1 + 81 + 8 + 255\n\tif (ptl->pt_present) {\n\t\t//\t\tgeneral_constraints_info\n\t\tptl->gci_present = gf_bs_read_int_log_idx(bs, 1, \"gci_present\", idx);\n\t\tif (ptl->gci_present) {\n\t\t\tu8 res;\n\t\t\tptl->gci[0] = 0x80;\n\t\t\tptl->gci[0] |= gf_bs_read_int(bs, 7);\n\t\t\t//81-7 = 74 bits till reserved\n\t\t\tgf_bs_read_data(bs, ptl->gci+1, 9);\n\t\t\tptl->gci[10] = gf_bs_read_int(bs, 2)<<6;\n\t\t\t//skip extensions\n\t\t\tptl->gci[11] = 0;\n\t\t\tres = gf_bs_read_int(bs, 8);\n\t\t\tgf_bs_read_int(bs, res);\n\t\t}\n\t\tgf_bs_align(bs);\n\t}\n\tfor (i=ptl->ptl_max_tid; i>0; i--) {\n\t\tptl->sub_ptl[i-1].level_present_flag = gf_bs_read_int_log_idx2(bs, 1, \"level_present_flag\", idx, i);\n\t}\n\tgf_bs_align(bs);\n\tfor (i=ptl->ptl_max_tid; i>0; i--) {\n\t\tif (ptl->sub_ptl[i-1].level_present_flag)\n\t\t\tptl->sub_ptl[i-1].sublayer_level_idc = gf_bs_read_int_log_idx2(bs, 8, \"sublayer_level_idc\", idx, i);\n\t}\n\tif (ptl->pt_present) {\n\t\tptl->num_sub_profiles = gf_bs_read_int_log_idx(bs, 8, \"num_sub_profiles\", idx);\n\t\tfor (i=0; i<ptl->num_sub_profiles; i++) {\n\t\t\tptl->sub_profile_idc[i] = gf_bs_read_int_log_idx2(bs, 32, \"sub_profile_idc\", idx, i);\n\t\t}\n\t}\n}",
"static s32 gf_media_vvc_read_vps_bs_internal(GF_BitStream *bs, VVCState *vvc, Bool stop_at_vps_ext)\n{\n\tu32 i, j;\n\ts32 vps_id;\n\tVVC_VPS *vps;\n\tBool vps_default_ptl_dpb_hrd_max_tid_flag=0;",
"\t//nalu header already parsed\n\tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n\tif ((vps_id<0) || (vps_id >= 16)) return -1;\n\tif (!vps_id) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] VPS ID 0 is forbidden\\n\"));\n\t\treturn -1;\n\t}\n\tvps = &vvc->vps[vps_id];\n\tif (!vps->state) {\n\t\tvps->id = vps_id;\n\t\tvps->state = 1;\n\t}\n\tvps->max_layers = 1 + gf_bs_read_int_log(bs, 6, \"max_layers\");\n\tif (vps->max_layers > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] sorry, %d layers in VPS but only %d supported\\n\", vps->max_layers, MAX_LHVC_LAYERS));\n\t\treturn -1;\n\t}\n\tvps->max_sub_layers = gf_bs_read_int_log(bs, 3, \"max_sub_layers_minus1\") + 1;",
"\tif ((vps->max_layers>1) && (vps->max_sub_layers>1))\n\t\tvps_default_ptl_dpb_hrd_max_tid_flag = gf_bs_read_int_log(bs, 1, \"vps_default_ptl_dpb_hrd_max_tid_flag\");",
"\tif (vps->max_layers>1)\n\t\tvps->all_layers_independent = gf_bs_read_int_log(bs, 1, \"all_layers_independent\");",
"\tfor (i=0; i<vps->max_layers; i++) {\n\t\tu32 layer_id = gf_bs_read_int_log_idx(bs, 6, \"layer_id\", i);\n\t\tif (layer_id>vps->max_layer_id) vps->max_layer_id = layer_id;\n\t\tif (i && !vps->all_layers_independent) {\n\t\t\tBool layer_indep = gf_bs_read_int_log_idx(bs, 1, \"layer_independent\", i);\n\t\t\tif (!layer_indep) {\n\t\t\t\tBool vps_max_tid_ref_present_flag = gf_bs_read_int_log_idx(bs, 1, \"vps_max_tid_ref_present_flag\", i);\n\t\t\t\tfor (j=0; j<i; j++) {\n\t\t\t\t\tBool vps_direct_ref_layer_flag = gf_bs_read_int_log_idx2(bs, 1, \"vps_direct_ref_layer_flag\", i, j);\n\t\t\t\t\tif (vps_max_tid_ref_present_flag && vps_direct_ref_layer_flag) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx2(bs, 3, \"vps_max_tid_il_ref_pics_plus1\", i, j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tvps->num_ptl = 1;\n\tif (vps->max_layers > 1) {\n\t\tif (vps->all_layers_independent) {\n\t\t\tvps->each_layer_is_ols = gf_bs_read_int_log(bs, 1, \"each_layer_is_ols\");\n\t\t}\n\t\tif (!vps->each_layer_is_ols) {\n\t\t\tu32 vps_ols_mode_idc = 2;\n\t\t\tif (!vps->all_layers_independent) {\n\t\t\t\tvps_ols_mode_idc = gf_bs_read_int_log(bs, 2, \"vps_ols_mode_idc\");\n\t\t\t}\n\t\t\tif (vps_ols_mode_idc==2) {\n\t\t\t\tu8 vps_num_output_layer_sets = 2 + gf_bs_read_int_log(bs, 8, \"vps_num_output_layer_sets_minus2\");\n\t\t\t\tfor (i=0; i<vps_num_output_layer_sets; i++) {\n\t\t\t\t\tfor (j=0; j<vps->max_layers; j++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx2(bs, 1, \"vps_ols_output_layer_flag\", i, j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvps->num_ptl = 1 + gf_bs_read_int_log(bs, 8, \"num_ptl_minus1\");\n\t}\n\tvps->ptl[0].pt_present = 1;\n\tfor (i=0; i<vps->num_ptl; i++) {\n\t\tif (i)\n\t\t\tvps->ptl[i].pt_present = gf_bs_read_int_log_idx(bs, 1, \"pt_present\", i);\n\t\tif (!vps_default_ptl_dpb_hrd_max_tid_flag)\n\t\t\tvps->ptl[i].ptl_max_tid = gf_bs_read_int_log_idx(bs, 3, \"ptl_max_tid\", i);\n\t\telse\n\t\t\tvps->ptl[i].ptl_max_tid = vps->max_sub_layers - 1;\n\t}\n\t//align\n\tgf_bs_align(bs);",
"\tfor (i=0; i<vps->num_ptl; i++) {\n\t\tvvc_profile_tier_level(bs, &vps->ptl[i], i);\n\t}",
"\t//TODO, parse multilayer stuff\n\treturn vps_id;\n}",
"\nstatic s32 gf_media_vvc_read_sps_bs_internal(GF_BitStream *bs, VVCState *vvc, u8 layer_id, u32 *vui_flag_pos)\n{\n\ts32 vps_id, sps_id;\n\tu32 i, CtbSizeY;\n\tVVC_SPS *sps;\n\tu8 sps_ptl_dpb_hrd_params_present_flag;",
"\tif (vui_flag_pos) *vui_flag_pos = 0;",
"\tsps_id = gf_bs_read_int_log(bs, 4, \"sps_id\");\n\tif ((sps_id<0) || (sps_id >= 16)) {\n\t\treturn -1;\n\t}\n\tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n\tif ((vps_id<0) || (vps_id >= 16)) {\n\t\treturn -1;\n\t}\n\tif (!vps_id && !vvc->vps[0].state) {\n\t\tvvc->vps[0].state = 1;\n\t\tvvc->vps[0].num_ptl = 1;\n\t\tvvc->vps[0].max_layers = 1;\n\t\tvvc->vps[0].all_layers_independent = 1;\n\t}",
"\tsps = &vvc->sps[sps_id];\n\tif (!sps->state) {\n\t\tsps->state = 1;\n\t\tsps->id = sps_id;\n\t\tsps->vps_id = vps_id;\n\t}\n\tsps->max_sublayers = 1 + gf_bs_read_int_log(bs, 3, \"max_sublayers_minus1\");\n\tsps->chroma_format_idc = gf_bs_read_int_log(bs, 2, \"chroma_format_idc\");\n\tsps->log2_ctu_size = 5 + gf_bs_read_int_log(bs, 2, \"log2_ctu_size_minus5\");\n\tCtbSizeY = 1<<sps->log2_ctu_size;",
"\tsps_ptl_dpb_hrd_params_present_flag = gf_bs_read_int_log(bs, 1, \"sps_ptl_dpb_hrd_params_present_flag\");\n\tif (sps_ptl_dpb_hrd_params_present_flag) {\n\t\tVVC_ProfileTierLevel ptl, *p_ptl;\n\t\tif (sps->vps_id) {\n\t\t\tp_ptl = &ptl;\n\t\t} else {\n\t\t\tp_ptl = &vvc->vps[0].ptl[0];\n\t\t}\n\t\tmemset(p_ptl, 0, sizeof(VVC_ProfileTierLevel));\n\t\tp_ptl->pt_present = 1;\n\t\tp_ptl->ptl_max_tid = sps->max_sublayers-1;\n\t\tvvc_profile_tier_level(bs, p_ptl, 0);\n\t}\n\tsps->gdr_enabled = gf_bs_read_int_log(bs, 1, \"gdr_enabled\");\n\tsps->ref_pic_resampling = gf_bs_read_int_log(bs, 1, \"ref_pic_resampling\");\n\tif (sps->ref_pic_resampling)\n\t\tsps->res_change_in_clvs = gf_bs_read_int_log(bs, 1, \"res_change_in_clvs\");\n\tsps->width = gf_bs_read_ue_log(bs, \"width\");\n\tsps->height = gf_bs_read_ue_log(bs, \"height\");\n\tsps->conf_window = gf_bs_read_int_log(bs, 1, \"conformance_window_present_flag\");\n\tif (sps->conf_window) {\n\t\tsps->cw_left = gf_bs_read_ue_log(bs, \"conformance_window_left\");\n\t\tsps->cw_right = gf_bs_read_ue_log(bs, \"conformance_window_right\");\n\t\tsps->cw_top = gf_bs_read_ue_log(bs, \"conformance_window_top\");\n\t\tsps->cw_bottom = gf_bs_read_ue_log(bs, \"conformance_window_bottom\");\n\t}\n\tsps->subpic_info_present = gf_bs_read_int_log(bs, 1, \"subpic_info_present\");\n\tif (sps->subpic_info_present) {\n\t\tsps->nb_subpics = 1 + gf_bs_read_ue_log(bs, \"nb_subpics_minus1\");\n\t\tif (sps->nb_subpics>1) {\n\t\t\tu32 tmpWidthVal, tmpHeightVal;\n\t\t\tsps->independent_subpic_flags = gf_bs_read_int_log(bs, 1, \"independent_subpic_flags\");\n\t\t\tsps->subpic_same_size = gf_bs_read_int_log(bs, 1, \"subpic_same_size\");",
"\t\t\ttmpWidthVal = (sps->width + CtbSizeY-1) / CtbSizeY;\n\t\t\ttmpWidthVal = gf_get_bit_size(tmpWidthVal);\n\t\t\ttmpHeightVal = (sps->height + CtbSizeY-1) / CtbSizeY;\n\t\t\ttmpHeightVal = gf_get_bit_size(tmpHeightVal);",
"\t\t\tfor (i=0; i<sps->nb_subpics; i++) {\n\t\t\t\tif( !sps->subpic_same_size || !i) {\n\t\t\t\t\tif (i && (sps->width > CtbSizeY))\n\t\t\t\t\t\tgf_bs_read_int_log(bs, tmpWidthVal, \"subpic_ctu_top_left_x\");\n\t\t\t\t\tif (i && (sps->height > CtbSizeY))\n\t\t\t\t\t\tgf_bs_read_int_log(bs, tmpHeightVal, \"subpic_ctu_top_left_y\");\n\t\t\t\t\tif ((i+1 < sps->nb_subpics) && (sps->width > CtbSizeY))\n\t\t\t\t\t\tgf_bs_read_int_log(bs, tmpWidthVal, \"subpic_width_minus1\");\n\t\t\t\t\tif ((i+1 < sps->nb_subpics) && (sps->height > CtbSizeY))\n\t\t\t\t\t\tgf_bs_read_int_log(bs, tmpHeightVal, \"subpic_height_minus1\");\n\t\t\t\t}\n\t\t\t\tif (!sps->independent_subpic_flags) {\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"subpic_treated_as_pic_flag\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"loop_filter_across_subpic_enabled_flag\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tsps->subpicid_len = gf_bs_read_ue_log(bs, \"subpic_id_len_minus1\") + 1;\n\t\t\tsps->subpicid_mapping_explicit = gf_bs_read_int_log(bs, 1, \"subpic_id_mapping_explicitly_signalled_flag\");\n\t\t\tif (sps->subpicid_mapping_explicit) {\n\t\t\t\tsps->subpicid_mapping_present = gf_bs_read_int_log(bs, 1, \"subpic_id_mapping_present_flag\");\n\t\t\t\tif (sps->subpicid_mapping_present) {\n\t\t\t\t\tfor (i=0; i<sps->nb_subpics; i++) {\n\t\t\t\t\t\tgf_bs_read_ue_log(bs, \"subpic_id\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tsps->bitdepth = gf_bs_read_ue_log(bs, \"bitdepth_minus8\") + 8;\n\tgf_bs_read_int_log(bs, 1, \"entropy_coding_sync_enabled_flag\");\n\tgf_bs_read_int_log(bs, 1, \"entry_point_offsets_present_flag\");\n\tsps->log2_max_poc_lsb = 4 + gf_bs_read_int_log(bs, 4, \"log2_max_poc_lsb_minus4\");\n\tif ((sps->poc_msb_cycle_flag = gf_bs_read_int_log(bs, 1, \"poc_msb_cycle_flag\")))\n\t\tsps->poc_msb_cycle_len = 1 + gf_bs_read_ue_log(bs, \"poc_msb_cycle_len_minus1\");",
"\tu8 sps_num_extra_ph_bits = 8 * gf_bs_read_int_log(bs, 2, \"sps_num_extra_ph_bytes\");\n\tfor (i=0; i<sps_num_extra_ph_bits; i++) {\n\t\tif (gf_bs_read_int_log_idx(bs, 1, \"extra_ph_bit_present_flag\", 1))\n\t\t\tsps->ph_num_extra_bits++;\n\t}\n\tu8 sps_num_extra_sh_bits = 8 * gf_bs_read_int_log(bs, 2, \"num_extra_sh_bytes\");\n\tfor (i=0; i<sps_num_extra_sh_bits; i++) {\n\t\tif (gf_bs_read_int_log_idx(bs, 1, \"extra_sh_bit_present_flag\", i))\n\t\t\tsps->sh_num_extra_bits++;\n\t}",
"\tif (sps_ptl_dpb_hrd_params_present_flag) {\n\t\tu8 sps_sublayer_dpb_params_flag = 0;\n\t\tif (sps->max_sublayers>1) {\n\t\t\tsps_sublayer_dpb_params_flag = gf_bs_read_int_log(bs, 1, \"sps_sublayer_dpb_params_flag\");\n\t\t}\n\t\tfor (i=(sps_sublayer_dpb_params_flag ? 0 : sps->max_sublayers-1); i < sps->max_sublayers; i++ ) {\n\t\t\tgf_bs_read_ue_log_idx(bs, \"dpb_max_dec_pic_buffering_minus1\", i);\n\t\t\tgf_bs_read_ue_log_idx(bs, \"dpb_max_num_reorder_pics\", i);\n\t\t\tgf_bs_read_ue_log_idx(bs, \"dpb_max_latency_increase_plus1\", i);\n\t\t}\n\t}\n\tgf_bs_read_ue_log(bs, \"sps_log2_min_luma_coding_block_size_minus2\");\n\tgf_bs_read_int_log(bs, 1, \"sps_partition_constraints_override_enabled_flag\");\n\tgf_bs_read_ue_log(bs, \"sps_log2_min_luma_coding_block_size_minus2\");\n\tu8 sps_max_mtt_hierarchy_depth_intra_slice_luma = gf_bs_read_ue_log(bs, \"sps_max_mtt_hierarchy_depth_intra_slice_luma\");\n\tif (sps_max_mtt_hierarchy_depth_intra_slice_luma != 0) {\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_bt_min_qt_intra_slice_luma\");\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_tt_min_qt_intra_slice_luma\");\n\t}\n\tu8 sps_qtbtt_dual_tree_intra_flag = 0;\n\tif (sps->chroma_format_idc) {\n\t\tsps_qtbtt_dual_tree_intra_flag = gf_bs_read_int_log(bs, 1, \"sps_qtbtt_dual_tree_intra_flag\");\n\t}\n\tif (sps_qtbtt_dual_tree_intra_flag) {\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_min_qt_min_cb_intra_slice_chroma\");\n\t\tu8 sps_max_mtt_hierarchy_depth_intra_slice_chroma = gf_bs_read_ue_log(bs, \"sps_max_mtt_hierarchy_depth_intra_slice_chroma\");\n\t\tif( sps_max_mtt_hierarchy_depth_intra_slice_chroma != 0) {\n\t\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_bt_min_qt_intra_slice_chroma\");\n\t\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_tt_min_qt_intra_slice_chroma\");\n\t\t}\n\t}",
"\tgf_bs_read_ue_log(bs, \"sps_log2_diff_min_qt_min_cb_inter_slice\");\n\tu8 sps_max_mtt_hierarchy_depth_inter_slice = gf_bs_read_ue_log(bs, \"sps_max_mtt_hierarchy_depth_inter_slice\");\n\tif (sps_max_mtt_hierarchy_depth_inter_slice != 0) {\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_bt_min_qt_inter_slice\");\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_tt_min_qt_inter_slice\");\n\t}\n\t//u8 sps_max_luma_transform_size_64_flag = 0;\n\tif (CtbSizeY > 32) {\n\t\t/*sps_max_luma_transform_size_64_flag = */gf_bs_read_int_log(bs, 1, \"sps_max_luma_transform_size_64_flag\");\n\t}\n\tu8 sps_transform_skip_enabled_flag = gf_bs_read_int_log(bs, 1, \"sps_transform_skip_enabled_flag\");",
"\tif (sps_transform_skip_enabled_flag) {\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_transform_skip_max_size_minus2\");\n\t\tgf_bs_read_int_log(bs, 1, \"sps_bdpcm_enabled_flag\");\n\t}\n\tif (gf_bs_read_int_log(bs, 1, \"sps_mts_enabled_flag\")) {\n\t\tgf_bs_read_int_log(bs, 1, \"sps_explicit_mts_intra_enabled_flag\");\n\t\tgf_bs_read_int_log(bs, 1, \"sps_explicit_mts_inter_enabled_flag\");\n\t}\n\tgf_bs_read_int_log(bs, 1, \"sps_lfnst_enabled_flag\");\n\tif (sps->chroma_format_idc) {\n\t\tu8 sps_joint_cbcr_enabled_flag = gf_bs_read_int_log(bs, 1, \"sps_joint_cbcr_enabled_flag\");\n\t\tu8 sps_same_qp_table_for_chroma_flag = gf_bs_read_int_log(bs, 1, \"sps_same_qp_table_for_chroma_flag\");\n\t\tu32 numQpTables = sps_same_qp_table_for_chroma_flag ? 1 : (sps_joint_cbcr_enabled_flag ? 3 : 2);\n\t\tfor (i=0; i<numQpTables; i++) {\n\t\t\tgf_bs_read_se_log_idx(bs, \"sps_qp_table_start_minus26\", i);\n\t\t\tu32 j, sps_num_points_in_qp_table = 1 + gf_bs_read_ue_log_idx(bs, \"sps_num_points_in_qp_table_minus1\", i);\n\t\t\tfor (j=0; j<sps_num_points_in_qp_table; j++) {\n\t\t\t\tgf_bs_read_ue_log_idx2(bs, \"sps_delta_qp_in_val_minus1\", i, j);\n\t\t\t\tgf_bs_read_ue_log_idx2(bs, \"sps_delta_qp_diff_val\", i, j);\n\t\t\t}\n\t\t}\n\t}\n\tgf_bs_read_int_log(bs, 1, \"sps_sao_enabled_flag\");\n\tsps->alf_enabled_flag = gf_bs_read_int_log(bs, 1, \"sps_alf_enabled_flag\");\n\tif (sps->alf_enabled_flag && sps->chroma_format_idc) {\n\t\tgf_bs_read_int_log(bs, 1, \"sps_ccalf_enabled_flag\");\n\t}\n\t/*! TODO parse the rest !*/",
"\treturn sps_id;\n}",
"static s32 gf_media_vvc_read_pps_bs_internal(GF_BitStream *bs, VVCState *vvc)\n{\n\tu32 i;\n\ts32 pps_id;\n\tVVC_PPS *pps;",
"\t//NAL header already read\n\tpps_id = gf_bs_read_int_log(bs, 6, \"pps_id\");",
"\tif ((pps_id < 0) || (pps_id >= 64)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] wrong PPS ID %d in PPS\\n\", pps_id));\n\t\treturn -1;\n\t}\n\tpps = &vvc->pps[pps_id];",
"\tif (!pps->state) {\n\t\tpps->id = pps_id;\n\t\tpps->state = 1;\n\t}\n\tpps->sps_id = gf_bs_read_int_log(bs, 4, \"sps_id\");\n\tif (((s32)pps->sps_id<0) || (pps->sps_id >= 16)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] wrong SPS ID %d in PPS\\n\", pps->sps_id));\n\t\tpps->sps_id=0;\n\t\treturn -1;\n\t}\n\tvvc->sps_active_idx = pps->sps_id; /*set active sps*/\n\tpps->mixed_nal_types = gf_bs_read_int_log(bs, 1, \"mixed_nal_types\");\n\tpps->width = gf_bs_read_ue_log(bs, \"width\");\n\tpps->height = gf_bs_read_ue_log(bs, \"height\");\n\tpps->conf_window = gf_bs_read_int_log(bs, 1, \"conformance_window_flag\");\n\tif (pps->conf_window) {\n\t\tpps->cw_left = gf_bs_read_ue_log(bs, \"conf_win_left_offset\");\n\t\tpps->cw_right = gf_bs_read_ue_log(bs, \"conf_win_right_offset\");\n\t\tpps->cw_top = gf_bs_read_ue_log(bs, \"conf_win_top_offset\");\n\t\tpps->cw_bottom = gf_bs_read_ue_log(bs, \"conf_win_bottom_offset\");\n\t}\n\t//scaling window\n\tif (gf_bs_read_int_log(bs, 1, \"scaling_window_explicit_signaling_flag\")) {\n\t\tgf_bs_read_se_log(bs, \"scaling_win_left_offset\");\n\t\tgf_bs_read_se_log(bs, \"scaling_win_right_offset\");\n\t\tgf_bs_read_se_log(bs, \"scaling_win_top_offset\");\n\t\tgf_bs_read_se_log(bs, \"scaling_win_bottom_offset\");\n\t}\n\tpps->output_flag_present_flag = gf_bs_read_int_log(bs, 1, \"output_flag_present_flag\");\n\tpps->no_pic_partition_flag = gf_bs_read_int_log(bs, 1, \"no_pic_partition_flag\");\n\tpps->subpic_id_mapping_present_flag = gf_bs_read_int_log(bs, 1, \"subpic_id_mapping_present_flag\");\n\tif (pps->subpic_id_mapping_present_flag) {\n\t\tu32 pps_subpic_id_len, pps_num_subpics=0;\n\t\tif (!pps->no_pic_partition_flag) {\n\t\t\tpps_num_subpics = 1+gf_bs_read_ue_log(bs, \"pps_num_subpics_minus1\");\n\t\t}\n\t\tpps_subpic_id_len = 1 + gf_bs_read_ue(bs);\n\t\tfor (i=0; i<pps_num_subpics; i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, pps_subpic_id_len, \"subpic_id\", i);\n\t\t}\n\t}\n\tif (!pps->no_pic_partition_flag) {\n\t\tgf_bs_read_int_log(bs, 2, \"pps_log2_ctu_size_minus5\");\n\t\tu32 num_exp_tile_columns = 1 + gf_bs_read_ue_log(bs, \"num_exp_tile_columns_minus1\");\n\t\tu32 num_exp_tile_rows = 1 + gf_bs_read_ue_log(bs, \"num_exp_tile_rows_minus1\");\n\t\tfor (i=0; i<num_exp_tile_columns; i++)\n\t\t\tgf_bs_read_ue_log_idx(bs, \"tile_column_width_minus1\", i);\n\t\tfor (i=0; i<num_exp_tile_rows; i++)\n\t\t\tgf_bs_read_ue_log_idx(bs, \"tile_row_height_minus1\", i);",
"\t\t//todo parse the rest\n\t\treturn pps_id;\n\t}",
"\n\t//todo parse the rest",
"\treturn pps_id;\n}",
"static\ns32 vvc_parse_picture_header(GF_BitStream *bs, VVCState *vvc, VVCSliceInfo *si)\n{\n\ts32 pps_id;",
"\tsi->irap_or_gdr_pic = gf_bs_read_int_log(bs, 1, \"irap_or_gdr_pic\");\n\tsi->non_ref_pic = gf_bs_read_int_log(bs, 1, \"non_ref_pic\");\n\tif (si->irap_or_gdr_pic)\n\t\tsi->gdr_pic = gf_bs_read_int_log(bs, 1, \"gdr_pic\");\n\tif ((si->inter_slice_allowed_flag = gf_bs_read_int_log(bs, 1, \"inter_slice_allowed_flag\")))\n\t\tsi->intra_slice_allowed_flag = gf_bs_read_int_log(bs, 1, \"intra_slice_allowed_flag\");",
"\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\tif ((pps_id<0) || (pps_id >= 64))\n\t\treturn -1;\n\tsi->pps = &vvc->pps[pps_id];\n\tsi->sps = &vvc->sps[si->pps->sps_id];\n\tsi->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, \"poc_lsb\");",
"\tsi->recovery_point_valid = 0;\n\tsi->gdr_recovery_count = 0;\n\tif (si->gdr_pic) {\n\t\tsi->recovery_point_valid = 1;\n\t\tsi->gdr_recovery_count = gf_bs_read_ue_log(bs, \"gdr_recovery_count\");\n\t}\n\tgf_bs_read_int_log(bs, si->sps->ph_num_extra_bits, \"ph_extra_bits\");",
"\tif (si->sps->poc_msb_cycle_flag) {\n\t\tif ( (si->poc_msb_cycle_present_flag = gf_bs_read_int_log(bs, 1, \"poc_msb_cycle_present_flag\"))) {\n\t\t\tsi->poc_msb_cycle = gf_bs_read_int_log(bs, si->sps->poc_msb_cycle_len, \"poc_msb_cycle\");\n\t\t}\n\t}",
"\treturn 0;\n}",
"static s32 vvc_parse_slice(GF_BitStream *bs, VVCState *vvc, VVCSliceInfo *si)\n{\n//\tu32 CurrSubpicIdx = 0;",
"\tsi->picture_header_in_slice_header_flag = gf_bs_read_int_log(bs, 1, \"picture_header_in_slice_header_flag\");\n\tif (si->picture_header_in_slice_header_flag) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CODING, (\"[VVC] Picture header in slice header incomplete support, cannot guess slice type\\n\"));\n\t\tsi->slice_type = GF_VVC_SLICE_TYPE_UNKNOWN;\n\t\treturn vvc_parse_picture_header(bs, vvc, si);\n\t}\n\tif (!si->sps) return -1;\n\tsi->slice_type = GF_VVC_SLICE_TYPE_I;\n\tif (gf_bs_read_int_log(bs, 1, \"sps_subpic_info_present_flag\")) {\n\t\tgf_bs_read_int_log(bs, si->sps->subpicid_len, \"subpic_id\");\n\t\t//todo update CurrSubpicIdx\n\t}",
"\tif (si->pps->rect_slice_flag ) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[VVC] tiling parsing not supported - patch welcome\\n\"));\n\t\treturn 0;\n\t}\n\tgf_bs_read_int_log(bs, si->sps->sh_num_extra_bits, \"num_extra_bits\");\n\t/*\n\t\tif( !pps_rect_slice_flag && NumTilesInPic − sh_slice_address > 1 )\n\t\tsh_num_tiles_in_slice_minus1",
"\t */",
"\tif (si->inter_slice_allowed_flag )\n\t\tsi->slice_type = gf_bs_read_int_log(bs, 2, \"slice_type\");",
"\treturn 0;\n}",
"static void vvc_compute_poc(VVCSliceInfo *si)\n{\n\tu32 max_poc_lsb = 1 << (si->sps->log2_max_poc_lsb);",
"\tif (si->poc_msb_cycle_present_flag) {\n\t\tsi->poc_msb = si->poc_msb_cycle;\n\t} else {\n\t\tif ((si->poc_lsb < si->poc_lsb_prev) && (si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2))\n\t\t\tsi->poc_msb = si->poc_msb_prev + max_poc_lsb;\n\t\telse if ((si->poc_lsb > si->poc_lsb_prev) && (si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))\n\t\t\tsi->poc_msb = si->poc_msb_prev - max_poc_lsb;\n\t\telse\n\t\t\tsi->poc_msb = si->poc_msb_prev;\n\t}",
"\tsi->poc = si->poc_msb + si->poc_lsb;\n}",
"\nGF_EXPORT\ns32 gf_media_vvc_parse_nalu_bs(GF_BitStream *bs, VVCState *vvc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tBool is_slice = GF_FALSE;\n\ts32 ret = -1;\n\tBool poc_reset = GF_FALSE;\n\tVVCSliceInfo n_state;",
"\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tmemcpy(&n_state, &vvc->s_info, sizeof(VVCSliceInfo));\n\tif (!vvc_parse_nal_header(bs, nal_unit_type, temporal_id, layer_id)) return -1;",
"\tn_state.nal_unit_type = *nal_unit_type;",
"\tswitch (n_state.nal_unit_type) {\n\tcase GF_VVC_NALU_ACCESS_UNIT:\n\tcase GF_VVC_NALU_END_OF_SEQ:\n\tcase GF_VVC_NALU_END_OF_STREAM:\n\t\tret = 1;\n\t\tbreak;",
"\tcase GF_VVC_NALU_SLICE_IDR_W_RADL:\n\tcase GF_VVC_NALU_SLICE_IDR_N_LP:\n\t\tpoc_reset = GF_TRUE;\n\tcase GF_VVC_NALU_SLICE_TRAIL:\n\tcase GF_VVC_NALU_SLICE_STSA:\n\tcase GF_VVC_NALU_SLICE_RADL:\n\tcase GF_VVC_NALU_SLICE_RASL:\n\tcase GF_VVC_NALU_SLICE_CRA:\n\tcase GF_VVC_NALU_SLICE_GDR:\n\t\t/* slice - read the info and compare.*/\n\t\tret = vvc_parse_slice(bs, vvc, &n_state);\n\t\tif (ret < 0) return ret;",
"\t\tret = 0;\n\t\tif (n_state.compute_poc_defer || n_state.picture_header_in_slice_header_flag) {\n\t\t\tis_slice = GF_TRUE;\n\t\t\tn_state.compute_poc_defer = 0;\n\t\t\tif (poc_reset) {\n\t\t\t\tn_state.poc_lsb_prev = 0;\n\t\t\t\tn_state.poc_msb_prev = 0;\n\t\t\t}",
"\t\t\tvvc_compute_poc(&n_state);\n\t\t\tif (vvc->s_info.poc != n_state.poc) {\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!(*layer_id) || (n_state.prev_layer_id_plus1 && ((*layer_id) <= n_state.prev_layer_id_plus1 - 1))) {\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;",
"\tcase GF_VVC_NALU_PIC_HEADER:\n\t\tif (vvc_parse_picture_header(bs, vvc, &n_state)<0) {\n\t\t\tret = -1;\n\t\t\tbreak;\n\t\t}\n\t\tis_slice = GF_TRUE;",
"\t\t/*POC reset for IDR frames, NOT for CRA*/\n\t\tif (n_state.irap_or_gdr_pic && !n_state.gdr_pic) {\n\t\t\tn_state.poc_lsb_prev = 0;\n\t\t\tn_state.poc_msb_prev = 0;\n\t\t\tvvc_compute_poc(&n_state);\n\t\t} else {\n\t\t\t//we cannot compute poc until we know the first picture unit type, since IDR will reset poc count\n\t\t\t//and irap_or_gdr_pic=0 does not prevent IDR from following\n\t\t\tn_state.compute_poc_defer = 1;\n\t\t}",
"\t\tif (!(*layer_id) || (n_state.prev_layer_id_plus1 && ((*layer_id) <= n_state.prev_layer_id_plus1 - 1))) {\n\t\t\tret = 1;\n\t\t}\n\t\tbreak;\n\tcase GF_VVC_NALU_SEQ_PARAM:\n\t\tvvc->last_parsed_sps_id = gf_media_vvc_read_sps_bs_internal(bs, vvc, *layer_id, NULL);\n\t\tret = (vvc->last_parsed_sps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tcase GF_VVC_NALU_PIC_PARAM:\n\t\tvvc->last_parsed_pps_id = gf_media_vvc_read_pps_bs_internal(bs, vvc);\n\t\tret = (vvc->last_parsed_pps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tcase GF_VVC_NALU_VID_PARAM:\n\t\tvvc->last_parsed_vps_id = gf_media_vvc_read_vps_bs_internal(bs, vvc, GF_FALSE);\n\t\tret = (vvc->last_parsed_vps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tcase GF_VVC_NALU_DEC_PARAM:\n\t\tret = 0;\n\t\tbreak;\n\tcase GF_VVC_NALU_APS_PREFIX:\n\t\t//we use the mix aps type + aps id (first 8 bits) as unique identifier\n\t\tvvc->last_parsed_aps_id = gf_bs_read_int_log(bs, 8, \"aps_id\");\n\t\tret = 0;\n\t\tbreak;\n\tdefault:\n\t\tret = 0;\n\t\tbreak;\n\t}",
"\t/* save _prev values */\n\tif ((ret>0) && vvc->s_info.sps) {\n//\t\tn_state.frame_num_offset_prev = vvc->s_info.frame_num_offset;\n//\t\tn_state.frame_num_prev = vvc->s_info.frame_num;",
"\t\tn_state.poc_lsb_prev = vvc->s_info.poc_lsb;\n\t\tn_state.poc_msb_prev = vvc->s_info.poc_msb;\n\t\tif (is_slice)\n\t\t\tn_state.prev_layer_id_plus1 = *layer_id + 1;\n\t}",
"\tmemcpy(&vvc->s_info, &n_state, sizeof(VVCSliceInfo));",
"\treturn ret;\n}",
"GF_EXPORT\ns32 gf_media_vvc_parse_nalu(u8 *data, u32 size, VVCState *vvc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tGF_BitStream *bs = NULL;\n\ts32 ret;",
"\tif (!vvc) {\n\t\tif (nal_unit_type) (*nal_unit_type) = data[1] >> 3;\n\t\tif (layer_id) (*layer_id) = data[0] & 0x3f;\n\t\tif (temporal_id) (*temporal_id) = (data[1] & 0x7);\n\t\treturn -1;\n\t}\n\tbs = gf_bs_new(data, size, GF_BITSTREAM_READ);\n\tif (!bs) return -1;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tret = gf_media_vvc_parse_nalu_bs(bs, vvc, nal_unit_type, temporal_id, layer_id);\n\tgf_bs_del(bs);\n\treturn ret;\n}",
"Bool gf_media_vvc_slice_is_ref(VVCState *vvc)\n{\n\tif (!vvc->s_info.irap_or_gdr_pic) {\n\t\treturn GF_FALSE;\n\t}\n\tif (vvc->s_info.gdr_pic) {\n\t\tif (vvc->s_info.recovery_point_valid) {\n\t\t\tvvc->s_info.recovery_point_valid = 0;\n\t\t\treturn GF_TRUE;\n\t\t}\n\t\treturn GF_FALSE;\n\t}\n\treturn GF_TRUE;\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [5789], "buggy_code_start_loc": [4693], "filenames": ["src/media_tools/av_parsers.c"], "fixing_code_end_loc": [5792], "fixing_code_start_loc": [4693], "message": "A buffer overflow vulnerability exists in Gpac through 1.0.1 via a malformed MP4 file in the svc_parse_slice function in av_parsers.c, which allows attackers to cause a denial of service, even code execution and escalation of privileges.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gpac:gpac:*:*:*:*:*:*:*:*", "matchCriteriaId": "72EEF01B-F945-4AEF-B5C2-6F84A51311C9", "versionEndExcluding": null, "versionEndIncluding": "1.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A buffer overflow vulnerability exists in Gpac through 1.0.1 via a malformed MP4 file in the svc_parse_slice function in av_parsers.c, which allows attackers to cause a denial of service, even code execution and escalation of privileges."}, {"lang": "es", "value": "es presentado una vulnerabilidad de desbordamiento de b\u00fafer en Gpac versiones hasta 1.0.1 por medio de un archivo MP4 malformado en la funci\u00f3n svc_parse_slice en el archivo av_parsers.c, que permite a atacantes causar una denegaci\u00f3n de servicio, incluso ejecuci\u00f3n de c\u00f3digo y escalada de privilegios"}], "evaluatorComment": null, "id": "CVE-2021-40568", "lastModified": "2023-05-27T04:15:16.660", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-01-13T18:15:07.977", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/commit/f1ae01d745200a258cdf62622f71754c37cb6c30"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/issues/1900"}, {"source": "cve@mitre.org", "tags": null, "url": "https://www.debian.org/security/2023/dsa-5411"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-120"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gpac/gpac/commit/f1ae01d745200a258cdf62622f71754c37cb6c30"}, "type": "CWE-120"}
| 246
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n *\t\t\tGPAC - Multimedia Framework C SDK\n *\n *\t\t\tAuthors: Jean Le Feuvre, Romain Bouqueau, Cyril Concolato\n *\t\t\tCopyright (c) Telecom ParisTech 2000-2021\n *\t\t\t\t\tAll rights reserved\n *\n * This file is part of GPAC / Media Tools sub-project\n *\n * GPAC is free software; you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2, or (at your option)\n * any later version.\n *\n * GPAC is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; see the file COPYING. If not, write to\n * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.\n *\n */",
"#include <gpac/internal/media_dev.h>\n#include <gpac/constants.h>\n#include <gpac/mpeg4_odf.h>\n#include <gpac/maths.h>\n#include <gpac/avparse.h>",
"#ifndef GPAC_DISABLE_OGG\n#include <gpac/internal/ogg.h>\n#endif",
"//uncomment/define globally to remove all bitstream parsing logging from code (this will break inspect mode ananlyze=bs)\n//#define GPAC_DISABLE_AVPARSE_LOGS",
"#ifndef GPAC_DISABLE_AVPARSE_LOGS\nvoid gf_bs_log_idx(GF_BitStream *bs, u32 nBits, const char *fname, s64 val, s32 idx1, s32 idx2, s32 idx3);",
"#define gf_bs_log(_bs, _nBits, _fname, _val) gf_bs_log_idx(_bs, _nBits, _fname, _val, -1, -1, -1)",
"u32 gf_bs_read_int_log_idx3(GF_BitStream *bs, u32 nBits, const char *fname, s32 idx1, s32 idx2, s32 idx3)\n{\n\tu32 val = gf_bs_read_int(bs, nBits);\n\tgf_bs_log_idx(bs, nBits, fname, val, idx1, idx2, idx3);\n\treturn val;\n}",
"#define gf_bs_read_int_log(_bs, _nBits, _fname) gf_bs_read_int_log_idx3(_bs, _nBits, _fname, -1, -1, -1)\n#define gf_bs_read_int_log_idx(_bs, _nBits, _fname, _idx) gf_bs_read_int_log_idx3(_bs, _nBits, _fname, _idx, -1, -1)\n#define gf_bs_read_int_log_idx2(_bs, _nBits, _fname, _idx1, _idx2) gf_bs_read_int_log_idx3(_bs, _nBits, _fname, (s32) _idx1, (s32) _idx2, -1)",
"\n#else",
"#define gf_bs_log(_bs, _nBits, _fname, _val)\n#define gf_bs_log_idx(_bs, _nBits, _fname, _val, _idx1, _idx2, _idx3)",
"#define gf_bs_read_int_log(_bs, _nbb, _f) gf_bs_read_int(_bs, _nbb)\n#define gf_bs_read_int_log_idx(_bs, _nbb, _f, _idx) gf_bs_read_int(_bs, _nbb)\n#define gf_bs_read_int_log_idx2(_bs, _nbb, _f, _idx1, _idx2) gf_bs_read_int(_bs, _nbb)\n#define gf_bs_read_int_log_idx3(_bs, _nbb, _f, _idx1, _idx2, _idx3) gf_bs_read_int(_bs, _nbb)",
"#endif",
"",
"\nstatic const struct {\n\tu32 w, h;\n} std_par[] =\n{\n\t{ 4, 3}, {3, 2}, {16, 9}, {5, 3}, {5, 4}, {8, 5}, {2, 1}, {1, 1},\n\t{0, 0},\n};",
"GF_EXPORT\nvoid gf_media_reduce_aspect_ratio(u32 *width, u32 *height)\n{\n\tu32 i = 0;\n\tu32 w = *width;\n\tu32 h = *height;\n\twhile (std_par[i].w) {\n\t\tif (std_par[i].w * h == std_par[i].h * w) {\n\t\t\t*width = std_par[i].w;\n\t\t\t*height = std_par[i].h;\n\t\t\treturn;\n\t\t}\n\t\ti++;\n\t}\n\t//not standard one, reduce by power of 2\n\ti = 2;\n\twhile (1) {\n\t\tif (w <= i) return;\n\t\tif (h <= i) return;",
"\t\tif (w % i) return;\n\t\tif (h % i) return;\n\t\t*width = w / i;\n\t\t*height = h / i;\n\t\ti *= 2;\n\t}\n}",
"GF_EXPORT\nvoid gf_media_get_reduced_frame_rate(u32 *timescale, u32 *sample_dur)\n{\n\tu32 res;\n\tif (!*sample_dur) return;\n\tres = *timescale / *sample_dur;\n\tif (res * (*sample_dur) == *timescale) {\n\t\t*timescale = res;\n\t\t*sample_dur = 1;\n\t}\n\telse if ((double)(*timescale * 1001 - (res + 1) * *sample_dur * 1000) / ((res + 1) * *sample_dur * 1000) < 0.001) {\n\t\t*timescale = (res + 1) * 1000;\n\t\t*sample_dur = 1001;\n\t}\n}",
"struct __m4v_profile\n{\n\tu32 value;\n\tconst char *name;\n} M4VProfiles[] = {\n\t{0x00, \"Reserved (0x00) Profile\"},\n\t{0x01, \"Simple Profile @ Level 1\"},\n\t{0x02, \"Simple Profile @ Level 2\"},\n\t{0x03, \"Simple Profile @ Level 3\"},\n\t{0x08, \"Simple Profile @ Level 0\"},\n\t{0x10, \"Simple Scalable Profile @ Level 0\"},\n\t{0x11, \"Simple Scalable Profile @ Level 1\"},\n\t{0x12, \"Simple Scalable Profile @ Level 2\"},\n\t{0x21, \"Core Profile @ Level 1\"},\n\t{0x22, \"Core Profile @ Level 2\"},\n\t{0x32, \"Main Profile @ Level 2\"},\n\t{0x33, \"Main Profile @ Level 3\"},\n\t{0x34, \"Main Profile @ Level 4\"},\n\t{0x42, \"N-bit Profile @ Level 2\"},\n\t{0x51, \"Scalable Texture Profile @ Level 1\"},\n\t{0x61, \"Simple Face Animation Profile @ Level 1\"},\n\t{0x62, \"Simple Face Animation Profile @ Level 2\"},\n\t{0x63, \"Simple FBA Profile @ Level 1\"},\n\t{0x64, \"Simple FBA Profile @ Level 2\"},\n\t{0x71, \"Basic Animated Texture Profile @ Level 1\"},\n\t{0x72, \"Basic Animated Texture Profile @ Level 2\"},\n\t{0x7F, \"AVC/H264 Profile\"},\n\t{0x81, \"Hybrid Profile @ Level 1\"},\n\t{0x82, \"Hybrid Profile @ Level 2\"},\n\t{0x91, \"Advanced Real Time Simple Profile @ Level 1\"},\n\t{0x92, \"Advanced Real Time Simple Profile @ Level 2\"},\n\t{0x93, \"Advanced Real Time Simple Profile @ Level 3\"},\n\t{0x94, \"Advanced Real Time Simple Profile @ Level 4\"},\n\t{0xA1, \"Core Scalable Profile @ Level1\"},\n\t{0xA2, \"Core Scalable Profile @ Level2\"},\n\t{0xA3, \"Core Scalable Profile @ Level3\"},\n\t{0xB1, \"Advanced Coding Efficiency Profile @ Level 1\"},\n\t{0xB2, \"Advanced Coding Efficiency Profile @ Level 2\"},\n\t{0xB3, \"Advanced Coding Efficiency Profile @ Level 3\"},\n\t{0xB4, \"Advanced Coding Efficiency Profile @ Level 4\"},\n\t{0xC1, \"Advanced Core Profile @ Level 1\"},\n\t{0xC2, \"Advanced Core Profile @ Level 2\"},\n\t{0xD1, \"Advanced Scalable Texture @ Level1\"},\n\t{0xD2, \"Advanced Scalable Texture @ Level2\"},\n\t{0xE1, \"Simple Studio Profile @ Level 1\"},\n\t{0xE2, \"Simple Studio Profile @ Level 2\"},\n\t{0xE3, \"Simple Studio Profile @ Level 3\"},\n\t{0xE4, \"Simple Studio Profile @ Level 4\"},\n\t{0xE5, \"Core Studio Profile @ Level 1\"},\n\t{0xE6, \"Core Studio Profile @ Level 2\"},\n\t{0xE7, \"Core Studio Profile @ Level 3\"},\n\t{0xE8, \"Core Studio Profile @ Level 4\"},\n\t{0xF0, \"Advanced Simple Profile @ Level 0\"},\n\t{0xF1, \"Advanced Simple Profile @ Level 1\"},\n\t{0xF2, \"Advanced Simple Profile @ Level 2\"},\n\t{0xF3, \"Advanced Simple Profile @ Level 3\"},\n\t{0xF4, \"Advanced Simple Profile @ Level 4\"},\n\t{0xF5, \"Advanced Simple Profile @ Level 5\"},\n\t{0xF7, \"Advanced Simple Profile @ Level 3b\"},\n\t{0xF8, \"Fine Granularity Scalable Profile @ Level 0\"},\n\t{0xF9, \"Fine Granularity Scalable Profile @ Level 1\"},\n\t{0xFA, \"Fine Granularity Scalable Profile @ Level 2\"},\n\t{0xFB, \"Fine Granularity Scalable Profile @ Level 3\"},\n\t{0xFC, \"Fine Granularity Scalable Profile @ Level 4\"},\n\t{0xFD, \"Fine Granularity Scalable Profile @ Level 5\"},\n\t{0xFE, \"Not part of MPEG-4 Visual profiles\"},\n\t{0xFF, \"No visual capability required\"}\n};",
"GF_EXPORT\nconst char *gf_m4v_get_profile_name(u8 video_pl)\n{\n\tu32 i, count = GF_ARRAY_LENGTH(M4VProfiles);\n\tfor (i=0; i<count; i++) {\n\t\tif ((u32)video_pl == M4VProfiles[i].value)\n\t\t\treturn M4VProfiles[i].name;\n\t}\n\treturn \"ISO Reserved Profile\";\n}",
"\n#ifndef GPAC_DISABLE_AV_PARSERS",
"#define MPEG12_START_CODE_PREFIX\t\t0x000001\n#define MPEG12_PICTURE_START_CODE\t\t0x00000100\n#define MPEG12_SLICE_MIN_START\t\t\t0x00000101\n#define MPEG12_SLICE_MAX_START\t\t\t0x000001af\n#define MPEG12_USER_DATA_START_CODE\t\t0x000001b2\n#define MPEG12_SEQUENCE_START_CODE\t\t0x000001b3\n#define MPEG12_SEQUENCE_ERR_START_CODE\t0x000001b4\n#define MPEG12_EXT_START_CODE\t\t\t0x000001b5\n#define MPEG12_SEQUENCE_END_START_CODE\t0x000001b7\n#define MPEG12_GOP_START_CODE\t\t\t0x000001b8",
"s32 gf_mv12_next_start_code(unsigned char *pbuffer, u32 buflen, u32 *optr, u32 *scode)\n{\n\tu32 value;\n\tu32 offset;",
"\tif (buflen < 4) return -1;\n\tfor (offset = 0; offset < buflen - 3; offset++, pbuffer++) {\n#ifdef GPAC_BIG_ENDIAN\n\t\tvalue = *(u32 *)pbuffer >> 8;\n#else\n\t\tvalue = (pbuffer[0] << 16) | (pbuffer[1] << 8) | (pbuffer[2] << 0);\n#endif",
"\t\tif (value == MPEG12_START_CODE_PREFIX) {\n\t\t\t*optr = offset;\n\t\t\t*scode = (value << 8) | pbuffer[3];\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn -1;\n}",
"s32 gf_mv12_next_slice_start(unsigned char *pbuffer, u32 startoffset, u32 buflen, u32 *slice_offset)\n{\n\tu32 slicestart, code;\n\twhile (gf_mv12_next_start_code(pbuffer + startoffset, buflen - startoffset, &slicestart, &code) >= 0) {\n\t\tif ((code >= MPEG12_SLICE_MIN_START) && (code <= MPEG12_SLICE_MAX_START)) {\n\t\t\t*slice_offset = slicestart + startoffset;\n\t\t\treturn 0;\n\t\t}\n\t\tstartoffset += slicestart + 4;\n\t}\n\treturn -1;\n}",
"\n/*\n\tMPEG-4 video (14496-2)\n*/",
"struct __tag_m4v_parser\n{\n\tGF_BitStream *bs;\n\tBool mpeg12, step_mode;\n\tu32 current_object_type;\n\tu32 force_next_obj_type;\n\tu64 current_object_start;\n\tu32 tc_dec, prev_tc_dec, tc_disp, prev_tc_disp;\n};",
"GF_EXPORT\nGF_M4VParser *gf_m4v_parser_new(u8 *data, u64 data_size, Bool mpeg12video)\n{\n\tGF_M4VParser *tmp;\n\tif (!data || !data_size) return NULL;\n\tGF_SAFEALLOC(tmp, GF_M4VParser);\n\tif (!tmp) return NULL;\n\ttmp->bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);\n\ttmp->mpeg12 = mpeg12video;\n\treturn tmp;\n}",
"GF_M4VParser *gf_m4v_parser_bs_new(GF_BitStream *bs, Bool mpeg12video)\n{\n\tGF_M4VParser *tmp;\n\tGF_SAFEALLOC(tmp, GF_M4VParser);\n\tif (!tmp) return NULL;\n\ttmp->bs = bs;\n\ttmp->mpeg12 = mpeg12video;\n\treturn tmp;\n}",
"GF_EXPORT\nvoid gf_m4v_parser_del(GF_M4VParser *m4v)\n{\n\tgf_bs_del(m4v->bs);\n\tgf_free(m4v);\n}",
"GF_EXPORT\nvoid gf_m4v_parser_del_no_bs(GF_M4VParser *m4v)\n{\n\tgf_free(m4v);\n}",
"GF_EXPORT\nvoid gf_m4v_parser_set_inspect(GF_M4VParser *m4v)\n{\n\tif (m4v) m4v->step_mode = 1;\n}\nGF_EXPORT\nu32 gf_m4v_parser_get_obj_type(GF_M4VParser *m4v)\n{\n\tif (m4v) return m4v->current_object_type;\n\treturn 0;\n}",
"#define M4V_CACHE_SIZE\t\t4096\ns32 M4V_LoadObject(GF_M4VParser *m4v)\n{\n\tu32 v, bpos, found;\n\tchar m4v_cache[M4V_CACHE_SIZE];\n\tu64 end, cache_start, load_size;\n\tif (!m4v) return 0;\n\tif (m4v->force_next_obj_type) {\n\t\tm4v->current_object_type = m4v->force_next_obj_type - 1;\n\t\tm4v->force_next_obj_type = 0;\n\t\treturn (s32)m4v->current_object_type;\n\t}",
"\tbpos = 0;\n\tfound = 0;\n\tload_size = 0;\n\tend = 0;\n\tcache_start = 0;\n\tv = 0xffffffff;\n\twhile (!end) {\n\t\t/*refill cache*/\n\t\tif (bpos == (u32)load_size) {\n\t\t\tif (!gf_bs_available(m4v->bs)) break;\n\t\t\tload_size = gf_bs_available(m4v->bs);\n\t\t\tif (load_size > M4V_CACHE_SIZE) load_size = M4V_CACHE_SIZE;\n\t\t\tbpos = 0;\n\t\t\tcache_start = gf_bs_get_position(m4v->bs);\n\t\t\tgf_bs_read_data(m4v->bs, m4v_cache, (u32)load_size);\n\t\t}\n\t\tv = ((v << 8) & 0xFFFFFF00) | ((u8)m4v_cache[bpos]);\n\t\tbpos++;\n\t\tif ((v & 0xFFFFFF00) == 0x00000100) {\n\t\t\tend = cache_start + bpos - 4;\n\t\t\tfound = 1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!found) return -1;\n\tm4v->current_object_start = end;\n\tgf_bs_seek(m4v->bs, end + 3);\n\tm4v->current_object_type = gf_bs_read_u8(m4v->bs);\n\treturn (s32)m4v->current_object_type;\n}",
"\nGF_EXPORT\nvoid gf_m4v_rewrite_pl(u8 **o_data, u32 *o_dataLen, u8 PL)\n{\n\tu32 pos = 0;\n\tunsigned char *data = (unsigned char *)*o_data;\n\tu32 dataLen = *o_dataLen;",
"\twhile (pos + 4 < dataLen) {\n\t\tif (!data[pos] && !data[pos + 1] && (data[pos + 2] == 0x01) && (data[pos + 3] == M4V_VOS_START_CODE)) {\n\t\t\tdata[pos + 4] = PL;\n\t\t\treturn;\n\t\t}\n\t\tpos++;\n\t}\n\t/*emulate VOS at beggining*/\n\t(*o_data) = (char *)gf_malloc(sizeof(char)*(dataLen + 5));\n\t(*o_data)[0] = 0;\n\t(*o_data)[1] = 0;\n\t(*o_data)[2] = 1;\n\t(*o_data)[3] = (char)M4V_VOS_START_CODE;\n\t(*o_data)[4] = PL;\n\tmemcpy((*o_data + 5), data, sizeof(char)*dataLen);\n\tgf_free(data);\n\t(*o_dataLen) = dataLen + 5;\n}",
"static GF_Err M4V_Reset(GF_M4VParser *m4v, u64 start)\n{\n\tgf_bs_seek(m4v->bs, start);",
"\tassert(start < (u64)1<<31);\n\tm4v->current_object_start = (u32)start;\n\tm4v->current_object_type = 0;\n\treturn GF_OK;\n}",
"void gf_m4v_parser_reset(GF_M4VParser *m4v, u8 sc_type)\n{\n\tm4v->current_object_start = 0;\n\tm4v->current_object_type = 0;\n\tm4v->force_next_obj_type = sc_type;\n}\nstatic GF_Err gf_m4v_parse_config_mpeg12(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)\n{\n\tunsigned char p[4];\n\tu32 ext_type;\n\ts32 o_type;\n\tu8 go, par;",
"\tif (!m4v || !dsi) return GF_BAD_PARAM;",
"\tmemset(dsi, 0, sizeof(GF_M4VDecSpecInfo));\n\tdsi->VideoPL = 0;",
"\tgo = 1;\n\twhile (go) {\n\t\to_type = M4V_LoadObject(m4v);\n\t\tswitch (o_type) {\n\t\tcase M2V_SEQ_START_CODE:\n\t\t\tdsi->RAP_stream = 1;\n\t\t\tgf_bs_read_data(m4v->bs, (char *)p, 4);\n\t\t\tdsi->width = (p[0] << 4) | ((p[1] >> 4) & 0xf);\n\t\t\tdsi->height = ((p[1] & 0xf) << 8) | p[2];",
"\t\t\tdsi->VideoPL = GF_CODECID_MPEG1;\n\t\t\tpar = (p[3] >> 4) & 0xf;\n\t\t\tswitch (par) {\n\t\t\tcase 2:\n\t\t\t\tdsi->par_num = dsi->height / 3;\n\t\t\t\tdsi->par_den = dsi->width / 4;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tdsi->par_num = dsi->height / 9;\n\t\t\t\tdsi->par_den = dsi->width / 16;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tdsi->par_num = dsi->height / 2;\n\t\t\t\tdsi->par_den = dsi->width / 21;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tdsi->par_den = dsi->par_num = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tswitch (p[3] & 0xf) {\n\t\t\tcase 0:\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tdsi->fps = 24000.0 / 1001.0;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tdsi->fps = 24.0;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tdsi->fps = 25.0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tdsi->fps = 30000.0 / 1001.0;\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tdsi->fps = 30.0;\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\tdsi->fps = 50.0;\n\t\t\t\tbreak;\n\t\t\tcase 7:\n\t\t\t\tdsi->fps = ((60.0*1000.0) / 1001.0);\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\tdsi->fps = 60.0;\n\t\t\t\tbreak;\n\t\t\tcase 9:\n\t\t\t\tdsi->fps = 1;\n\t\t\t\tbreak;\n\t\t\tcase 10:\n\t\t\t\tdsi->fps = 5;\n\t\t\t\tbreak;\n\t\t\tcase 11:\n\t\t\t\tdsi->fps = 10;\n\t\t\t\tbreak;\n\t\t\tcase 12:\n\t\t\t\tdsi->fps = 12;\n\t\t\t\tbreak;\n\t\t\tcase 13:\n\t\t\t\tdsi->fps = 15;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase M2V_EXT_START_CODE:\n\t\t\tgf_bs_read_data(m4v->bs, (char *)p, 4);\n\t\t\text_type = ((p[0] >> 4) & 0xf);\n\t\t\tif (ext_type == 1) {\n\t\t\t\tdsi->VideoPL = 0x65;\n\t\t\t\tdsi->height = ((p[1] & 0x1) << 13) | ((p[2] & 0x80) << 5) | (dsi->height & 0x0fff);\n\t\t\t\tdsi->width = (((p[2] >> 5) & 0x3) << 12) | (dsi->width & 0x0fff);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase M2V_PIC_START_CODE:\n\t\t\tif (dsi->width) go = 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t\t/*EOS*/\n\t\tcase -1:\n\t\t\tgo = 0;\n\t\t\tm4v->current_object_start = gf_bs_get_position(m4v->bs);\n\t\t\tbreak;\n\t\t}\n\t}\n\tM4V_Reset(m4v, 0);\n\treturn GF_OK;\n}",
"\nstatic const struct {\n\tu32 w, h;\n} m4v_sar[6] = { { 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 }, { 40, 33 } };",
"static u8 m4v_get_sar_idx(u32 w, u32 h)\n{\n\tu32 i;\n\tfor (i = 0; i < 6; i++) {\n\t\tif ((m4v_sar[i].w == w) && (m4v_sar[i].h == h)) return i;\n\t}\n\treturn 0xF;\n}",
"static void gf_m4v_parse_vol(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)\n{\n\tu8 verid, par;\n\ts32 clock_rate;\n\tu8 vpl = dsi->VideoPL;",
"\tmemset(dsi, 0, sizeof(GF_M4VDecSpecInfo));\n\tdsi->VideoPL = vpl;",
"\tverid = 0;\n\tdsi->RAP_stream = gf_bs_read_int(m4v->bs, 1);\n\tdsi->objectType = gf_bs_read_int(m4v->bs, 8);\n\tif (gf_bs_read_int(m4v->bs, 1)) {\n\t\tverid = gf_bs_read_int(m4v->bs, 4);\n\t\tgf_bs_read_int(m4v->bs, 3);\n\t}\n\tpar = gf_bs_read_int(m4v->bs, 4);\n\tif (par == 0xF) {\n\t\tdsi->par_num = gf_bs_read_int(m4v->bs, 8);\n\t\tdsi->par_den = gf_bs_read_int(m4v->bs, 8);\n\t} else if (par<6) {\n\t\tdsi->par_num = m4v_sar[par].w;\n\t\tdsi->par_den = m4v_sar[par].h;\n\t}\n\tif (gf_bs_read_int(m4v->bs, 1)) {\n\t\tgf_bs_read_int(m4v->bs, 3);\n\t\tif (gf_bs_read_int(m4v->bs, 1)) gf_bs_read_int(m4v->bs, 79);\n\t}\n\tdsi->has_shape = gf_bs_read_int(m4v->bs, 2);\n\tif (dsi->has_shape && (verid!=1) ) gf_bs_read_int(m4v->bs, 4);\n\tgf_bs_read_int(m4v->bs, 1);\n\t/*clock rate*/\n\tdsi->clock_rate = gf_bs_read_int(m4v->bs, 16);\n\t/*marker*/\n\tgf_bs_read_int(m4v->bs, 1);",
"\tclock_rate = dsi->clock_rate-1;\n\tif (clock_rate >= 65536) clock_rate = 65535;\n\tif (clock_rate > 0) {\n\t\tfor (dsi->NumBitsTimeIncrement = 1; dsi->NumBitsTimeIncrement < 16; dsi->NumBitsTimeIncrement++)\t{\n\t\t\tif (clock_rate == 1) break;\n\t\t\tclock_rate = (clock_rate >> 1);\n\t\t}\n\t} else {\n\t\t/*fix from vivien for divX*/\n\t\tdsi->NumBitsTimeIncrement = 1;\n\t}\n\t/*fixed FPS stream*/\n\tdsi->time_increment = 0;\n\tif (gf_bs_read_int(m4v->bs, 1)) {\n\t\tdsi->time_increment = gf_bs_read_int(m4v->bs, dsi->NumBitsTimeIncrement);\n\t}\n\tif (!dsi->has_shape) {\n\t\tgf_bs_read_int(m4v->bs, 1);\n\t\tdsi->width = gf_bs_read_int(m4v->bs, 13);\n\t\tgf_bs_read_int(m4v->bs, 1);\n\t\tdsi->height = gf_bs_read_int(m4v->bs, 13);\n\t} else {\n\t\tdsi->width = dsi->height = 0;\n\t}\n\tgf_bs_align(m4v->bs);\n}",
"static GF_Err gf_m4v_parse_config_mpeg4(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)\n{\n\ts32 o_type;\n\tu8 go;",
"\tif (!m4v || !dsi) return GF_BAD_PARAM;",
"\tmemset(dsi, 0, sizeof(GF_M4VDecSpecInfo));",
"\tgo = 1;\n\twhile (go) {\n\t\to_type = M4V_LoadObject(m4v);\n\t\tswitch (o_type) {\n\t\t\t/*vosh*/\n\t\tcase M4V_VOS_START_CODE:\n\t\t\tdsi->VideoPL = (u8)gf_bs_read_u8(m4v->bs);\n\t\t\tbreak;",
"\t\tcase M4V_VOL_START_CODE:\n\t\t\tgf_m4v_parse_vol(m4v, dsi);\n\t\t\t/*shape will be done later*/\n\t\t\tgf_bs_align(m4v->bs);\n\t\t\tbreak;",
"\t\tcase M4V_VOP_START_CODE:\n\t\tcase M4V_GOV_START_CODE:\n\t\t\tgo = 0;\n\t\t\tbreak;\n\t\t\t/*EOS*/\n\t\tcase -1:\n\t\t\tm4v->current_object_start = gf_bs_get_position(m4v->bs);\n\t\t\treturn GF_EOS;\n\t\t\t/*don't interest us*/\n\t\tcase M4V_UDTA_START_CODE:\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4v_parse_config(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)\n{\n\tif (m4v->mpeg12) {\n\t\treturn gf_m4v_parse_config_mpeg12(m4v, dsi);\n\t}\n\telse {\n\t\treturn gf_m4v_parse_config_mpeg4(m4v, dsi);\n\t}\n}",
"static GF_Err gf_m4v_parse_frame_mpeg12(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)\n{\n\tu8 go, hasVOP, firstObj, val;\n\ts32 o_type;",
"\tif (!m4v || !size || !start || !frame_type) return GF_BAD_PARAM;",
"\t*size = 0;\n\tfirstObj = 1;\n\thasVOP = 0;\n\t*is_coded = GF_FALSE;\n\t*frame_type = 0;",
"\tif (!m4v->step_mode)\n\t\tM4V_Reset(m4v, m4v->current_object_start);",
"\tm4v->current_object_type = (u32)-1;\n\tgo = 1;\n\twhile (go) {\n\t\to_type = M4V_LoadObject(m4v);\n\t\tswitch (o_type) {\n\t\tcase M2V_PIC_START_CODE:\n\t\t\t/*done*/\n\t\t\tif (hasVOP) {\n\t\t\t\tgo = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\thasVOP = 1;\n\t\t\t*is_coded = 1;",
"\t\t\t/*val = */gf_bs_read_u8(m4v->bs);\n\t\t\tval = gf_bs_read_u8(m4v->bs);\n\t\t\t*frame_type = ((val >> 3) & 0x7) - 1;\n\t\t\tbreak;\n\t\tcase M2V_GOP_START_CODE:\n\t\t\tif (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\tif (hasVOP) go = 0;\n\t\t\tbreak;",
"\t\tcase M2V_SEQ_START_CODE:\n\t\t\tif (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\tif (hasVOP) {\n\t\t\t\tgo = 0;\n\t\t\t\tbreak;\n\t\t\t}",
"\t\t\t/**/\n\t\t\tbreak;",
"\t\tdefault:\n\t\t\tbreak;",
"\t\tcase -1:\n\t\t\t*size = gf_bs_get_position(m4v->bs) - *start;\n\t\t\treturn GF_EOS;\n\t\t}\n\t\tif (m4v->step_mode)\n\t\t\treturn GF_OK;\n\t}\n\t*size = m4v->current_object_start - *start;\n\treturn GF_OK;\n}",
"static GF_Err gf_m4v_parse_frame_mpeg4(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)\n{\n\tu8 go, hasVOP, firstObj, secs;\n\ts32 o_type;\n\tu32 vop_inc = 0;",
"\tif (!m4v || !size || !start || !frame_type) return GF_BAD_PARAM;",
"\t*size = 0;\n\tfirstObj = 1;\n\thasVOP = 0;\n\t*is_coded = 0;\n\tm4v->current_object_type = (u32)-1;\n\t*frame_type = 0;\n\t*start = 0;",
"\tif (!m4v->step_mode)\n\t\tM4V_Reset(m4v, m4v->current_object_start);",
"\tgo = 1;\n\twhile (go) {\n\t\to_type = M4V_LoadObject(m4v);\n\t\tswitch (o_type) {\n\t\tcase M4V_VOP_START_CODE:\n\t\t\t/*done*/\n\t\t\tif (hasVOP) {\n\t\t\t\tgo = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\thasVOP = 1;",
"\t\t\t/*coding type*/\n\t\t\t*frame_type = gf_bs_read_int(m4v->bs, 2);\n\t\t\t/*modulo time base*/\n\t\t\tsecs = 0;\n\t\t\twhile (gf_bs_read_int(m4v->bs, 1) != 0)\n\t\t\t\tsecs++;\n\t\t\t/*no support for B frames in parsing*/\n\t\t\tsecs += (dsi->enh_layer || *frame_type!=2) ? m4v->tc_dec : m4v->tc_disp;\n\t\t\t/*marker*/\n\t\t\tgf_bs_read_int(m4v->bs, 1);\n\t\t\t/*vop_time_inc*/\n\t\t\tif (dsi->NumBitsTimeIncrement)\n\t\t\t\tvop_inc = gf_bs_read_int(m4v->bs, dsi->NumBitsTimeIncrement);",
"\t\t\tm4v->prev_tc_dec = m4v->tc_dec;\n\t\t\tm4v->prev_tc_disp = m4v->tc_disp;\n\t\t\tif (dsi->enh_layer || *frame_type!=2) {\n\t\t\t\tm4v->tc_disp = m4v->tc_dec;\n\t\t\t\tm4v->tc_dec = secs;\n\t\t\t}\n\t\t\t*time_inc = secs * dsi->clock_rate + vop_inc;\n\t\t\t/*marker*/\n\t\t\tgf_bs_read_int(m4v->bs, 1);\n\t\t\t/*coded*/\n\t\t\t*is_coded = gf_bs_read_int(m4v->bs, 1);\n\t\t\tgf_bs_align(m4v->bs);\n\t\t\tbreak;\n\t\tcase M4V_GOV_START_CODE:\n\t\t\tif (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\tif (hasVOP) go = 0;\n\t\t\tbreak;",
"\t\tcase M4V_VOL_START_CODE:\n\t\t\tif (m4v->step_mode)\n\t\t\t\tgf_m4v_parse_vol(m4v, dsi);\n\t\tcase M4V_VOS_START_CODE:\n\t\t\tif (hasVOP) {\n\t\t\t\tgo = 0;\n\t\t\t}\n\t\t\telse if (firstObj) {\n\t\t\t\t*start = m4v->current_object_start;\n\t\t\t\tfirstObj = 0;\n\t\t\t}\n\t\t\tbreak;",
"\t\tcase M4V_VO_START_CODE:\n\t\tdefault:\n\t\t\tbreak;",
"\t\tcase -1:\n\t\t\t*size = gf_bs_get_position(m4v->bs) - *start;\n\t\t\treturn GF_EOS;\n\t\t}\n\t\tif (m4v->step_mode)\n\t\t\treturn GF_OK;\n\t}\n\tassert(m4v->current_object_start >= *start);\n\t*size = m4v->current_object_start - *start;\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4v_parse_frame(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)\n{\n\tif (m4v->mpeg12) {\n\t\treturn gf_m4v_parse_frame_mpeg12(m4v, dsi, frame_type, time_inc, size, start, is_coded);\n\t}\n\telse {\n\t\treturn gf_m4v_parse_frame_mpeg4(m4v, dsi, frame_type, time_inc, size, start, is_coded);\n\t}\n}",
"GF_Err gf_m4v_rewrite_par(u8 **o_data, u32 *o_dataLen, s32 par_n, s32 par_d)\n{\n\tu64 start, end, size;\n\tGF_BitStream *mod;\n\tGF_M4VParser *m4v;\n\tBool go = 1;",
"\tm4v = gf_m4v_parser_new(*o_data, *o_dataLen, 0);\n\tmod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);",
"\tstart = 0;\n\twhile (go) {\n\t\tu32 type = M4V_LoadObject(m4v);",
"\t\tend = gf_bs_get_position(m4v->bs) - 4;\n\t\tsize = end - start;\n\t\t/*store previous object*/\n\t\tif (size) {\n\t\t\tassert (size < (u64)1<<31);\n\t\t\tgf_bs_write_data(mod, *o_data + start, (u32)size);\n\t\t\tstart = end;\n\t\t}",
"\t\tswitch (type) {\n\t\tcase M4V_VOL_START_CODE:\n\t\t\tgf_bs_write_int(mod, 0, 8);\n\t\t\tgf_bs_write_int(mod, 0, 8);\n\t\t\tgf_bs_write_int(mod, 1, 8);\n\t\t\tgf_bs_write_int(mod, M4V_VOL_START_CODE, 8);\n\t\t\tgf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 1), 1);\n\t\t\tgf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 8), 8);\n\t\t\tstart = gf_bs_read_int(m4v->bs, 1);\n\t\t\tgf_bs_write_int(mod, (u32)start, 1);\n\t\t\tif (start) {\n\t\t\t\tgf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 7), 7);\n\t\t\t}\n\t\t\tstart = gf_bs_read_int(m4v->bs, 4);\n\t\t\tif (start == 0xF) {\n\t\t\t\tgf_bs_read_int(m4v->bs, 8);\n\t\t\t\tgf_bs_read_int(m4v->bs, 8);\n\t\t\t}\n\t\t\tif ((par_n >= 0) && (par_d >= 0)) {\n\t\t\t\tu8 par = m4v_get_sar_idx(par_n, par_d);\n\t\t\t\tgf_bs_write_int(mod, par, 4);\n\t\t\t\tif (par == 0xF) {\n\t\t\t\t\tgf_bs_write_int(mod, par_n, 8);\n\t\t\t\t\tgf_bs_write_int(mod, par_d, 8);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tgf_bs_write_int(mod, 0x0, 4);\n\t\t\t}\n\t\tcase -1:\n\t\t\tgo = 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\twhile (gf_bs_bits_available(m4v->bs)) {\n\t\tu32 b = gf_bs_read_int(m4v->bs, 1);\n\t\tgf_bs_write_int(mod, b, 1);\n\t}",
"\tgf_m4v_parser_del(m4v);\n\tgf_free(*o_data);\n\tgf_bs_get_content(mod, o_data, o_dataLen);\n\tgf_bs_del(mod);\n\treturn GF_OK;\n}",
"GF_EXPORT\nu64 gf_m4v_get_object_start(GF_M4VParser *m4v)\n{\n\treturn m4v->current_object_start;\n}",
"#if 0 //unused\nBool gf_m4v_is_valid_object_type(GF_M4VParser *m4v)\n{\n\treturn ((s32)m4v->current_object_type == -1) ? 0 : 1;\n}\n#endif",
"\nGF_EXPORT\nGF_Err gf_m4v_get_config(u8 *rawdsi, u32 rawdsi_size, GF_M4VDecSpecInfo *dsi)\n{\n\tGF_Err e;\n\tGF_M4VParser *vparse;\n\tif (!rawdsi || !rawdsi_size) return GF_NON_COMPLIANT_BITSTREAM;\n\tvparse = gf_m4v_parser_new(rawdsi, rawdsi_size, 0);\n\te = gf_m4v_parse_config(vparse, dsi);\n\tdsi->next_object_start = (u32)vparse->current_object_start;\n\tgf_m4v_parser_del(vparse);\n\treturn e < 0 ? e : GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_mpegv12_get_config(u8 *rawdsi, u32 rawdsi_size, GF_M4VDecSpecInfo *dsi)\n{\n\tGF_Err e;\n\tGF_M4VParser *vparse;\n\tif (!rawdsi || !rawdsi_size) return GF_NON_COMPLIANT_BITSTREAM;\n\tvparse = gf_m4v_parser_new(rawdsi, rawdsi_size, GF_TRUE);\n\te = gf_m4v_parse_config(vparse, dsi);\n\tdsi->next_object_start = (u32)vparse->current_object_start;\n\tgf_m4v_parser_del(vparse);\n\treturn e;\n}",
"#endif",
"\n/*\n\tAAC parser\n*/",
"struct __m4a_oti\n{\n\tu32 type;\n\tconst char *name;\n} M4AObjectTypes[] = {\n\t{0, \"MPEG-4 Audio Reserved\"},\n\t{1, \"MPEG-4 Audio AAC Main\"},\n\t{2, \"MPEG-4 Audio AAC LC\"},\n\t{3, \"MPEG-4 Audio AAC SSR\"},\n\t{4, \"MPEG-4 Audio AAC LTP\"},\n\t{5, \"MPEG-4 Audio SBR\"},\n\t{6, \"MPEG-4 Audio AAC Scalable\"},\n\t{7, \"MPEG-4 Audio TwinVQ\"},\n\t{8, \"MPEG-4 Audio CELP\"},\n\t{9, \"MPEG-4 Audio HVXC\"},\n\t{10, \"MPEG-4 Audio Reserved\"},\n\t{11, \"MPEG-4 Audio Reserved\"},\n\t{12, \"MPEG-4 Audio TTSI\"},\n\t{13, \"MPEG-4 Audio Main synthetic\"},\n\t{14, \"MPEG-4 Audio Wavetable synthesis\"},\n\t{15, \"MPEG-4 Audio General MIDI\"},\n\t{16, \"MPEG-4 Audio Algorithmic Synthesis and Audio FX\"},\n\t{17, \"MPEG-4 Audio ER AAC LC\"},\n\t{18, \"MPEG-4 Audio Reserved\"},\n\t{19, \"MPEG-4 Audio ER AAC LTP\"},\n\t{20, \"MPEG-4 Audio ER AAC scalable\"},\n\t{21, \"MPEG-4 Audio ER TwinVQ\"},\n\t{22, \"MPEG-4 Audio ER BSAC\"},\n\t{23, \"MPEG-4 Audio ER AAC LD\"},\n\t{24, \"MPEG-4 Audio ER CELP\"},\n\t{25, \"MPEG-4 Audio ER HVXC\"},\n\t{26, \"MPEG-4 Audio ER HILN\"},\n\t{27, \"MPEG-4 Audio ER Parametric\"},\n\t{28, \"MPEG-4 Audio SSC\"},\n\t{29, \"MPEG-4 Audio ParametricStereo\"},\n\t{30, \"MPEG-4 Audio Reserved\"},\n\t{31, \"MPEG-4 Audio Reserved\"},\n\t{32, \"MPEG-1 Audio Layer-1\"},\n\t{33, \"MPEG-1 Audio Layer-2\"},\n\t{34, \"MPEG-1 Audio Layer-3\"},\n\t{35, \"MPEG-4 Audio DST\"},\n\t{36, \"MPEG-4 Audio ALS\"},\n\t{37, \"MPEG-4 Audio SLS\"},\n\t{42, \"MPEG Audio xHE-AAC\"},\n};",
"GF_EXPORT\nconst char *gf_m4a_object_type_name(u32 objectType)\n{\n\tu32 i, count = GF_ARRAY_LENGTH(M4AObjectTypes);\n\tfor (i=0; i<count; i++) {\n\t\tif (objectType==M4AObjectTypes[i].type)\n\t\t\treturn M4AObjectTypes[i].name;\n\t}\n\treturn \"MPEG-4 Audio Unknown\";\n}",
"struct __m4a_profile\n{\n\tu32 value;\n\tconst char *name;\n} M4AProfiles[] = {\n\t{0x00, \"ISO Reserved (0x00)\"},\n\t{0x01, \"Main Audio Profile @ Level 1\"},\n\t{0x02, \"Main Audio Profile @ Level 2\"},\n\t{0x03, \"Main Audio Profile @ Level 3\"},\n\t{0x04, \"Main Audio Profile @ Level 4\"},\n\t{0x05, \"Scalable Audio Profile @ Level 1\"},\n\t{0x06, \"Scalable Audio Profile @ Level 2\"},\n\t{0x07, \"Scalable Audio Profile @ Level 3\"},\n\t{0x08, \"Scalable Audio Profile @ Level 4\"},\n\t{0x09, \"Speech Audio Profile @ Level 1\"},\n\t{0x0A, \"Speech Audio Profile @ Level 2\"},\n\t{0x0B, \"Synthetic Audio Profile @ Level 1\"},\n\t{0x0C, \"Synthetic Audio Profile @ Level 2\"},\n\t{0x0D, \"Synthetic Audio Profile @ Level 3\"},\n\t{0x0E, \"High Quality Audio Profile @ Level 1\"},\n\t{0x0F, \"High Quality Audio Profile @ Level 2\"},\n\t{0x10, \"High Quality Audio Profile @ Level 3\"},\n\t{0x11, \"High Quality Audio Profile @ Level 4\"},\n\t{0x12, \"High Quality Audio Profile @ Level 5\"},\n\t{0x13, \"High Quality Audio Profile @ Level 6\"},\n\t{0x14, \"High Quality Audio Profile @ Level 7\"},\n\t{0x15, \"High Quality Audio Profile @ Level 8\"},\n\t{0x16, \"Low Delay Audio Profile @ Level 1\"},\n\t{0x17, \"Low Delay Audio Profile @ Level 2\"},\n\t{0x18, \"Low Delay Audio Profile @ Level 3\"},\n\t{0x19, \"Low Delay Audio Profile @ Level 4\"},\n\t{0x1A, \"Low Delay Audio Profile @ Level 5\"},\n\t{0x1B, \"Low Delay Audio Profile @ Level 6\"},\n\t{0x1C, \"Low Delay Audio Profile @ Level 7\"},\n\t{0x1D, \"Low Delay Audio Profile @ Level 8\"},\n\t{0x1E, \"Natural Audio Profile @ Level 1\"},\n\t{0x1F, \"Natural Audio Profile @ Level 2\"},\n\t{0x20, \"Natural Audio Profile @ Level 3\"},\n\t{0x21, \"Natural Audio Profile @ Level 4\"},\n\t{0x22, \"Mobile Audio Internetworking Profile @ Level 1\"},\n\t{0x23, \"Mobile Audio Internetworking Profile @ Level 2\"},\n\t{0x24, \"Mobile Audio Internetworking Profile @ Level 3\"},\n\t{0x25, \"Mobile Audio Internetworking Profile @ Level 4\"},\n\t{0x26, \"Mobile Audio Internetworking Profile @ Level 5\"},\n\t{0x27, \"Mobile Audio Internetworking Profile @ Level 6\"},\n\t{0x28, \"AAC Profile @ Level 1\"},\n\t{0x29, \"AAC Profile @ Level 2\"},\n\t{0x2A, \"AAC Profile @ Level 4\"},\n\t{0x2B, \"AAC Profile @ Level 5\"},\n\t{0x2C, \"High Efficiency AAC Profile @ Level 2\"},\n\t{0x2D, \"High Efficiency AAC Profile @ Level 3\"},\n\t{0x2E, \"High Efficiency AAC Profile @ Level 4\"},\n\t{0x2F, \"High Efficiency AAC Profile @ Level 5\"},\n\t{0x30, \"High Efficiency AAC v2 Profile @ Level 2\"},\n\t{0x31, \"High Efficiency AAC v2 Profile @ Level 3\"},\n\t{0x32, \"High Efficiency AAC v2 Profile @ Level 4\"},\n\t{0x33, \"High Efficiency AAC v2 Profile @ Level 5\"},\n\t{0x34, \"Low Delay AAC Profile\"},\n\t{0x35, \"Baseline MPEG Surround Profile @ Level 1\"},\n\t{0x36, \"Baseline MPEG Surround Profile @ Level 2\"},\n\t{0x37, \"Baseline MPEG Surround Profile @ Level 3\"},\n\t{0x38, \"Baseline MPEG Surround Profile @ Level 4\"},\n\t{0x39, \"Baseline MPEG Surround Profile @ Level 5\"},\n\t{0x3A, \"Baseline MPEG Surround Profile @ Level 6\"},\n\t{0x3B, \"High Definition AAC Profile @ Level 1\"},\n\t{0x3C, \"ALS Simple Profile @ Level 1\"},\n\t{0x50, \"AAC Profile @ Level 6\"},\n\t{0x51, \"AAC Profile @ Level 7\"},\n\t{0x52, \"High Efficiency AAC Profile @ Level 6\"},\n\t{0x53, \"High Efficiency AAC Profile @ Level 7\"},\n\t{0x54, \"High Efficiency AAC v2 Profile @ Level 6\"},\n\t{0x55, \"High Efficiency AAC v2 Profile @ Level 7\"},\n\t{0x56, \"Extended High Efficiency AAC Profile @ Level 6\"},\n\t{0x57, \"Extended High Efficiency AAC Profile @ Level 7\"},\n\t{0xFE, \"Not part of MPEG-4 audio profiles\"},\n\t{0xFF, \"No audio capability required\"}\n};",
"GF_EXPORT\nconst char *gf_m4a_get_profile_name(u8 audio_pl)\n{\n\tu32 i, count = GF_ARRAY_LENGTH(M4AProfiles);\n\tfor (i=0; i<count; i++) {\n\t\tif ((u32) audio_pl==M4AProfiles[i].value)\n\t\t\treturn M4AProfiles[i].name;\n\t}\n\treturn \"ISO Reserved / User Private\";\n}",
"#ifndef GPAC_DISABLE_AV_PARSERS",
"GF_EXPORT\nu32 gf_m4a_get_profile(GF_M4ADecSpecInfo *cfg)\n{\n\tswitch (cfg->base_object_type) {\n\tcase 2: /*AAC LC*/\n\t\tif (cfg->nb_chan <= 2)\n\t\t\treturn (cfg->base_sr <= 24000) ? 0x28 : 0x29; /*LC@L1 or LC@L2*/\n\t\tif (cfg->nb_chan <= 5)\n\t\t\treturn (cfg->base_sr <= 48000) ? 0x2A : 0x2B; /*LC@L4 or LC@L5*/\n\t\treturn (cfg->base_sr <= 48000) ? 0x50 : 0x51; /*LC@L4 or LC@L5*/\n\tcase 5: /*HE-AAC - SBR*/\n\t\tif (cfg->nb_chan <= 2)\n\t\t\treturn (cfg->base_sr <= 24000) ? 0x2C : 0x2D; /*HE@L2 or HE@L3*/\n\t\tif (cfg->nb_chan <= 5)\n\t\t\treturn (cfg->base_sr <= 48000) ? 0x2E : 0x2F; /*HE@L4 or HE@L5*/\n\t\treturn (cfg->base_sr <= 48000) ? 0x52 : 0x53; /*HE@L6 or HE@L7*/\n\tcase 29: /*HE-AACv2 - SBR+PS*/\n\t\tif (cfg->nb_chan <= 2)\n\t\t\treturn (cfg->base_sr <= 24000) ? 0x30 : 0x31; /*HE-AACv2@L2 or HE-AACv2@L3*/\n\t\tif (cfg->nb_chan <= 5)\n\t\t\treturn (cfg->base_sr <= 48000) ? 0x32 : 0x33; /*HE-AACv2@L4 or HE-AACv2@L5*/\n\t\treturn (cfg->base_sr <= 48000) ? 0x54 : 0x55; /*HE-AACv2@L6 or HE-AACv2@L7*/\n\t/*default to HQ*/\n\tdefault:\n\t\tif (cfg->nb_chan <= 2) return (cfg->base_sr < 24000) ? 0x0E : 0x0F; /*HQ@L1 or HQ@L2*/\n\t\treturn 0x10; /*HQ@L3*/\n\t}\n}",
"GF_EXPORT\nGF_Err gf_m4a_parse_program_config_element(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg)\n{\n\tu32 i;",
"\tcfg->program_config_element_present = 1;\n\tcfg->cpe_channels = 0;",
"\tcfg->element_instance_tag = gf_bs_read_int_log(bs, 4, \"element_instance_tag\");\n\tcfg->object_type = gf_bs_read_int_log(bs, 2, \"object_type\");\n\tcfg->sampling_frequency_index = gf_bs_read_int_log(bs, 4, \"sampling_frequency_index\");\n\tcfg->num_front_channel_elements = gf_bs_read_int_log(bs, 4, \"num_front_channel_elements\");\n\tcfg->num_side_channel_elements = gf_bs_read_int_log(bs, 4, \"num_side_channel_elements\");\n\tcfg->num_back_channel_elements = gf_bs_read_int_log(bs, 4, \"num_back_channel_elements\");\n\tcfg->num_lfe_channel_elements = gf_bs_read_int_log(bs, 2, \"num_lfe_channel_elements\");\n\tcfg->num_assoc_data_elements = gf_bs_read_int_log(bs, 3, \"num_assoc_data_elements\");\n\tcfg->num_valid_cc_elements = gf_bs_read_int_log(bs, 4, \"num_valid_cc_elements\");\n\tcfg->mono_mixdown_present = (Bool)gf_bs_read_int_log(bs, 1, \"mono_mixdown_present\");\n\tif (cfg->mono_mixdown_present) {\n\t\tcfg->mono_mixdown_element_number = gf_bs_read_int_log(bs, 4, \"mono_mixdown_element_number\");\n\t}\n\tcfg->stereo_mixdown_present = gf_bs_read_int_log(bs, 1, \"stereo_mixdown_present\");\n\tif (cfg->stereo_mixdown_present) {\n\t\tcfg->stereo_mixdown_element_number = gf_bs_read_int_log(bs, 4, \"stereo_mixdown_element_number\");\n\t}\n\tcfg->matrix_mixdown_idx_present = gf_bs_read_int_log(bs, 1, \"matrix_mixdown_idx_present\");\n\tif (cfg->matrix_mixdown_idx_present) {\n\t\tcfg->matrix_mixdown_idx = gf_bs_read_int_log(bs, 2, \"matrix_mixdown_idx\");\n\t\tcfg->pseudo_surround_enable = gf_bs_read_int_log(bs, 1, \"pseudo_surround_enable\");\n\t}\n\tfor (i = 0; i < cfg->num_front_channel_elements; i++) {\n\t\tcfg->front_element_is_cpe[i] = gf_bs_read_int_log_idx(bs, 1, \"front_element_is_cpe\", i);\n\t\tcfg->front_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"front_element_tag_select\", i);\n\t\tif (cfg->front_element_is_cpe[i]) cfg->cpe_channels++;\n\t}\n\tfor (i = 0; i < cfg->num_side_channel_elements; i++) {\n\t\tcfg->side_element_is_cpe[i] = gf_bs_read_int_log_idx(bs, 1, \"side_element_is_cpe\", i);\n\t\tcfg->side_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"side_element_tag_select\", i);\n\t\tif (cfg->side_element_is_cpe[i]) cfg->cpe_channels++;\n\t}\n\tfor (i = 0; i < cfg->num_back_channel_elements; i++) {\n\t\tcfg->back_element_is_cpe[i] = gf_bs_read_int_log_idx(bs, 1, \"back_element_is_cpe\", i);\n\t\tcfg->back_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"back_element_tag_select\", i);\n\t\tif (cfg->back_element_is_cpe[i]) cfg->cpe_channels++;\n\t}\n\tfor (i = 0; i < cfg->num_lfe_channel_elements; i++) {\n\t\tcfg->lfe_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"lfe_element_tag_select\", i);\n\t}\n\tfor (i = 0; i < cfg->num_assoc_data_elements; i++) {\n\t\tcfg->assoc_data_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"assoc_data_element_tag_select\", i);\n\t}",
"\tfor (i = 0; i < cfg->num_valid_cc_elements; i++) {\n\t\tcfg->cc_element_is_ind_sw[i] = gf_bs_read_int_log_idx(bs, 1, \"cc_element_is_ind_sw\", i);\n\t\tcfg->valid_cc_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, \"valid_cc_element_tag_select\", i);\n\t}\n\tgf_bs_align(bs);\n\tcfg->comment_field_bytes = gf_bs_read_int_log(bs, 8, \"comment_field_bytes\");\n\tgf_bs_read_data(bs, (char *)cfg->comments, cfg->comment_field_bytes);",
"\tcfg->nb_chan = cfg->num_front_channel_elements + cfg->num_back_channel_elements + cfg->num_side_channel_elements + cfg->num_lfe_channel_elements;\n\tcfg->nb_chan += cfg->cpe_channels;",
"\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4a_parse_config(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg, Bool size_known)\n{\n\tu32 audio_obj_type;\n\tmemset(cfg, 0, sizeof(GF_M4ADecSpecInfo));\n\tcfg->base_object_type = gf_bs_read_int_log(bs, 5, \"base_object_type\");\n\t/*extended object type*/\n\tif (cfg->base_object_type == 31) {\n\t\tcfg->base_object_type = 32 + gf_bs_read_int_log(bs, 6, \"extended_base_object_type\");\n\t}\n\tcfg->base_sr_index = gf_bs_read_int_log(bs, 4, \"base_samplerate_index\");\n\tif (cfg->base_sr_index == 0x0F) {\n\t\tcfg->base_sr = gf_bs_read_int_log(bs, 24, \"base_samplerate\");\n\t}\n\telse {\n\t\tcfg->base_sr = GF_M4ASampleRates[cfg->base_sr_index];\n\t}",
"\tcfg->chan_cfg = gf_bs_read_int_log(bs, 4, \"channel_configuration\");\n\tif (cfg->chan_cfg) {\n\t\tcfg->nb_chan = GF_M4ANumChannels[cfg->chan_cfg - 1];\n\t}",
"\taudio_obj_type = cfg->base_object_type;\n\tif (cfg->base_object_type == 5 || cfg->base_object_type == 29) {\n\t\tif (cfg->base_object_type == 29) {\n\t\t\tcfg->has_ps = 1;\n\t\t\tcfg->nb_chan = 1;\n\t\t}\n\t\tcfg->has_sbr = GF_TRUE;\n\t\tcfg->sbr_sr_index = gf_bs_read_int_log(bs, 4, \"sbr_samplerate_index\");\n\t\tif (cfg->sbr_sr_index == 0x0F) {\n\t\t\tcfg->sbr_sr = gf_bs_read_int_log(bs, 24, \"sbr_samplerate\");\n\t\t}\n\t\telse {\n\t\t\tcfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];\n\t\t}\n\t\tcfg->sbr_object_type = gf_bs_read_int_log(bs, 5, \"sbr_object_type\");\n\t\tif (cfg->sbr_object_type==31)\n\t\t\tcfg->sbr_object_type = 32 + gf_bs_read_int_log(bs, 6, \"audioObjectTypeExt\");\n\t\taudio_obj_type = cfg->sbr_object_type;\n\t\tif (cfg->sbr_object_type==22) {\n\t\t\t/*ext_chan_cfg = */gf_bs_read_int_log(bs, 4, \"channel_configuration\");\n\t\t}\n\t}",
"\t/*object cfg*/\n\tswitch (audio_obj_type) {\n\tcase 1:\n\tcase 2:\n\tcase 3:\n\tcase 4:\n\tcase 6:\n\tcase 7:\n\tcase 17:\n\tcase 19:\n\tcase 20:\n\tcase 21:\n\tcase 22:\n\tcase 23:\n\tcase 42:\n\t{\n\t\tBool ext_flag;\n\t\tgf_bs_read_int_log(bs, 1, \"frame_length_flag\");\n\t\tif (gf_bs_read_int_log(bs, 1, \"depends_on_core_coder\"))\n\t\t\tgf_bs_read_int_log(bs, 14, \"delay\");\n\t\text_flag = gf_bs_read_int_log(bs, 1, \"extension_flag\");",
"\t\tif (!cfg->chan_cfg) {\n\t\t\tgf_m4a_parse_program_config_element(bs, cfg);\n\t\t}",
"\t\tif ((cfg->base_object_type == 6) || (cfg->base_object_type == 20)) {\n\t\t\tgf_bs_read_int_log(bs, 3, \"layerN\");\n\t\t}\n\t\tif (ext_flag) {\n\t\t\tif (cfg->base_object_type == 22) {\n\t\t\t\tgf_bs_read_int_log(bs, 5, \"numOfSubFrame\");\n\t\t\t\tgf_bs_read_int_log(bs, 11, \"layer_length\");\n\t\t\t}\n\t\t\tif ((cfg->base_object_type == 17)\n\t\t\t\t|| (cfg->base_object_type == 19)\n\t\t\t\t|| (cfg->base_object_type == 20)\n\t\t\t\t|| (cfg->base_object_type == 23)\n\t\t\t) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"aacSectionDataResilienceFlag\");\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"aacScalefactorDataResilienceFlag\");\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"aacSpectralDataResilienceFlag\");\n\t\t\t}\n\t\t\tgf_bs_read_int_log(bs, 1, \"extensionFlag3\");\n\t\t}\n\t}\n\tbreak;\n\t}\n\t/*ER cfg*/\n\tswitch (audio_obj_type) {\n\tcase 17:\n\tcase 19:\n\tcase 20:\n\tcase 21:\n\tcase 22:\n\tcase 23:\n\tcase 24:\n\tcase 25:\n\tcase 26:\n\tcase 27:\n\t{\n\t\tu32 epConfig = gf_bs_read_int_log(bs, 2, \"epConfig\");\n\t\tif ((epConfig == 2) || (epConfig == 3)) {\n\t\t}\n\t\tif (epConfig == 3) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"directMapping\");\n\t\t}\n\t}\n\tbreak;\n\t}",
"\tif (size_known && (cfg->base_object_type != 5) && (cfg->base_object_type != 29)) {\n\t\twhile (gf_bs_available(bs) >= 2) {\n\t\t\tu32 sync = gf_bs_peek_bits(bs, 11, 0);\n\t\t\tif (sync == 0x2b7) {\n\t\t\t\tgf_bs_read_int_log(bs, 11, \"syncExtensionType\");\n\t\t\t\tcfg->sbr_object_type = gf_bs_read_int_log(bs, 5, \"extensionAudioObjectType \");\n\t\t\t\tcfg->has_sbr = gf_bs_read_int_log(bs, 1, \"sbrPresentFlag\");\n\t\t\t\tif (cfg->has_sbr) {\n\t\t\t\t\tcfg->sbr_sr_index = gf_bs_read_int_log(bs, 4, \"extensionSamplingFrequencyIndex\");\n\t\t\t\t\tif (cfg->sbr_sr_index == 0x0F) {\n\t\t\t\t\t\tcfg->sbr_sr = gf_bs_read_int_log(bs, 24, \"extensionSamplingFrequency\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tcfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (sync == 0x548) {\n\t\t\t\tgf_bs_read_int_log(bs, 11, \"syncExtensionType\");\n\t\t\t\tcfg->has_ps = gf_bs_read_int_log(bs, 1, \"hasParametricStereo\");\n\t\t\t\tif (cfg->has_ps)\n\t\t\t\t\tcfg->nb_chan = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tcfg->audioPL = gf_m4a_get_profile(cfg);\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4a_get_config(u8 *dsi, u32 dsi_size, GF_M4ADecSpecInfo *cfg)\n{\n\tGF_BitStream *bs;\n\tif (!dsi || !dsi_size || (dsi_size < 2)) return GF_NON_COMPLIANT_BITSTREAM;\n\tbs = gf_bs_new(dsi, dsi_size, GF_BITSTREAM_READ);\n\tgf_m4a_parse_config(bs, cfg, GF_TRUE);\n\tgf_bs_del(bs);\n\treturn GF_OK;\n}",
"u32 gf_latm_get_value(GF_BitStream *bs)\n{\n\tu32 i, tmp, value = 0;\n\tu32 bytesForValue = gf_bs_read_int(bs, 2);\n\tfor (i = 0; i <= bytesForValue; i++) {\n\t\tvalue <<= 8;\n\t\ttmp = gf_bs_read_int(bs, 8);\n\t\tvalue += tmp;\n\t}\n\treturn value;\n}",
"GF_EXPORT\nu32 gf_m4a_get_channel_cfg(u32 nb_chan)\n{\n\tu32 i, count = sizeof(GF_M4ANumChannels) / sizeof(u32);\n\tfor (i = 0; i < count; i++) {\n\t\tif (GF_M4ANumChannels[i] == nb_chan) return i + 1;\n\t}\n\treturn 0;\n}",
"GF_EXPORT\nGF_Err gf_m4a_write_program_config_element_bs(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg)\n{\n\tu32 i;\n\tgf_bs_write_int(bs, cfg->element_instance_tag, 4);\n\tgf_bs_write_int(bs, cfg->object_type, 2);\n\tgf_bs_write_int(bs, cfg->sampling_frequency_index, 4);\n\tgf_bs_write_int(bs, cfg->num_front_channel_elements, 4);\n\tgf_bs_write_int(bs, cfg->num_side_channel_elements, 4);\n\tgf_bs_write_int(bs, cfg->num_back_channel_elements, 4);\n\tgf_bs_write_int(bs, cfg->num_lfe_channel_elements, 2);\n\tgf_bs_write_int(bs, cfg->num_assoc_data_elements, 3);\n\tgf_bs_write_int(bs, cfg->num_valid_cc_elements, 4);\n\tgf_bs_write_int(bs, cfg->mono_mixdown_present, 1);\n\tif (cfg->mono_mixdown_present) {\n\t\tgf_bs_write_int(bs, cfg->mono_mixdown_element_number, 4);\n\t}\n\tgf_bs_write_int(bs, cfg->stereo_mixdown_present, 1);\n\tif (cfg->stereo_mixdown_present) {\n\t\tgf_bs_write_int(bs, cfg->stereo_mixdown_element_number, 4);\n\t}\n\tgf_bs_write_int(bs, cfg->matrix_mixdown_idx_present, 1);\n\tif (cfg->matrix_mixdown_idx_present) {\n\t\tgf_bs_write_int(bs, cfg->matrix_mixdown_idx, 2);\n\t\tgf_bs_write_int(bs, cfg->pseudo_surround_enable, 1);\n\t}\n\tfor (i = 0; i < cfg->num_front_channel_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->front_element_is_cpe[i], 1);\n\t\tgf_bs_write_int(bs, cfg->front_element_tag_select[i], 4);\n\t}\n\tfor (i = 0; i < cfg->num_side_channel_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->side_element_is_cpe[i], 1);\n\t\tgf_bs_write_int(bs, cfg->side_element_tag_select[i], 4);\n\t}\n\tfor (i = 0; i < cfg->num_back_channel_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->back_element_is_cpe[i], 1);\n\t\tgf_bs_write_int(bs, cfg->back_element_tag_select[i], 4);\n\t}\n\tfor (i = 0; i < cfg->num_lfe_channel_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->lfe_element_tag_select[i], 4);\n\t}\n\tfor (i = 0; i < cfg->num_assoc_data_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->assoc_data_element_tag_select[i], 4);\n\t}",
"\tfor (i = 0; i < cfg->num_valid_cc_elements; i++) {\n\t\tgf_bs_write_int(bs, cfg->cc_element_is_ind_sw[i], 1);\n\t\tgf_bs_write_int(bs, cfg->valid_cc_element_tag_select[i], 4);\n\t}\n\tgf_bs_align(bs);\n\tgf_bs_write_int(bs, cfg->comment_field_bytes, 8);\n\tgf_bs_write_data(bs, (char *)cfg->comments, cfg->comment_field_bytes);\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4a_write_config_bs(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg)\n{\n\tif (!cfg->base_sr_index) {\n\t\tif (!cfg->base_sr) return GF_BAD_PARAM;\n\t\twhile (GF_M4ASampleRates[cfg->base_sr_index]) {\n\t\t\tif (GF_M4ASampleRates[cfg->base_sr_index] == cfg->base_sr)\n\t\t\t\tbreak;\n\t\t\tcfg->base_sr_index++;\n\t\t}\n\t}\n\tif (cfg->sbr_sr && !cfg->sbr_sr_index) {\n\t\twhile (GF_M4ASampleRates[cfg->sbr_sr_index]) {\n\t\t\tif (GF_M4ASampleRates[cfg->sbr_sr_index] == cfg->sbr_sr)\n\t\t\t\tbreak;\n\t\t\tcfg->sbr_sr_index++;\n\t\t}\n\t}\n\t/*extended object type*/\n\tif (cfg->base_object_type >= 32) {\n\t\tgf_bs_write_int(bs, 31, 5);\n\t\tgf_bs_write_int(bs, cfg->base_object_type - 32, 6);\n\t}\n\telse {\n\t\tgf_bs_write_int(bs, cfg->base_object_type, 5);\n\t}\n\tgf_bs_write_int(bs, cfg->base_sr_index, 4);\n\tif (cfg->base_sr_index == 0x0F) {\n\t\tgf_bs_write_int(bs, cfg->base_sr, 24);\n\t}",
"\tif (cfg->program_config_element_present) {\n\t\tgf_bs_write_int(bs, 0, 4);\n\t} else {\n\t\tcfg->chan_cfg = gf_m4a_get_channel_cfg(cfg->nb_chan);\n\t\tif (!cfg->chan_cfg) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AAC] Cannot write decoder config, ProgramConfigElement is missing and channel configuration is not a predefined one !\\n\"));\n\t\t\treturn GF_BAD_PARAM;\n\t\t}\n\t\tgf_bs_write_int(bs, cfg->chan_cfg, 4);\n\t}",
"\tif (cfg->base_object_type == 5 || cfg->base_object_type == 29) {\n\t\tif (cfg->base_object_type == 29) {\n\t\t\tcfg->has_ps = 1;\n\t\t\tcfg->nb_chan = 1;\n\t\t}\n\t\tcfg->has_sbr = 1;\n\t\tgf_bs_write_int(bs, cfg->sbr_sr_index, 4);\n\t\tif (cfg->sbr_sr_index == 0x0F) {\n\t\t\tgf_bs_write_int(bs, cfg->sbr_sr, 24);\n\t\t}\n\t\tgf_bs_write_int(bs, cfg->sbr_object_type, 5);\n\t}",
"\t/*object cfg*/\n\tswitch (cfg->base_object_type) {\n\tcase 1:\n\tcase 2:\n\tcase 3:\n\tcase 4:\n\tcase 6:\n\tcase 7:\n\tcase 17:\n\tcase 19:\n\tcase 20:\n\tcase 21:\n\tcase 22:\n\tcase 23:\n\tcase 42:\n\t{\n\t\t/*frame length flag*/\n\t\tgf_bs_write_int(bs, 0, 1);\n\t\t/*depends on core coder*/\n\t\tgf_bs_write_int(bs, 0, 1);\n\t\t/*ext flag*/\n\t\tgf_bs_write_int(bs, 0, 1);",
"\t\tif (cfg->program_config_element_present) {\n\t\t\tgf_m4a_write_program_config_element_bs(bs, cfg);\n\t\t}",
"\t\tif ((cfg->base_object_type == 6) || (cfg->base_object_type == 20)) {\n\t\t\tgf_bs_write_int(bs, 0, 3);\n\t\t}\n\t}\n\tbreak;\n\t}\n\t/*ER cfg - not supported*/",
"\t/*implicit sbr/ps signaling not written here, cf reframe_adts*/\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_m4a_write_config(GF_M4ADecSpecInfo *cfg, u8 **dsi, u32 *dsi_size)\n{\n\tGF_BitStream *bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\tgf_m4a_write_config_bs(bs, cfg);\n\tgf_bs_get_content(bs, dsi, dsi_size);\n\tgf_bs_del(bs);\n\treturn GF_OK;\n}",
"\n/*AV1 parsing*/",
"static u32 av1_read_ns(GF_BitStream *bs, u32 n, const char *fname)\n{\n\tu32 v, res;\n\tBool extra_bit;\n\tint w = (u32)(log(n) / log(2)) + 1;\n\tu32 m = (1 << w) - n;\n\tassert(w < 32);\n\tv = gf_bs_read_int(bs, w - 1);\n\tif (v < m) {\n\t\tif (fname) {\n\t\t\tgf_bs_log(bs, w-1, fname, v);\n\t\t}\n\t\treturn v;\n\t}\n\textra_bit = gf_bs_read_int(bs, 1);\n\tres = (v << 1) - m + extra_bit;\n\tif (fname) {\n\t\tgf_bs_log(bs, w, fname, res);\n\t}\n\treturn res;\n}",
"static void av1_color_config(GF_BitStream *bs, AV1State *state)\n{\n\tstate->config->high_bitdepth = gf_bs_read_int_log(bs, 1, \"high_bitdepth\");\n\tstate->bit_depth = 8;\n\tif (state->config->seq_profile == 2 && state->config->high_bitdepth) {\n\t\tstate->config->twelve_bit = gf_bs_read_int_log(bs, 1, \"twelve_bit\");\n\t\tstate->bit_depth = state->config->twelve_bit ? 12 : 10;\n\t}\n\telse if (state->config->seq_profile <= 2) {\n\t\tstate->bit_depth = state->config->high_bitdepth ? 10 : 8;\n\t}",
"\tstate->config->monochrome = GF_FALSE;\n\tif (state->config->seq_profile == 1) {\n\t\tstate->config->monochrome = GF_FALSE;\n\t}\n\telse {\n\t\tstate->config->monochrome = gf_bs_read_int_log(bs, 1, \"monochrome\");\n\t}\n\t/*NumPlanes = mono_chrome ? 1 : 3;*/\n\tstate->color_description_present_flag = gf_bs_read_int_log(bs, 1, \"color_description_present_flag\");\n\tif (state->color_description_present_flag) {\n\t\tstate->color_primaries = gf_bs_read_int_log(bs, 8, \"color_primaries\");\n\t\tstate->transfer_characteristics = gf_bs_read_int_log(bs, 8, \"transfer_characteristics\");\n\t\tstate->matrix_coefficients = gf_bs_read_int_log(bs, 8, \"matrix_coefficients\");\n\t}\n\telse {\n\t\tstate->color_primaries = 2/*CP_UNSPECIFIED*/;\n\t\tstate->transfer_characteristics = 2/*TC_UNSPECIFIED*/;\n\t\tstate->matrix_coefficients = 2/*MC_UNSPECIFIED*/;\n\t}\n\tif (state->config->monochrome) {\n\t\tstate->color_range = gf_bs_read_int_log(bs, 1, \"color_range\");\n\t\tstate->config->chroma_subsampling_x = GF_TRUE;\n\t\tstate->config->chroma_subsampling_y = GF_TRUE;\n\t\tstate->config->chroma_sample_position = 0/*CSP_UNKNOWN*/;\n\t\tstate->separate_uv_delta_q = 0;\n\t\treturn;\n\t}\n\telse if (state->color_primaries == 0/*CP_BT_709*/ &&\n\t\tstate->transfer_characteristics == 13/*TC_SRGB*/ &&\n\t\tstate->matrix_coefficients == 0/*MC_IDENTITY*/) {\n\t\tstate->color_range = GF_TRUE;\n\t\tstate->config->chroma_subsampling_x = GF_FALSE;\n\t\tstate->config->chroma_subsampling_y = GF_FALSE;\n\t}\n\telse {\n\t\tstate->config->chroma_subsampling_x = GF_FALSE;\n\t\tstate->config->chroma_subsampling_y = GF_FALSE;",
"\t\tstate->color_range = gf_bs_read_int_log(bs, 1, \"color_range\");\n\t\tif (state->config->seq_profile == 0) {\n\t\t\tstate->config->chroma_subsampling_x = GF_TRUE;\n\t\t\tstate->config->chroma_subsampling_y = GF_TRUE;\n\t\t}\n\t\telse if (state->config->seq_profile == 1) {\n\t\t\tstate->config->chroma_subsampling_x = GF_FALSE;\n\t\t\tstate->config->chroma_subsampling_y = GF_FALSE;\n\t\t}\n\t\telse {\n\t\t\tif (state->bit_depth == 12) {\n\t\t\t\tstate->config->chroma_subsampling_x = gf_bs_read_int_log(bs, 1, \"chroma_subsampling_x\");\n\t\t\t\tif (state->config->chroma_subsampling_x)\n\t\t\t\t\tstate->config->chroma_subsampling_y = gf_bs_read_int_log(bs, 1, \"chroma_subsampling_y\");\n\t\t\t\telse\n\t\t\t\t\tstate->config->chroma_subsampling_y = GF_FALSE;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate->config->chroma_subsampling_x = GF_TRUE;\n\t\t\t\tstate->config->chroma_subsampling_y = GF_FALSE;\n\t\t\t}\n\t\t}\n\t\tif (state->config->chroma_subsampling_x && state->config->chroma_subsampling_y) {\n\t\t\tstate->config->chroma_sample_position = gf_bs_read_int_log(bs, 2, \"chroma_sample_position\");\n\t\t}\n\t}\n\tstate->separate_uv_delta_q = gf_bs_read_int_log(bs, 1, \"separate_uv_delta_q\");\n}",
"\nstatic u32 av1_uvlc(GF_BitStream *bs, const char *fname)\n{\n\tu32 res;\n\tu8 leadingZeros = 0;\n\twhile (1) {\n\t\tBool done = gf_bs_read_int(bs, 1);\n\t\tif (done)\n\t\t\tbreak;\n\t\tleadingZeros++;\n\t}\n\tif (leadingZeros >= 32) {\n\t\treturn 0xFFFFFFFF;\n\t}\n\tres = gf_bs_read_int(bs, leadingZeros) + (1 << leadingZeros) - 1;\n\tgf_bs_log(bs, 2*leadingZeros, fname, res);\n\treturn res;\n}",
"static void timing_info(GF_BitStream *bs, AV1State *state) {\n\tu32 time_scale = 0;\n\tu32 num_units_in_display_tick = gf_bs_read_int_log(bs, 32, \"num_units_in_display_tick\");\n\tif (num_units_in_display_tick == 0) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] num_units_in_display_tick must be greater than 0.\\n\"));\n\t}\n\ttime_scale = gf_bs_read_int_log(bs, 32, \"time_scale\");\n\tif (time_scale == 0) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] time_scale must be greater than 0.\\n\"));\n\t}\n\tstate->equal_picture_interval = gf_bs_read_int_log(bs, 1, \"equal_picture_interval\");\n\tif (state->equal_picture_interval) {\n\t\tu32 num_ticks_per_picture_minus_1 = av1_uvlc(bs, \"num_ticks_per_picture_minus_1\");\n\t\tstate->tb_num = time_scale;\n\t\tstate->tb_den = (num_ticks_per_picture_minus_1 + 1)*num_units_in_display_tick;\n\t}\n\telse {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] VFR not supported.\\n\"));\n\t\t//TODO: upload num_units_in_display_tick (eq. to the POC in H264), compute delta between frames, set it as dts_inc in gf_import_aom_av1()\n\t}\n}",
"static void decoder_model_info(AV1State *state, GF_BitStream *bs) {\n\tstate->buffer_delay_length = 1 + gf_bs_read_int_log(bs, 5, \"buffer_delay_length_minus1\");\n\tgf_bs_read_int_log(bs, 32, \"num_units_in_decoding_tick\");\n\tstate->buffer_removal_time_length = gf_bs_read_int_log(bs, 5, \"buffer_removal_time_length\");\n\tstate->frame_presentation_time_length = 1 + gf_bs_read_int_log(bs, 5, \"frame_presentation_time_length_minus1\");\n}",
"static void operating_parameters_info(GF_BitStream *bs, const u8 idx, const u8 buffer_delay_length_minus_1) {\n\tconst u8 n = buffer_delay_length_minus_1 + 1;\n\tgf_bs_read_int_log(bs, n, \"decoder_buffer_delay\");\n\tgf_bs_read_int_log(bs, n, \"encoder_buffer_delay\");\n\tgf_bs_read_int_log(bs, 1, \"low_delay_mode_flag\");\n}",
"static void av1_parse_sequence_header_obu(GF_BitStream *bs, AV1State *state)\n{\n\tu8 buffer_delay_length_minus_1 = 0;\n\tstate->frame_state.seen_seq_header = GF_TRUE;\n\tstate->config->seq_profile = gf_bs_read_int_log(bs, 3, \"seq_profile\");\n\tstate->still_picture = gf_bs_read_int_log(bs, 1, \"still_picture\");\n\tstate->reduced_still_picture_header = gf_bs_read_int_log(bs, 1, \"reduced_still_picture_header\");\n\tif (state->reduced_still_picture_header) {\n\t\t//timing_info_present_flag = GF_FALSE;\n\t\t//initial_display_delay_present_flag = GF_FALSE;\n\t\tstate->operating_points_count = 1;\n\t\tstate->config->seq_level_idx_0 = gf_bs_read_int_log(bs, 5, \"seq_level_idx_0\");\n\t}\n\telse {\n\t\tu8 i = 0;\n\t\tBool initial_display_delay_present_flag;\n\t\tBool timing_info_present_flag = gf_bs_read_int_log(bs, 1, \"timing_info_present_flag\");\n\t\tif (timing_info_present_flag) {\n\t\t\ttiming_info(bs, state);\n\t\t\tstate->decoder_model_info_present_flag = gf_bs_read_int_log(bs, 1, \"decoder_model_info_present_flag\");\n\t\t\tif (state->decoder_model_info_present_flag) {\n\t\t\t\tdecoder_model_info(state, bs);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tstate->decoder_model_info_present_flag = GF_FALSE;\n\t\t}\n\t\tinitial_display_delay_present_flag = gf_bs_read_int_log(bs, 1, \"initial_display_delay_present_flag\");\n\t\tstate->operating_points_count = 1 + gf_bs_read_int_log(bs, 5, \"operating_points_count_minus1\");\n\t\tfor (i = 0; i < state->operating_points_count; i++) {\n\t\t\tu8 seq_level_idx_i, seq_tier = 0;",
"\t\t\tstate->operating_point_idc[i] = gf_bs_read_int_log_idx(bs, 12, \"operating_point_idc\", i);",
"\t\t\tseq_level_idx_i = gf_bs_read_int_log_idx(bs, 5, \"seq_level_idx\", i);\n\t\t\tif (i == 0) state->config->seq_level_idx_0 = seq_level_idx_i;",
"\t\t\tif (seq_level_idx_i > 7) {\n\t\t\t\tseq_tier = gf_bs_read_int_log_idx(bs, 1, \"seq_tier\", i);\n\t\t\t}\n\t\t\tif (i == 0) state->config->seq_tier_0 = seq_tier;",
"\t\t\tif (state->decoder_model_info_present_flag) {\n\t\t\t\tstate->decoder_model_present_for_this_op[i] = gf_bs_read_int_log_idx(bs, 1, \"decoder_model_present_for_this_op\", i);\n\t\t\t\tif (state->decoder_model_present_for_this_op[i]) {\n\t\t\t\t\toperating_parameters_info(bs, i, buffer_delay_length_minus_1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate->decoder_model_present_for_this_op[i] = 0;\n\t\t\t}\n\t\t\tif (initial_display_delay_present_flag) {\n\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"initial_display_delay_present_for_this_op\", i) ) {\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 4, \"initial_display_delay_minus1\", i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\t//operatingPoint = av1_choose_operating_point(bs);\n\tstate->OperatingPointIdc = 0;//TODO: operating_point_idc[operatingPoint];",
"\tstate->frame_width_bits_minus_1 = gf_bs_read_int_log(bs, 4, \"frame_width_bits_minus1\");\n\tstate->frame_height_bits_minus_1 = gf_bs_read_int_log(bs, 4, \"frame_height_bits_minus1\");\n\tstate->width = gf_bs_read_int_log(bs, state->frame_width_bits_minus_1 + 1, \"width_minus1\") + 1;\n\tstate->height = gf_bs_read_int_log(bs, state->frame_height_bits_minus_1 + 1, \"height_minus1\") + 1;\n\tstate->sequence_width = state->width;\n\tstate->sequence_height = state->height;\n\tstate->frame_id_numbers_present_flag = GF_FALSE;\n\tif (!state->reduced_still_picture_header) {\n\t\tstate->frame_id_numbers_present_flag = gf_bs_read_int_log(bs, 1, \"frame_id_numbers_present_flag\");\n\t}\n\tif (state->frame_id_numbers_present_flag) {\n\t\tstate->delta_frame_id_length_minus_2 = gf_bs_read_int_log(bs, 4, \"delta_frame_id_length_minus2\");\n\t\tstate->additional_frame_id_length_minus_1 = gf_bs_read_int_log(bs, 3, \"additional_frame_id_length_minus1\");\n\t}\n\tstate->use_128x128_superblock = gf_bs_read_int_log(bs, 1, \"use_128x128_superblock\");\n\tgf_bs_read_int_log(bs, 1, \"enable_filter_intra\");\n\tgf_bs_read_int_log(bs, 1, \"enable_intra_edge_filter\");\n\tif (state->reduced_still_picture_header) {\n\t\t/*enable_interintra_compound = 0;\n\t\tenable_masked_compound = 0;\n\t\tenable_dual_filter = 0;\n\t\tenable_jnt_comp = 0;\n\t\tenable_ref_frame_mvs = 0;*/\n\t\tstate->enable_warped_motion = 0;\n\t\tstate->enable_order_hint = GF_FALSE;\n\t\tstate->OrderHintBits = 0;\n\t\tstate->seq_force_integer_mv = 2/*SELECT_INTEGER_MV*/;\n\t\tstate->seq_force_screen_content_tools = 2/*SELECT_SCREEN_CONTENT_TOOLS*/;\n\t}\n\telse {\n\t\tBool seq_choose_screen_content_tools;\n\t\tgf_bs_read_int_log(bs, 1, \"enable_interintra_compound\");\n\t\tgf_bs_read_int_log(bs, 1, \"enable_masked_compound\");\n\t\tstate->enable_warped_motion = gf_bs_read_int_log(bs, 1, \"enable_warped_motion\");\n\t\tgf_bs_read_int_log(bs, 1, \"enable_dual_filter\");\n\t\tstate->enable_order_hint = gf_bs_read_int_log(bs, 1, \"enable_order_hint\");\n\t\tif (state->enable_order_hint) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"enable_jnt_comp\");\n\t\t\tstate->enable_ref_frame_mvs = gf_bs_read_int_log(bs, 1, \"enable_ref_frame_mvs\");\n\t\t}\n\t\telse {\n\t\t\t/*enable_jnt_comp = 0*/;\n\t\t\t/*enable_ref_frame_mvs = 0*/;\n\t\t}\n\t\tseq_choose_screen_content_tools = gf_bs_read_int_log(bs, 1, \"seq_choose_screen_content_tools\");\n\t\tstate->seq_force_screen_content_tools = 0;\n\t\tif (seq_choose_screen_content_tools) {\n\t\t\tstate->seq_force_screen_content_tools = 2/*SELECT_SCREEN_CONTENT_TOOLS*/;\n\t\t}\n\t\telse {\n\t\t\tstate->seq_force_screen_content_tools = gf_bs_read_int_log(bs, 1, \"seq_force_screen_content_tools\");\n\t\t}",
"\t\tstate->seq_force_integer_mv = 0;\n\t\tif (state->seq_force_screen_content_tools > 0) {\n\t\t\tconst Bool seq_choose_integer_mv = gf_bs_read_int_log(bs, 1, \"seq_choose_integer_mv\");\n\t\t\tif (seq_choose_integer_mv) {\n\t\t\t\tstate->seq_force_integer_mv = 2/*SELECT_INTEGER_MV*/;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate->seq_force_integer_mv = gf_bs_read_int_log(bs, 1, \"seq_force_integer_mv\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tstate->seq_force_integer_mv = 2/*SELECT_INTEGER_MV*/;\n\t\t}\n\t\tif (state->enable_order_hint) {\n\t\t\tu8 order_hint_bits_minus_1 = gf_bs_read_int_log(bs, 3, \"order_hint_bits_minus1\");\n\t\t\tstate->OrderHintBits = order_hint_bits_minus_1 + 1;\n\t\t}\n\t\telse {\n\t\t\tstate->OrderHintBits = 0;\n\t\t}\n\t}",
"\tstate->enable_superres = gf_bs_read_int_log(bs, 1, \"enable_superres\");\n\tstate->enable_cdef = gf_bs_read_int_log(bs, 1, \"enable_cdef\");\n\tstate->enable_restoration = gf_bs_read_int_log(bs, 1, \"enable_restoration\");\n\tav1_color_config(bs, state);\n\tstate->film_grain_params_present = gf_bs_read_int_log(bs, 1, \"film_grain_params_present\");\n}",
"",
"#define IVF_FILE_HEADER_SIZE 32",
"Bool gf_media_probe_ivf(GF_BitStream *bs)\n{\n\tu32 dw = 0;\n\tif (gf_bs_available(bs) < IVF_FILE_HEADER_SIZE) return GF_FALSE;",
"\tdw = gf_bs_peek_bits(bs, 32, 0);\n\tif (dw != GF_4CC('D', 'K', 'I', 'F')) {\n\t\treturn GF_FALSE;\n\t}\n\treturn GF_TRUE;\n}",
"GF_Err gf_media_parse_ivf_file_header(GF_BitStream *bs, u32 *width, u32 *height, u32 *codec_fourcc, u32 *timebase_num, u32 *timebase_den, u32 *num_frames)\n{\n\tu32 dw = 0;",
"\tif (!width || !height || !codec_fourcc || !timebase_den || !timebase_num || !num_frames) {\n\t\tassert(0);\n\t\treturn GF_BAD_PARAM;\n\t}",
"\tif (gf_bs_available(bs) < IVF_FILE_HEADER_SIZE) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[IVF] Not enough bytes available (\"LLU\").\\n\", gf_bs_available(bs)));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\tdw = gf_bs_read_u32(bs);\n\tif (dw != GF_4CC('D', 'K', 'I', 'F')) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CODING, (\"[IVF] Invalid signature\\n\"));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\tdw = gf_bs_read_u16_le(bs);\n\tif (dw != 0) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[IVF] Wrong IVF version. 0 expected, got %u\\n\", dw));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\tdw = gf_bs_read_u16_le(bs); //length of header in bytes\n\tif (dw != IVF_FILE_HEADER_SIZE) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[IVF] Wrong IVF header length. Expected 32 bytes, got %u\\n\", dw));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\t*codec_fourcc = gf_bs_read_u32(bs);",
"\t*width = gf_bs_read_u16_le(bs);\n\t*height = gf_bs_read_u16_le(bs);",
"\t*timebase_num = gf_bs_read_u32_le(bs);\n\t*timebase_den = gf_bs_read_u32_le(bs);",
"\t*num_frames = gf_bs_read_u32_le(bs);\n\tgf_bs_read_u32_le(bs); //skip unused",
"\treturn GF_OK;\n}",
"GF_Err gf_media_parse_ivf_frame_header(GF_BitStream *bs, u64 *frame_size, u64 *pts)\n{\n\tif (!frame_size) return GF_BAD_PARAM;\n\tif (gf_bs_available(bs) < 12)\n\t\treturn GF_BUFFER_TOO_SMALL;",
"\t*frame_size = gf_bs_read_u32_le(bs);\n\tif (*frame_size > 256 * 1024 * 1024) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[IVF] Wrong frame size %u\\n\", *frame_size));\n\t\t*frame_size = 0;\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\t*pts = gf_bs_read_u64_le(bs);",
"\treturn GF_OK;\n}",
"GF_Err gf_media_vp9_parse_superframe(GF_BitStream *bs, u64 ivf_frame_size, u32 *num_frames_in_superframe, u32 frame_sizes[VP9_MAX_FRAMES_IN_SUPERFRAME], u32 *superframe_index_size)\n{\n\tu32 byte, bytes_per_framesize;\n\tu64 pos = gf_bs_get_position(bs), i = 0;\n\tGF_Err e;",
"\tassert(bs && num_frames_in_superframe);",
"\t/*initialize like there is no superframe*/\n\tmemset(frame_sizes, 0, VP9_MAX_FRAMES_IN_SUPERFRAME * sizeof(frame_sizes[0]));\n\t*num_frames_in_superframe = 1;\n\tframe_sizes[0] = (u32)ivf_frame_size;\n\t*superframe_index_size = 0;",
"\te = gf_bs_seek(bs, pos + ivf_frame_size - 1);\n\tif (e) return e;",
"\tbyte = gf_bs_read_u8(bs);\n\tif ((byte & 0xe0) != 0xc0)\n\t\tgoto exit; /*no superframe*/",
"\tbytes_per_framesize = 1 + ((byte & 0x18) >> 3);\n\t*num_frames_in_superframe = (u32)(1 + (byte & 0x7));",
"\t/*superframe_index()*/\n\t*superframe_index_size = 2 + bytes_per_framesize * *num_frames_in_superframe;\n\tgf_bs_seek(bs, pos + ivf_frame_size - *superframe_index_size);\n\tbyte = gf_bs_read_u8(bs);\n\tif ((byte & 0xe0) != 0xc0)\n\t\tgoto exit; /*no superframe*/",
"\tframe_sizes[0] = 0;\n\tfor (i = 0; i < *num_frames_in_superframe; ++i) {\n\t\tgf_bs_read_data(bs, (char*)(frame_sizes + i), bytes_per_framesize);\n\t}",
"exit:\n\tgf_bs_seek(bs, pos);\n\treturn e;\n}",
"\nstatic Bool vp9_frame_sync_code(GF_BitStream *bs)\n{\n\tu8 val = gf_bs_read_int_log(bs, 8, \"syncbyte1\");\n\tif (val != 0x49)\n\t\treturn GF_FALSE;",
"\tval = gf_bs_read_int_log(bs, 8, \"syncbyte2\");\n\tif (val != 0x83)\n\t\treturn GF_FALSE;",
"\tval = gf_bs_read_int_log(bs, 8, \"syncbyte3\");\n\tif (val != 0x42)\n\t\treturn GF_FALSE;",
"\treturn GF_TRUE;\n}",
"typedef enum {\n\tCS_UNKNOWN = 0,\n\tCS_BT_601 = 1,\n\tCS_BT_709 = 2,\n\tCS_SMPTE_170 = 3,\n\tCS_SMPTE_240 = 4,\n\tCS_BT_2020 = 5,\n\tCS_RESERVED = 6,\n\tCS_RGB = 7,\n} VP9_color_space;",
"static const int VP9_CS_to_23001_8_colour_primaries[] = { -1/*undefined*/, 5, 1, 6, 7, 9, -1/*reserved*/, 1 };\nstatic const int VP9_CS_to_23001_8_transfer_characteristics[] = { -1/*undefined*/, 5, 1, 6, 7, 9, -1/*reserved*/, 13 };\nstatic const int VP9_CS_to_23001_8_matrix_coefficients[] = { -1/*undefined*/, 6, 1, -1, -1, 9, -1/*reserved*/, 0 };",
"static GF_Err vp9_color_config(GF_BitStream *bs, GF_VPConfig *vp9_cfg)\n{\n\tVP9_color_space color_space;",
"\tif (vp9_cfg->profile >= 2) {\n\t\tBool ten_or_twelve_bit = gf_bs_read_int_log(bs, 1, \"ten_or_twelve_bit\");\n\t\tvp9_cfg->bit_depth = ten_or_twelve_bit ? 12 : 10;\n\t}\n\telse {\n\t\tvp9_cfg->bit_depth = 8;\n\t}",
"\tcolor_space = gf_bs_read_int_log(bs, 3, \"color_space\");\n\tvp9_cfg->colour_primaries = VP9_CS_to_23001_8_colour_primaries[color_space];\n\tvp9_cfg->transfer_characteristics = VP9_CS_to_23001_8_transfer_characteristics[color_space];\n\tvp9_cfg->matrix_coefficients = VP9_CS_to_23001_8_matrix_coefficients[color_space];\n\tif (color_space != CS_RGB) {\n\t\tvp9_cfg->video_fullRange_flag = gf_bs_read_int_log(bs, 1, \"video_fullRange_flag\");\n\t\tif (vp9_cfg->profile == 1 || vp9_cfg->profile == 3) {\n\t\t\tu8 subsampling_x, subsampling_y, subsampling_xy_to_chroma_subsampling[2][2] = { {3, 0}, {2, 0} };\n\t\t\tsubsampling_x = gf_bs_read_int_log(bs, 1, \"subsampling_x\");\n\t\t\tsubsampling_y = gf_bs_read_int_log(bs, 1, \"subsampling_x\");\n\t\t\tvp9_cfg->chroma_subsampling = subsampling_xy_to_chroma_subsampling[subsampling_x][subsampling_y];\n\t\t\tBool reserved_zero = gf_bs_read_int_log(bs, 1, \"reserved_zero\");\n\t\t\tif (reserved_zero) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VP9] color config reserved zero (1) is not zero.\\n\"));\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tvp9_cfg->chroma_subsampling = 0;\n\t\t}\n\t}\n\telse {\n\t\tvp9_cfg->video_fullRange_flag = GF_TRUE;\n\t\tif (vp9_cfg->profile == 1 || vp9_cfg->profile == 3) {\n\t\t\tvp9_cfg->chroma_subsampling = 3;\n\t\t\tBool reserved_zero = gf_bs_read_int_log(bs, 1, \"reserved_zero\");\n\t\t\tif (reserved_zero) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VP9] color config reserved zero (2) is not zero.\\n\"));\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t}\n\t}",
"\treturn GF_OK;\n}",
"static void vp9_compute_image_size(int FrameWidth, int FrameHeight, int *Sb64Cols, int *Sb64Rows)\n{\n\tint MiCols = (FrameWidth + 7) >> 3;\n\tint MiRows = (FrameHeight + 7) >> 3;\n\t*Sb64Cols = (MiCols + 7) >> 3;\n\t*Sb64Rows = (MiRows + 7) >> 3;\n}",
"static void vp9_frame_size(GF_BitStream *bs, int *FrameWidth, int *FrameHeight, int *Sb64Cols, int *Sb64Rows)\n{\n\tint frame_width_minus_1 = gf_bs_read_int_log(bs, 16, \"frame_width_minus_1\");\n\tint frame_height_minus_1 = gf_bs_read_int_log(bs, 16, \"frame_height_minus_1\");\n\tif (frame_width_minus_1 + 1 != *FrameWidth || frame_height_minus_1 + 1 != *FrameHeight) {\n\t\tif (*FrameWidth || *FrameHeight)\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[VP9] inconsistent frame dimensions: previous was %dx%d, new one is %dx%d.\\n\", *FrameWidth, *FrameHeight, frame_width_minus_1 + 1, frame_height_minus_1 + 1));\n\t}\n\t*FrameWidth = frame_width_minus_1 + 1;\n\t*FrameHeight = frame_height_minus_1 + 1;\n\tvp9_compute_image_size(*FrameWidth, *FrameHeight, Sb64Cols, Sb64Rows);\n}",
"static void vp9_render_size(GF_BitStream *bs, int FrameWidth, int FrameHeight, int *renderWidth, int *renderHeight)\n{\n\tBool render_and_frame_size_different = gf_bs_read_int_log(bs, 1, \"render_and_frame_size_different\");\n\tif (render_and_frame_size_different == 1) {\n\t\tint render_width_minus_1 = gf_bs_read_int_log(bs, 16, \"render_width_minus_1\");\n\t\tint render_height_minus_1 = gf_bs_read_int_log(bs, 16, \"render_height_minus_1\");\n\t\t*renderWidth = render_width_minus_1 + 1;\n\t\t*renderHeight = render_height_minus_1 + 1;\n\t}\n\telse {\n\t\t*renderWidth = FrameWidth;\n\t\t*renderHeight = FrameHeight;\n\t}\n}",
"static s64 vp9_s(GF_BitStream *bs, int n, const char *fname, u32 idx) {\n\ts64 value = gf_bs_read_int(bs, n);\n\tBool sign = gf_bs_read_int(bs, 1);\n\tif (sign) value = -value;\n\tgf_bs_log_idx(bs, n+1, fname, value, idx, -1, -1);\n\treturn value;\n}",
"static void vp9_loop_filter_params(GF_BitStream *bs)\n{\n\t/*loop_filter_level = */gf_bs_read_int_log(bs, 6, \"loop_filter_level\");\n\t/*loop_filter_sharpness = */gf_bs_read_int_log(bs, 3, \"loop_filter_sharpness\");\n\tBool loop_filter_delta_enabled = gf_bs_read_int_log(bs, 1, \"loop_filter_delta_enabled\");\n\tif (loop_filter_delta_enabled == 1) {\n\t\tBool loop_filter_delta_update = gf_bs_read_int_log(bs, 1, \"loop_filter_delta_update\");\n\t\tif (loop_filter_delta_update == GF_TRUE) {\n\t\t\tint i;\n\t\t\tfor (i = 0; i < 4; i++) {\n\t\t\t\tBool update_ref_delta = gf_bs_read_int_log_idx(bs, 1, \"update_ref_delta\", i);\n\t\t\t\tif (update_ref_delta == GF_TRUE)\n\t\t\t\t\tvp9_s(bs, 6, \"loop_filter_ref_deltas\", i);\n\t\t\t}\n\t\t\tfor (i = 0; i < 2; i++) {\n\t\t\t\tBool update_mode_delta = gf_bs_read_int_log_idx(bs, 1, \"update_mode_delta\", i);\n\t\t\t\tif (update_mode_delta == GF_TRUE)\n\t\t\t\t\tvp9_s(bs, 6, \"loop_filter_mode_deltas\", i);\n\t\t\t}\n\t\t}\n\t}\n}",
"static void vp9_quantization_params(GF_BitStream *bs)\n{\n\t/*base_q_idx = */gf_bs_read_int_log(bs, 8, \"base_q_idx\");\n}",
"#define VP9_MAX_SEGMENTS 8\n#define VP9_SEG_LVL_MAX 4\nstatic const int segmentation_feature_bits[VP9_SEG_LVL_MAX] = { 8, 6, 2, 0 };\nstatic const int segmentation_feature_signed[VP9_SEG_LVL_MAX] = { 1, 1, 0, 0 };",
"#define VP9_MIN_TILE_WIDTH_B64 4\n#define VP9_MAX_TILE_WIDTH_B64 64",
"static void vp9_segmentation_params(GF_BitStream *bs)\n{\n\tBool segmentation_enabled = gf_bs_read_int_log(bs, 1, \"segmentation_enabled\");\n\tif (segmentation_enabled == 1) {\n\t\tint i;\n\t\tBool segmentation_update_map = gf_bs_read_int_log(bs, 1, \"segmentation_update_map\");\n\t\tif (segmentation_update_map) {\n\t\t\tfor (i = 0; i < 7; i++)\n\t\t\t\t/*segmentation_tree_probs[i] = read_prob()*/\n\t\t\t\t/*segmentation_temporal_update = */gf_bs_read_int_log(bs, 1, \"segmentation_temporal_update\");\n\t\t\t/*for (i = 0; i < 3; i++)\n\t\t\t\tsegmentation_pred_prob[i] = segmentation_temporal_update ? read_prob() : 255*/\n\t\t}\n\t\tBool segmentation_update_data = gf_bs_read_int_log(bs, 1, \"segmentation_update_data\");\n\t\tif (segmentation_update_data == 1) {\n\t\t\t/*segmentation_abs_or_delta_update =*/ gf_bs_read_int_log(bs, 1, \"segmentation_abs_or_delta_update\");\n\t\t\tfor (i = 0; i < VP9_MAX_SEGMENTS; i++) {\n\t\t\t\tint j;\n\t\t\t\tfor (j = 0; j < VP9_SEG_LVL_MAX; j++) {\n\t\t\t\t\t/*feature_value = 0*/\n\t\t\t\t\tBool feature_enabled = gf_bs_read_int_log(bs, 1, \"feature_enabled\");\n\t\t\t\t\t/*FeatureEnabled[i][j] = feature_enabled*/\n\t\t\t\t\tif (feature_enabled) {\n\t\t\t\t\t\tint bits_to_read = segmentation_feature_bits[j];\n\t\t\t\t\t\t/*feature_value =*/ gf_bs_read_int_log(bs, bits_to_read, \"feature_value\");\n\t\t\t\t\t\tif (segmentation_feature_signed[j] == 1) {\n\t\t\t\t\t\t\t/*Bool feature_sign = */gf_bs_read_int_log(bs, 1, \"feature_sign\");\n\t\t\t\t\t\t\t/*if (feature_sign == 1)\n\t\t\t\t\t\t\t\tfeature_value *= -1*/\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t/*FeatureData[i][j] = feature_value*/\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"static int calc_min_log2_tile_cols(int Sb64Cols) {\n\tint minLog2 = 0;\n\twhile ((VP9_MAX_TILE_WIDTH_B64 << minLog2) < Sb64Cols)\n\t\tminLog2++;",
"\treturn minLog2;\n}",
"static int calc_max_log2_tile_cols(int Sb64Cols) {\n\tint maxLog2 = 1;\n\twhile ((Sb64Cols >> maxLog2) >= VP9_MIN_TILE_WIDTH_B64)\n\t\tmaxLog2++;",
"\treturn maxLog2 - 1;\n}",
"static void vp9_tile_info(GF_BitStream *bs, int Sb64Cols)\n{\n\tBool tile_rows_log2;\n\tint minLog2TileCols = calc_min_log2_tile_cols(Sb64Cols);\n\tint maxLog2TileCols = calc_max_log2_tile_cols(Sb64Cols);\n\tint tile_cols_log2 = minLog2TileCols;\n\twhile (tile_cols_log2 < maxLog2TileCols) {\n\t\tBool increment_tile_cols_log2 = gf_bs_read_int_log(bs, 1, \"increment_tile_cols_log2\");\n\t\tif (increment_tile_cols_log2)\n\t\t\ttile_cols_log2++;\n\t\telse\n\t\t\tbreak;\n\t}\n\ttile_rows_log2 = gf_bs_read_int_log(bs, 1, \"tile_rows_log2\");\n\tif (tile_rows_log2) {\n\t\t/*Bool increment_tile_rows_log2 = */gf_bs_read_int_log(bs, 1, \"increment_tile_rows_log2\");\n\t\t//tile_rows_log2 += increment_tile_rows_log2;\n\t}\n}",
"static void vp9_frame_size_with_refs(GF_BitStream *bs, u8 refresh_frame_flags, u8 * ref_frame_idx, int * RefFrameWidth, int *RefFrameHeight,\n\tint *FrameWidth, int *FrameHeight, int *RenderWidth, int *RenderHeight, int *Sb64Cols, int *Sb64Rows)\n{\n\tBool found_ref;\n\tint i;\n\tfor (i = 0; i < 3; i++) {\n\t\tfound_ref = gf_bs_read_int_log(bs, 1, \"found_ref\");\n\t\tif (found_ref) {\n\t\t\t*FrameWidth = RefFrameWidth [ref_frame_idx[i]];\n\t\t\t*FrameHeight = RefFrameHeight[ref_frame_idx[i]];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (found_ref == 0) {\n\t\tvp9_frame_size(bs, FrameWidth, FrameHeight, Sb64Cols, Sb64Rows);\n\t}\n\telse {\n\t\tvp9_compute_image_size(*FrameWidth, *FrameHeight, Sb64Cols, Sb64Rows);\n\t}",
"\tvp9_render_size(bs, *FrameWidth, *FrameHeight, RenderWidth, RenderHeight);\n}",
"static void vp9_read_interpolation_filter(GF_BitStream *bs)\n{\n\tBool is_filter_switchable = gf_bs_read_int_log(bs, 1, \"is_filter_switchable\");\n\tif (!is_filter_switchable) {\n\t\t/*raw_interpolation_filter = */gf_bs_read_int_log(bs, 2, \"raw_interpolation_filter\");\n\t}\n}",
"\n#define VP9_KEY_FRAME 0",
"GF_Err gf_media_vp9_parse_sample(GF_BitStream *bs, GF_VPConfig *vp9_cfg, Bool *key_frame, u32 *FrameWidth, u32 *FrameHeight, u32 *renderWidth, u32 *renderHeight)\n{\n\tBool FrameIsIntra = GF_FALSE, profile_low_bit, profile_high_bit, show_existing_frame = GF_FALSE, frame_type = GF_FALSE, show_frame = GF_FALSE, error_resilient_mode = GF_FALSE;\n\t/*u8 frame_context_idx = 0, reset_frame_context = 0, frame_marker = 0*/;\n\tint Sb64Cols = 0, Sb64Rows = 0, i;\n\tu8 refresh_frame_flags = 0;",
"\tassert(bs && key_frame);",
"\t/*uncompressed header*/\n\t/*frame_marker = */gf_bs_read_int_log(bs, 2, \"frame_marker\");\n\tprofile_low_bit = gf_bs_read_int_log(bs, 1, \"profile_low_bit\");\n\tprofile_high_bit = gf_bs_read_int_log(bs, 1, \"profile_high_bit\");\n\tvp9_cfg->profile = (profile_high_bit << 1) + profile_low_bit;\n\tif (vp9_cfg->profile == 3) {\n\t\tBool reserved_zero = gf_bs_read_int_log(bs, 1, \"reserved_zero\");\n\t\tif (reserved_zero) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VP9] uncompressed header reserved zero is not zero.\\n\"));\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t}",
"\tshow_existing_frame = gf_bs_read_int_log(bs, 1, \"show_existing_frame\");\n\tif (show_existing_frame == GF_TRUE) {\n\t\t/*frame_to_show_map_idx = */gf_bs_read_int_log(bs, 3, \"frame_to_show_map_idx\");\n\t\treturn GF_OK;\n\t}",
"\tframe_type = gf_bs_read_int_log(bs, 1, \"frame_type\");\n\tshow_frame = gf_bs_read_int_log(bs, 1, \"show_frame\");\n\terror_resilient_mode = gf_bs_read_int_log(bs, 1, \"error_resilient_mode\");\n\tif (frame_type == VP9_KEY_FRAME) {\n\t\tif (!vp9_frame_sync_code(bs))\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\tif (vp9_color_config(bs, vp9_cfg) != GF_OK)\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\tvp9_frame_size(bs, FrameWidth, FrameHeight, &Sb64Cols, &Sb64Rows);\n\t\tvp9_render_size(bs, *FrameWidth, *FrameHeight, renderWidth, renderHeight);\n\t\trefresh_frame_flags = 0xFF;\n\t\t*key_frame = GF_TRUE;\n\t\tFrameIsIntra = GF_TRUE;\n\t}\n\telse {\n\t\tBool intra_only = GF_FALSE;\n\t\t*key_frame = GF_FALSE;",
"\t\tif (show_frame == GF_FALSE) {\n\t\t\tintra_only = gf_bs_read_int_log(bs, 1, \"intra_only\");\n\t\t}\n\t\tFrameIsIntra = intra_only;",
"\t\tif (error_resilient_mode == GF_FALSE) {\n\t\t\t/*reset_frame_context = */gf_bs_read_int_log(bs, 2, \"reset_frame_context\");\n\t\t}",
"\t\tif (intra_only == GF_TRUE) {\n\t\t\tif (!vp9_frame_sync_code(bs))\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;",
"\t\t\tif (vp9_cfg->profile > 0) {\n\t\t\t\tif (vp9_color_config(bs, vp9_cfg) != GF_OK)\n\t\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tu8 color_space = CS_BT_601;\n\t\t\t\tvp9_cfg->colour_primaries = VP9_CS_to_23001_8_colour_primaries[color_space];\n\t\t\t\tvp9_cfg->transfer_characteristics = VP9_CS_to_23001_8_transfer_characteristics[color_space];\n\t\t\t\tvp9_cfg->matrix_coefficients = VP9_CS_to_23001_8_matrix_coefficients[color_space];\n\t\t\t\tvp9_cfg->chroma_subsampling = 0;\n\t\t\t\tvp9_cfg->bit_depth = 8;\n\t\t\t}\n\t\t\trefresh_frame_flags = gf_bs_read_int_log(bs, 8, \"refresh_frame_flags\");\n\t\t\tvp9_frame_size(bs, FrameWidth, FrameHeight, &Sb64Cols, &Sb64Rows);\n\t\t\tvp9_render_size(bs, *FrameWidth, *FrameHeight, renderWidth, renderHeight);\n\t\t}\n\t\telse {\n\t\t\trefresh_frame_flags = gf_bs_read_int_log(bs, 8, \"refresh_frame_flags\");\n\t\t\tu8 ref_frame_idx[3];\n\t\t\tfor (i = 0; i < 3; i++) {\n\t\t\t\tref_frame_idx[i] = gf_bs_read_int_log_idx(bs, 3, \"ref_frame_idx\", i);\n\t\t\t\t/*ref_frame_sign_bias[LAST_FRAME + i] = */gf_bs_read_int_log_idx(bs, 1, \"ref_frame_sign_bias\", i);\n\t\t\t}\n\t\t\tvp9_frame_size_with_refs(bs, refresh_frame_flags, ref_frame_idx, vp9_cfg->RefFrameWidth, vp9_cfg->RefFrameHeight, FrameWidth, FrameHeight, renderWidth, renderHeight, &Sb64Cols, &Sb64Rows);\n\t\t\t/*allow_high_precision_mv = */gf_bs_read_int_log(bs, 1, \"allow_high_precision_mv\");\n\t\t\tvp9_read_interpolation_filter(bs);\n\t\t}\n\t}",
"\tif (error_resilient_mode == 0) {\n\t\t/*refresh_frame_context = */gf_bs_read_int_log(bs, 1, \"refresh_frame_context\");\n\t\t/*frame_parallel_decoding_mode = */gf_bs_read_int_log(bs, 1, \"frame_parallel_decoding_mode\");\n\t}",
"\t/*frame_context_idx = */gf_bs_read_int_log(bs, 2, \"frame_context_idx\");\n\tif (FrameIsIntra || error_resilient_mode) {\n\t\t/*setup_past_independence + save_probs ...*/\n\t\t//frame_context_idx = 0;\n\t}",
"\tvp9_loop_filter_params(bs);\n\tvp9_quantization_params(bs);\n\tvp9_segmentation_params(bs);\n\tvp9_tile_info(bs, Sb64Cols);",
"\t/*header_size_in_bytes = */gf_bs_read_int_log(bs, 16, \"header_size_in_bytes\");",
"\t/*Reference frame update process (8.10 - partial)*/\n\tfor (i = 0; i < VP9_NUM_REF_FRAMES; i++) {\n\t\tif ((refresh_frame_flags >> i) & 1) {\n\t\t\tvp9_cfg->RefFrameWidth[i] = *FrameWidth;\n\t\t\tvp9_cfg->RefFrameHeight[i] = *FrameHeight;\n\t\t}\n\t}",
"\treturn GF_OK;\n}",
"GF_Err gf_av1_parse_obu_header(GF_BitStream *bs, ObuType *obu_type, Bool *obu_extension_flag, Bool *obu_has_size_field, u8 *temporal_id, u8 *spatial_id)\n{\n\tBool forbidden = gf_bs_read_int(bs, 1);\n\tif (forbidden) {\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\t*obu_type = gf_bs_read_int(bs, 4);\n\t*obu_extension_flag = gf_bs_read_int(bs, 1);\n\t*obu_has_size_field = gf_bs_read_int(bs, 1);\n\tif (gf_bs_read_int(bs, 1) /*obu_reserved_1bit*/) {\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\tif (*obu_extension_flag) {\n\t\t*temporal_id = gf_bs_read_int(bs, 3);\n\t\t*spatial_id = gf_bs_read_int(bs, 2);\n\t\t/*extension_header_reserved_3bits = */gf_bs_read_int(bs, 3);\n\t}",
"\treturn GF_OK;\n}",
"#endif // GPAC_DISABLE_AV_PARSERS",
"GF_EXPORT\nconst char *gf_av1_get_obu_name(ObuType obu_type)\n{\n\tswitch (obu_type) {\n\tcase OBU_SEQUENCE_HEADER: return \"seq_header\";\n\tcase OBU_TEMPORAL_DELIMITER: return \"delimiter\";\n\tcase OBU_FRAME_HEADER: return \"frame_header\";\n\tcase OBU_TILE_GROUP: return \"tile_group\";\n\tcase OBU_METADATA: return \"metadata\";\n\tcase OBU_FRAME: return \"frame\";\n\tcase OBU_REDUNDANT_FRAME_HEADER: return \"redundant_frame_header\";\n\tcase OBU_TILE_LIST: return \"tile_list\";\n\tcase OBU_PADDING: return \"padding\";\n\tcase OBU_RESERVED_0:\n\tcase OBU_RESERVED_9:\n\tcase OBU_RESERVED_10:\n\tcase OBU_RESERVED_11:\n\tcase OBU_RESERVED_12:\n\tcase OBU_RESERVED_13:\n\tcase OBU_RESERVED_14:\n\t\treturn \"reserved\";\n\tdefault: return \"unknown\";\n\t}\n}",
"Bool av1_is_obu_header(ObuType obu_type) {\n\tswitch (obu_type) {\n\tcase OBU_SEQUENCE_HEADER:\n\tcase OBU_METADATA:\n\t\t// TODO add check based on the metadata type\n\t\treturn GF_TRUE;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n}",
"#ifndef GPAC_DISABLE_AV_PARSERS",
"static Bool av1_is_obu_frame(AV1State *state, ObuType obu_type)\n{\n\tswitch (obu_type) {\n\tcase OBU_PADDING:\n\tcase OBU_REDUNDANT_FRAME_HEADER:\n\t\treturn GF_FALSE;\n\tcase OBU_TEMPORAL_DELIMITER:\n\t\treturn state->keep_temporal_delim ? GF_TRUE : GF_FALSE;\n\tdefault:\n\t\treturn GF_TRUE;\n\t}\n}",
"u64 gf_av1_leb128_read(GF_BitStream *bs, u8 *opt_Leb128Bytes) {\n\tu64 value = 0;\n\tu8 Leb128Bytes = 0, i = 0;\n\tfor (i = 0; i < 8; i++) {\n\t\tu8 leb128_byte = gf_bs_read_u8(bs);\n\t\tvalue |= ( ((u64) (leb128_byte & 0x7f)) << (i * 7));\n\t\tLeb128Bytes += 1;\n\t\tif (!(leb128_byte & 0x80)) {\n\t\t\tbreak;\n\t\t}\n\t}",
"\tif (opt_Leb128Bytes) {\n\t\t*opt_Leb128Bytes = Leb128Bytes;\n\t}\n\treturn value;\n}",
"u32 gf_av1_leb128_size(u64 value)\n{\n\tu32 gf_av1_leb128_size = 0;\n\tdo {\n\t\t++gf_av1_leb128_size;\n\t} while ((value >>= 7) != 0);",
"\treturn gf_av1_leb128_size;\n}",
"u64 gf_av1_leb128_write(GF_BitStream *bs, u64 value)\n{\n\tu32 i, leb_size = gf_av1_leb128_size(value);\n\tfor (i = 0; i < leb_size; ++i) {\n\t\tu8 byte = value & 0x7f;\n\t\tvalue >>= 7;\n\t\tif (value != 0) byte |= 0x80; //more bytes follow\n\t\tgf_bs_write_u8(bs, byte);\n\t}",
"\treturn leb_size;\n}",
"#define OBU_BLOCK_SIZE 4096\nstatic void av1_add_obu_internal(GF_BitStream *bs, u64 pos, u64 obu_length, ObuType obu_type, GF_List **obu_list, AV1State *state)\n{\n\tchar block[OBU_BLOCK_SIZE];\n\tBool has_size_field = 0, obu_extension_flag = 0;\n\tu8 temporal_id, spatial_id;\n\tGF_AV1_OBUArrayEntry *a = NULL;",
"\tif (state && state->mem_mode) {\n\t\tif (!state->bs) state->bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\t\telse gf_bs_reassign_buffer(state->bs, state->frame_obus, state->frame_obus_alloc);\n\t}\n\telse {\n\t\tGF_SAFEALLOC(a, GF_AV1_OBUArrayEntry);\n\t\tif (!a) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[AV1] Failed to allocate OBU\\n\"));\n\t\t\treturn;\n\t\t}\n\t}",
"\tgf_bs_seek(bs, pos);\n\tgf_av1_parse_obu_header(bs, &obu_type, &obu_extension_flag, &has_size_field, &temporal_id, &spatial_id);\n\tgf_bs_seek(bs, pos);",
"\tif (has_size_field) {\n\t\tif (a) {\n\t\t\ta->obu = gf_malloc((size_t)obu_length);\n\t\t\tgf_bs_read_data(bs, a->obu, (u32)obu_length);\n\t\t\ta->obu_length = obu_length;\n\t\t}\n\t\telse {\n\t\t\tu32 remain = (u32)obu_length;\n\t\t\twhile (remain) {\n\t\t\t\tu32 block_size = OBU_BLOCK_SIZE;\n\t\t\t\tif (block_size > remain) block_size = remain;\n\t\t\t\tgf_bs_read_data(bs, block, block_size);\n\t\t\t\tgf_bs_write_data(state->bs, block, block_size);\n\t\t\t\tremain -= block_size;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t}\n\telse {\n\t\tu8 i, hdr_size = obu_extension_flag ? 2 : 1;\n\t\tconst u32 leb_size = (u32)gf_av1_leb128_size(obu_length);\n\t\tconst u64 obu_size = obu_length - hdr_size;",
"\t\tif (a) {\n\t\t\ta->obu = gf_malloc((size_t)obu_length + leb_size);\n\t\t\ta->obu_length = obu_length + leb_size;\n\t\t\tfor (i = 0; i < hdr_size; ++i) {\n\t\t\t\ta->obu[i] = gf_bs_read_u8(bs);\n\t\t\t\t/*add size field flag*/\n\t\t\t\tif (i == 0) a->obu[0] |= 0x02;\n\t\t\t}\n\t\t\t{\n\t\t\t\tu32 out_size = 0;\n\t\t\t\tu8 *output = NULL;\n\t\t\t\tGF_BitStream *bsLeb128 = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\t\t\t\t/*write size field*/\n\t\t\t\tgf_av1_leb128_write(bsLeb128, obu_size);\n\t\t\t\tassert(gf_bs_get_position(bsLeb128) == leb_size);\n\t\t\t\tgf_bs_get_content(bsLeb128, &output, &out_size);\n\t\t\t\tgf_bs_del(bsLeb128);\n\t\t\t\tmemcpy(a->obu + hdr_size, output, out_size);\n\t\t\t\tgf_free(output);\n\t\t\t}\n\t\t\tgf_bs_read_data(bs, a->obu + hdr_size + leb_size, (u32)(obu_size));\n\t\t\tassert(gf_bs_get_position(bs) == pos + obu_length);\n\t\t}\n\t\telse {\n\t\t\tu32 remain;\n\t\t\tfor (i = 0; i < hdr_size; ++i) {\n\t\t\t\tu8 hdr_b = gf_bs_read_u8(bs);\n\t\t\t\tif (i == 0) hdr_b |= 0x02; /*add size field flag*/\n\t\t\t\tgf_bs_write_u8(state->bs, hdr_b);\n\t\t\t}\n\t\t\t/*add size field */\n\t\t\tgf_av1_leb128_write(state->bs, obu_size);\n\t\t\tremain = (u32)obu_length - hdr_size;\n\t\t\twhile (remain) {\n\t\t\t\tu32 block_size = OBU_BLOCK_SIZE;\n\t\t\t\tif (block_size > remain) block_size = remain;\n\t\t\t\tgf_bs_read_data(bs, block, block_size);\n\t\t\t\tgf_bs_write_data(state->bs, block, block_size);\n\t\t\t\tremain -= block_size;\n\t\t\t}\n\t\t\tassert(gf_bs_get_position(bs) == pos + obu_length);\n\t\t\treturn;\n\t\t}\n\t}\n\tif (!obu_list) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[AV1] internal error, no OBU list cannot add\\n\"));\n\t\tgf_free(a->obu);\n\t\tgf_free(a);\n\t\treturn;\n\t}\n\ta->obu_type = obu_type;\n\tif (! *obu_list)\n\t\t*obu_list = gf_list_new();\n\tgf_list_add(*obu_list, a);\n}",
"static void av1_populate_state_from_obu(GF_BitStream *bs, u64 pos, u64 obu_length, ObuType obu_type, AV1State *state)\n{\n\tif (av1_is_obu_header(obu_type)) {\n\t\tav1_add_obu_internal(bs, pos, obu_length, obu_type, &state->frame_state.header_obus, NULL);\n\t}\n\tif (!state->skip_frames && av1_is_obu_frame(state, obu_type)) {\n\t\tif (!state->mem_mode) {\n\t\t\tav1_add_obu_internal(bs, pos, obu_length, obu_type, &state->frame_state.frame_obus, NULL);\n\t\t}\n\t\telse {\n\t\t\tav1_add_obu_internal(bs, pos, obu_length, obu_type, NULL, state);\n\t\t}\n\t}\n}",
"GF_Err aom_av1_parse_temporal_unit_from_section5(GF_BitStream *bs, AV1State *state)\n{\n\tif (!state) return GF_BAD_PARAM;\n\tstate->obu_type = -1;",
"\twhile (state->obu_type != OBU_TEMPORAL_DELIMITER) {\n\t\tGF_Err e;\n\t\tif (!gf_bs_available(bs))\n\t\t\treturn state->unframed ? GF_BUFFER_TOO_SMALL : GF_OK;",
"\t\tu64 pos = gf_bs_get_position(bs), obu_length = 0;",
"\t\te = gf_av1_parse_obu(bs, &state->obu_type, &obu_length, NULL, state);\n\t\tif (e)\n\t\t\treturn e;",
"\t\tif (obu_length != gf_bs_get_position(bs) - pos) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[AV1] OBU (Section 5) frame size \"LLU\" different from consumed bytes \"LLU\".\\n\", obu_length, gf_bs_get_position(bs) - pos));\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}",
"\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] Section5 OBU detected (size \"LLU\")\\n\", obu_length));\n\t\tav1_populate_state_from_obu(bs, pos, obu_length, state->obu_type, state);\n\t}",
"\treturn GF_OK;\n}",
"Bool gf_media_aom_probe_annexb(GF_BitStream *bs)\n{\n\tBool res = GF_TRUE;\n\tu64 init_pos = gf_bs_get_position(bs);\n\tu64 sz = gf_av1_leb128_read(bs, NULL);\n\tif (!sz) res = GF_FALSE;\n\twhile (sz > 0) {\n\t\tu8 Leb128Bytes = 0;\n\t\tu64 frame_unit_size = gf_av1_leb128_read(bs, &Leb128Bytes);",
"\t\tif (!frame_unit_size) {\n\t\t\tres = GF_FALSE;\n\t\t\tbreak;\n\t\t}",
"\t\tif (sz < Leb128Bytes + frame_unit_size) {\n\t\t\tres = GF_FALSE;\n\t\t\tbreak;\n\t\t}\n\t\tsz -= Leb128Bytes + frame_unit_size;",
"\t\twhile (frame_unit_size > 0) {\n\t\t\tObuType obu_type;\n\t\t\tu64 pos, obu_length = gf_av1_leb128_read(bs, &Leb128Bytes);\n\t\t\tif (frame_unit_size < Leb128Bytes + obu_length) {\n\t\t\t\tres = GF_FALSE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpos = gf_bs_get_position(bs);\n\t\t\tframe_unit_size -= Leb128Bytes;",
"\t\t\tu8 tid, sid;\n\t\t\tBool extflag, has_size;\n\t\t\tGF_Err e = gf_av1_parse_obu_header(bs, &obu_type, &extflag, &has_size, &tid, &sid);\n\t\t\tif (e) {\n\t\t\t\tres = GF_FALSE;\n\t\t\t\tbreak;\n\t\t\t}",
"\t\t\tif (has_size) {\n\t\t\t\tobu_length = (u32)gf_av1_leb128_read(bs, NULL);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (obu_length >= 1 + extflag) {\n\t\t\t\t\tobu_length = obu_length - 1 - extflag;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tres = GF_FALSE;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tu32 hdr_size = (u32)(gf_bs_get_position(bs) - pos);\n\t\t\tobu_length += hdr_size;",
"\t\t\tif (frame_unit_size < obu_length) {\n\t\t\t\tres = GF_FALSE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tframe_unit_size -= obu_length;\n\t\t\tgf_bs_skip_bytes(bs, obu_length - hdr_size);\n\t\t}\n\t\tif (!res) break;\n\t}\n\tgf_bs_seek(bs, init_pos);\n\treturn res;\n}",
"GF_Err aom_av1_parse_temporal_unit_from_annexb(GF_BitStream *bs, AV1State *state)\n{\n\tGF_Err e;\n\tu64 tupos;\n\tu64 tusize, sz;\n\tif (!bs || !state) return GF_BAD_PARAM;",
"\tstate->bs_overread = GF_FALSE;\n\ttusize = sz = gf_av1_leb128_read(bs, NULL);\n\ttupos = gf_bs_get_position(bs);\n\tif (!sz) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CODING, (\"[AV1] temporal unit size is 0, likely not annex B\\n\"));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}",
"\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] Annex B temporal unit detected (size \"LLU\") ***** \\n\", sz));\n\twhile (sz > 0) {\n\t\tu8 Leb128Bytes = 0;\n\t\tu64 frame_unit_size = gf_av1_leb128_read(bs, &Leb128Bytes);",
"\t\tif (state->bs_overread) {\n\t\t\treturn GF_BUFFER_TOO_SMALL;\n\t\t}\n\t\tif (sz < Leb128Bytes + frame_unit_size) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] Annex B sz(\"LLU\") < Leb128Bytes(\"LLU\") + frame_unit_size(\"LLU\")\\n\", sz, Leb128Bytes, frame_unit_size));\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] Annex B frame unit detected (size \"LLU\")\\n\", frame_unit_size));\n\t\tsz -= Leb128Bytes + frame_unit_size;",
"\t\twhile (frame_unit_size > 0) {\n\t\t\tu64 pos, obu_length = gf_av1_leb128_read(bs, &Leb128Bytes);",
"\t\t\tif (state->bs_overread) {\n\t\t\t\treturn GF_BUFFER_TOO_SMALL;\n\t\t\t}\n\t\t\tif (frame_unit_size < Leb128Bytes + obu_length) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] Annex B frame_unit_size(\"LLU\") < Leb128Bytes(\"LLU\") + obu_length(\"LLU\")\\n\", frame_unit_size, Leb128Bytes, obu_length));\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] Annex B OBU detected (size \"LLU\")\\n\", obu_length));\n\t\t\tpos = gf_bs_get_position(bs);\n\t\t\tframe_unit_size -= Leb128Bytes;",
"\t\t\te = gf_av1_parse_obu(bs, &state->obu_type, &obu_length, NULL, state);\n\t\t\tif (e) return e;",
"\t\t\tif (obu_length != gf_bs_get_position(bs) - pos) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[AV1] Annex B frame size \"LLU\" different from consumed bytes \"LLU\".\\n\", obu_length, gf_bs_get_position(bs) - pos));\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}",
"\t\t\tav1_populate_state_from_obu(bs, pos, obu_length, state->obu_type, state);\n\t\t\tif (frame_unit_size < obu_length) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] Annex B frame_unit_size(\"LLU\") < OBU size (\"LLU\")\\n\", frame_unit_size, obu_length));\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t\tframe_unit_size -= obu_length;\n\t\t}\n\t}\n\tassert(sz == 0);\n\tif (tusize != gf_bs_get_position(bs) - tupos) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[AV1] Annex B TU size \"LLU\" different from consumed bytes \"LLU\".\\n\", tusize, gf_bs_get_position(bs) - tupos));\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\treturn GF_OK;\n}",
"GF_Err aom_av1_parse_temporal_unit_from_ivf(GF_BitStream *bs, AV1State *state)\n{\n\tu64 frame_size, pts_ignored;\n\tGF_Err e;\n\tif (gf_bs_available(bs)<12) return GF_EOS;\n\te = gf_media_parse_ivf_frame_header(bs, &frame_size, &pts_ignored);\n\tif (e) return e;\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1] IVF frame detected (size \"LLU\")\\n\", frame_size));",
"\tif (gf_bs_available(bs) < frame_size) return GF_EOS;",
"\twhile (frame_size > 0) {\n\t\tu64 obu_size = 0, pos = gf_bs_get_position(bs);",
"\t\te = gf_av1_parse_obu(bs, &state->obu_type, &obu_size, NULL, state);\n\t\tif (e != GF_OK)\n\t\t\treturn e;",
"\t\tif (obu_size != gf_bs_get_position(bs) - pos) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[AV1] IVF frame size \"LLU\" different from consumed bytes \"LLU\".\\n\", obu_size, gf_bs_get_position(bs) - pos));\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}",
"\t\tav1_populate_state_from_obu(bs, pos, obu_size, state->obu_type, state);",
"\t\tframe_size -= obu_size;\n\t}\n\treturn GF_OK;\n}",
"#define AV1_NUM_REF_FRAMES 8\n#define AV1_ALL_FRAMES ((1 << AV1_NUM_REF_FRAMES) - 1)",
"#define AV1_SUPERRES_DENOM_MIN 9\n#define AV1_SUPERRES_DENOM_BITS 3\n#define AV1_SUPERRES_NUM 8",
"#define AV1_REFS_PER_FRAME 7\n#define AV1_PRIMARY_REF_NONE 7",
"#define MAX_TILE_WIDTH 4096\n#define MAX_TILE_AREA (4096 * 2304)",
"static u32 aom_av1_tile_log2(u32 blkSize, u32 target)\n{\n\tu32 k;\n\tfor (k = 0; (blkSize << k) < target; k++) {\n\t}\n\treturn k;\n}",
"static u64 aom_av1_le(GF_BitStream *bs, u32 n, const char *name) {\n\tu32 i = 0;\n\tu64 t = 0;\n\tfor (i = 0; i < n; i++) {\n\t\tu8 byte = gf_bs_read_int(bs, 8);\n\t\tt += (byte << (i * 8));\n\t}\n\tgf_bs_log(bs, n*8, name, t);\n\treturn t;\n}",
"\nstatic void av1_parse_tile_info(GF_BitStream *bs, AV1State *state)\n{\n\tu32 i;\n\tu32 MiCols = 2 * ((state->width + 7) >> 3);\n\tu32 MiRows = 2 * ((state->height + 7) >> 3);\n\tu32 sbCols = state->use_128x128_superblock ? ((MiCols + 31) >> 5) : ((MiCols + 15) >> 4);\n\tu32 sbRows = state->use_128x128_superblock ? ((MiRows + 31) >> 5) : ((MiRows + 15) >> 4);\n\tu32 sbShift = state->use_128x128_superblock ? 5 : 4;\n\tu32 sbSize = sbShift + 2;\n\tu32 maxTileWidthSb = MAX_TILE_WIDTH >> sbSize;\n\tu32 maxTileAreaSb = MAX_TILE_AREA >> (2 * sbSize);\n\tu32 minLog2tileCols = aom_av1_tile_log2(maxTileWidthSb, sbCols);\n\tu32 maxLog2tileCols = aom_av1_tile_log2(1, MIN(sbCols, AV1_MAX_TILE_COLS));\n\tu32 maxLog2tileRows = aom_av1_tile_log2(1, MIN(sbRows, AV1_MAX_TILE_ROWS));\n\tu32 minLog2Tiles = MAX(minLog2tileCols, aom_av1_tile_log2(maxTileAreaSb, sbRows * sbCols));\n\tBool uniform_tile_spacing_flag = gf_bs_read_int_log(bs, 1, \"uniform_tile_spacing_flag\");\n\tif (uniform_tile_spacing_flag) {\n\t\tu32 startSb, tileWidthSb, tileHeightSb, minLog2tileRows;\n\t\tstate->tileColsLog2 = minLog2tileCols;\n\t\twhile (state->tileColsLog2 < maxLog2tileCols) {\n\t\t\tBool increment_tile_cols_log2 = gf_bs_read_int_log(bs, 1, \"increment_tile_cols_log2\");\n\t\t\tif (increment_tile_cols_log2 == 1)\n\t\t\t\tstate->tileColsLog2++;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}",
"\t\ttileWidthSb = (sbCols + (1 << state->tileColsLog2) - 1) >> state->tileColsLog2;\n\t\ti = 0;\n\t\tfor (startSb = 0; startSb < sbCols; startSb += tileWidthSb) {\n\t\t\ti += 1;\n\t\t}\n\t\tstate->tileCols = i;\n\t\tminLog2tileRows = MAX((int)(minLog2Tiles - state->tileColsLog2), 0);\n\t\tstate->tileRowsLog2 = minLog2tileRows;\n\t\twhile (state->tileRowsLog2 < maxLog2tileRows) {\n\t\t\tBool increment_tile_rows_log2 = gf_bs_read_int_log(bs, 1, \"increment_tile_rows_log2\");\n\t\t\tif (increment_tile_rows_log2 == 1)\n\t\t\t\tstate->tileRowsLog2++;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}",
"\t\ttileHeightSb = (sbRows + (1 << state->tileRowsLog2) - 1) >> state->tileRowsLog2;\n\t\ti = 0;\n\t\tfor (startSb = 0; startSb < sbRows; startSb += tileHeightSb) {\n\t\t\ti += 1;\n\t\t}\n\t\tstate->tileRows = i;\n\t}\n\telse {\n\t\tu32 startSb, maxTileHeightSb, widestTileSb;\n\t\twidestTileSb = 0;\n\t\tstartSb = 0;\n\t\tfor (i = 0; startSb < sbCols; i++) {\n\t\t\tu32 maxWidth = MIN((int)(sbCols - startSb), maxTileWidthSb);\n\t\t\tu32 width_in_sbs_minus_1 = av1_read_ns(bs, maxWidth, \"width_in_sbs_minus_1\");\n\t\t\tu32 sizeSb = width_in_sbs_minus_1 + 1;\n\t\t\twidestTileSb = MAX(sizeSb, widestTileSb);\n\t\t\tstartSb += sizeSb;\n\t\t}\n\t\tif (!widestTileSb) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] widest tile is 0, broken bitstream\\n\"));\n\t\t\treturn;\n\t\t}\n\t\tstate->tileCols = i;\n\t\tstate->tileColsLog2 = aom_av1_tile_log2(1, state->tileCols);",
"\t\tif (minLog2Tiles > 0)\n\t\t\tmaxTileAreaSb = (sbRows * sbCols) >> (minLog2Tiles + 1);\n\t\telse\n\t\t\tmaxTileAreaSb = sbRows * sbCols;\n\t\tmaxTileHeightSb = MAX(maxTileAreaSb / widestTileSb, 1);",
"\t\tstartSb = 0;\n\t\tfor (i = 0; startSb < sbRows; i++) {\n\t\t\tu32 maxHeight = MIN((int)(sbRows - startSb), maxTileHeightSb);\n\t\t\tu32 height_in_sbs_minus_1 = av1_read_ns(bs, maxHeight, \"height_in_sbs_minus_1\");\n\t\t\tu32 sizeSb = height_in_sbs_minus_1 + 1;\n\t\t\tstartSb += sizeSb;\n\t\t}",
"\t\tstate->tileRows = i;\n\t\tstate->tileRowsLog2 = aom_av1_tile_log2(1, state->tileRows);\n\t}\n\tif (state->tileColsLog2 > 0 || state->tileRowsLog2 > 0) {\n\t\tgf_bs_read_int_log(bs, state->tileRowsLog2 + state->tileColsLog2, \"context_update_tile_id\");\n\t\tstate->tile_size_bytes = gf_bs_read_int_log(bs, 2, \"tile_size_bytes_minus1\") + 1;\n\t}\n}",
"static void superres_params(GF_BitStream *bs, AV1State *state)\n{\n\tu32 SuperresDenom;\n\tBool use_superres;",
"\tif (state->enable_superres) {\n\t\tuse_superres = gf_bs_read_int_log(bs, 1, \"use_superres\");\n\t}\n\telse {\n\t\tuse_superres = GF_FALSE;\n\t}\n\tif (use_superres) {\n\t\tu8 coded_denom = gf_bs_read_int_log(bs, AV1_SUPERRES_DENOM_BITS, \"coded_denom\");\n\t\tSuperresDenom = coded_denom + AV1_SUPERRES_DENOM_MIN;\n\t}\n\telse {\n\t\tSuperresDenom = AV1_SUPERRES_NUM;\n\t}\n\tstate->UpscaledWidth = state->width;\n\tstate->width = (state->UpscaledWidth * AV1_SUPERRES_NUM + (SuperresDenom / 2)) / SuperresDenom;\n}",
"static void av1_frame_size(GF_BitStream *bs, AV1State *state, Bool frame_size_override_flag)\n{\n\tif (frame_size_override_flag) {\n\t\tu32 frame_width_minus_1, frame_height_minus_1;\n\t\tu8 n = state->frame_width_bits_minus_1 + 1;\n\t\tframe_width_minus_1 = gf_bs_read_int_log(bs, n, \"frame_width_minus_1\");\n\t\tn = state->frame_height_bits_minus_1 + 1;\n\t\tframe_height_minus_1 = gf_bs_read_int_log(bs, n, \"frame_height_minus_1\");\n\t\tstate->width = frame_width_minus_1 + 1;\n\t\tstate->height = frame_height_minus_1 + 1;\n\t} else {\n\t\tstate->width = state->sequence_width;\n\t\tstate->height = state->sequence_height;\n\t}\n\tsuperres_params(bs, state);\n\t//compute_image_size(); //no bits\n}",
"static void av1_render_size(GF_BitStream *bs)\n{\n\tBool render_and_frame_size_different = gf_bs_read_int_log(bs, 1, \"render_and_frame_size_different_flag\");\n\tif (render_and_frame_size_different == GF_TRUE) {\n\t\tgf_bs_read_int_log(bs, 16, \"render_width_minus_1\");\n\t\tgf_bs_read_int_log(bs, 16, \"render_height_minus_1\");\n\t\t//RenderWidth = render_width_minus_1 + 1;\n\t\t//RenderHeight = render_height_minus_1 + 1;\n\t}\n\telse {\n\t\t//RenderWidth = UpscaledWidth;\n\t\t//RenderHeight = FrameHeight;\n\t}\n}",
"static void read_interpolation_filter(GF_BitStream *bs)\n{\n\tBool is_filter_switchable = gf_bs_read_int_log(bs, 1, \"is_filter_switchable\");\n\tif (!is_filter_switchable) {\n\t\t/*interpolation_filter =*/ gf_bs_read_int_log(bs, 2, \"interpolation_filter\");\n\t}\n}",
"static void frame_size_with_refs(GF_BitStream *bs, AV1State *state, Bool frame_size_override_flag, s8 *ref_frame_idx)\n{\n\tBool found_ref = GF_FALSE;\n\tu32 i = 0;\n\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\tfound_ref = gf_bs_read_int_log_idx(bs, 1, \"found_ref\", i);\n\t\tif (found_ref == 1) {\n\t\t\tstate->UpscaledWidth = state->RefUpscaledWidth[ref_frame_idx[i]];\n\t\t\tstate->width = state->UpscaledWidth;\n\t\t\tstate->height = state->RefFrameHeight[ref_frame_idx[i]];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (found_ref == 0) {\n\t\tav1_frame_size(bs, state, frame_size_override_flag);\n\t\tav1_render_size(bs);\n\t}\n\telse {\n\t\tsuperres_params(bs, state);\n\t\t//compute_image_size();\n\t}\n}",
"static s32 av1_delta_q(GF_BitStream *bs, const char *name_flag, const char *name)\n{\n\tBool delta_coded = gf_bs_read_int_log(bs, 1, name_flag);\n\ts32 delta_q = 0;\n\tif (delta_coded) {\n\t\tu32 signMask = 1 << (7 - 1);\n\t\tdelta_q = gf_bs_read_int_log(bs, 7, name);\n\t\tif (delta_q & signMask)\n\t\t\tdelta_q = delta_q - 2 * signMask;\n\t}\n\treturn delta_q;\n}",
"static u8 Segmentation_Feature_Bits[] = { 8,6,6,6,6,3,0,0 };\nstatic u8 Segmentation_Feature_Signed[] = { 1, 1, 1, 1, 1, 0, 0, 0 };",
"static u8 av1_get_qindex(Bool ignoreDeltaQ, u32 segmentId, u32 base_q_idx, u32 delta_q_present, u32 CurrentQIndex, Bool segmentation_enabled, u8 *features_SEG_LVL_ALT_Q_enabled, s32 *features_SEG_LVL_ALT_Q)\n{\n\t//If seg_feature_active_idx( segmentId, SEG_LVL_ALT_Q ) is equal to 1 the following ordered steps apply:\n\tif (segmentation_enabled && features_SEG_LVL_ALT_Q_enabled[segmentId]) {\n\t\t//Set the variable data equal to FeatureData[ segmentId ][ SEG_LVL_ALT_Q ].\n\t\ts32 data = features_SEG_LVL_ALT_Q[segmentId];\n\t\ts32 qindex = base_q_idx + data;\n\t\t//If ignoreDeltaQ is equal to 0 and delta_q_present is equal to 1, set qindex equal to CurrentQIndex + data.\n\t\tif ((ignoreDeltaQ == 0) && (delta_q_present == 1)) qindex = CurrentQIndex + data;\n\t\t//Return Clip3( 0, 255, qindex ).\n\t\tif (qindex < 0) return 0;\n\t\telse if (qindex > 255) return 255;\n\t\telse return (u8)qindex;\n\t}\n\t//Otherwise, if ignoreDeltaQ is equal to 0 and delta_q_present is equal to 1, return CurrentQIndex.\n\tif ((ignoreDeltaQ == 0) && (delta_q_present == 1)) return CurrentQIndex;\n\t//otherwise\n\treturn base_q_idx;\n}",
"enum {\n\tAV1_RESTORE_NONE = 0,\n\tAV1_RESTORE_SWITCHABLE,\n\tAV1_RESTORE_WIENER,\n\tAV1_RESTORE_SGRPROJ\n};",
"#define AV1_GMC_IDENTITY 0\n#define AV1_GMC_TRANSLATION 1\n#define AV1_GMC_ROTZOOM 2\n#define AV1_GMC_AFFINE 3",
"#define AV1_LAST_FRAME 1\n#define AV1_LAST2_FRAME 2\n#define AV1_LAST3_FRAME 3\n#define AV1_GOLDEN_FRAME 4\n#define AV1_BWDREF_FRAME 5\n#define AV1_ALTREF2_FRAME 6\n#define AV1_ALTREF_FRAME 7",
"#define GM_ABS_ALPHA_BITS 12\n#define GM_ALPHA_PREC_BITS 15\n#define GM_ABS_TRANS_ONLY_BITS 9\n#define GM_TRANS_ONLY_PREC_BITS 3\n#define GM_ABS_TRANS_BITS 12\n#define GM_TRANS_PREC_BITS 6\n#define WARPEDMODEL_PREC_BITS 16",
"\nstatic u32 av1_decode_subexp(GF_BitStream *bs, s32 numSyms)\n{\n\ts32 i = 0;\n\ts32 mk = 0;\n\ts32 k = 3;\n\twhile (1) {\n\t\ts32 b2 = i ? k + i - 1 : k;\n\t\ts32 a = 1 << b2;\n\t\tif (numSyms <= mk + 3 * a) {\n\t\t\ts32 subexp_final_bits = av1_read_ns(bs, numSyms - mk, NULL);\n\t\t\treturn subexp_final_bits + mk;\n\t\t}\n\t\telse {\n\t\t\ts32 subexp_more_bits = gf_bs_read_int(bs, 1);\n\t\t\tif (subexp_more_bits) {\n\t\t\t\ti++;\n\t\t\t\tmk += a;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ts32 subexp_bits = gf_bs_read_int(bs, b2);\n\t\t\t\treturn subexp_bits + mk;\n\t\t\t}\n\t\t}\n\t}\n}",
"static GFINLINE s32 inverse_recenter(s32 r, u32 v)\n{\n\tif ((s64)v > (s64)(2 * r))\n\t\treturn v;\n\telse if (v & 1)\n\t\treturn r - ((v + 1) >> 1);\n\telse\n\t\treturn r + (v >> 1);\n}",
"static s32 av1_decode_unsigned_subexp_with_ref(GF_BitStream *bs, s32 mx, s32 r)\n{\n\tu32 v = av1_decode_subexp(bs, mx);\n\tif ((r < 0) && (-(-r << 1) <= mx)) {\n\t\treturn inverse_recenter(r, v);\n\t}\n\telse if ((r << 1) <= mx) {\n\t\treturn inverse_recenter(r, v);\n\t}\n\telse {\n\t\treturn mx - 1 - inverse_recenter(mx - 1 - r, v);\n\t}\n}\nstatic s16 av1_decode_signed_subexp_with_ref(GF_BitStream *bs, s32 low, s32 high, s32 r)\n{\n\ts16 x = av1_decode_unsigned_subexp_with_ref(bs, high - low, r - low);\n\treturn x + low;\n}",
"static void av1_read_global_param(AV1State *state, GF_BitStream *bs, u8 type, u8 ref, u8 idx)\n{\n\tu8 absBits = GM_ABS_ALPHA_BITS;\n\tu8 precBits = GM_ALPHA_PREC_BITS;\n\tif (idx < 2) {\n\t\tif (type == AV1_GMC_TRANSLATION) {\n\t\t\tabsBits = GM_ABS_TRANS_ONLY_BITS - (!state->frame_state.allow_high_precision_mv ? 1 : 0);\n\t\t\tprecBits = GM_TRANS_ONLY_PREC_BITS - (!state->frame_state.allow_high_precision_mv ? 1 : 0);\n\t\t}\n\t\telse {\n\t\t\tabsBits = GM_ABS_TRANS_BITS;\n\t\t\tprecBits = GM_TRANS_PREC_BITS;\n\t\t}\n\t}\n\ts32 precDiff = WARPEDMODEL_PREC_BITS - precBits;\n\ts32 round = (idx % 3) == 2 ? (1 << WARPEDMODEL_PREC_BITS) : 0;\n\ts32 sub = (idx % 3) == 2 ? (1 << precBits) : 0;\n\ts32 mx = (1 << absBits);\n\ts32 r = (state->PrevGmParams.coefs[ref][idx] >> precDiff) - sub;\n\ts32 val = av1_decode_signed_subexp_with_ref(bs, -mx, mx + 1, r);",
"\tif (val < 0) {\n\t\tval = -val;\n\t\tstate->GmParams.coefs[ref][idx] = (-(val << precDiff) + round);\n\t}\n\telse {\n\t\tstate->GmParams.coefs[ref][idx] = (val << precDiff) + round;\n\t}\n}",
"static s32 av1_get_relative_dist(s32 a, s32 b, AV1State *state)\n{\n\tif (!state->enable_order_hint)\n\t\treturn 0;\n\ts32 diff = a - b;\n\ts32 m = 1 << (state->OrderHintBits - 1);\n\tdiff = (diff & (m - 1)) - (diff & m);\n\treturn diff;\n}",
"static void av1_setup_past_independence(AV1State *state)\n{\n\tu32 ref, i;\n\tfor (ref = AV1_LAST_FRAME; ref <= AV1_ALTREF_FRAME; ref++) {\n\t\tfor (i = 0; i <= 5; i++) {\n\t\t\tstate->PrevGmParams.coefs[ref][i] = ((i % 3 == 2) ? 1 << WARPEDMODEL_PREC_BITS : 0);\n\t\t}\n\t}\n}",
"static void av1_load_previous(AV1State *state, u8 primary_ref_frame, s8 *ref_frame_idx)\n{\n\ts8 prevFrame = ref_frame_idx[primary_ref_frame];\n\tif (prevFrame < 0) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] load_previous: prevFrame reference index %d is invalid\\n\", prevFrame));\n\t}\n\telse {\n\t\tstate->PrevGmParams = state->SavedGmParams[prevFrame];\n\t\t// load_loop_filter_params( prevFrame )\n\t\t// load_segmentation_params( prevFrame )\n\t}\n}",
"static void av1_decode_frame_wrapup(AV1State *state)\n{\n\tu32 i;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\tif ((state->frame_state.refresh_frame_flags >> i) & 1) {\n\t\t\tstate->RefOrderHint[i] = state->frame_state.order_hint;\n\t\t\tstate->SavedGmParams[i] = state->GmParams;\n\t\t\tstate->RefFrameType[i] = state->frame_state.frame_type;\n\t\t\tstate->RefUpscaledWidth[i] = state->UpscaledWidth;\n\t\t\tstate->RefFrameHeight[i] = state->height;\n\t\t}\n\t}\n\tstate->frame_state.seen_frame_header = GF_FALSE;\n\t//Otherwise (show_existing_frame is equal to 1), if frame_type is equal to KEY_FRAME, the reference frame loading process as specified in section 7.21 is invoked\n\tif ((state->frame_state.show_existing_frame) && (state->frame_state.frame_type == AV1_KEY_FRAME)) {\n\t\tstate->frame_state.order_hint = state->RefOrderHint[state->frame_state.frame_to_show_map_idx];\n\t\t//OrderHints[ j + LAST_FRAME ] is set equal to SavedOrderHints[state->frame_to_show_map_idx ][ j + LAST_FRAME ] for j = 0..REFS_PER_FRAME-1.",
"\t\t//gm_params[ ref ][ j ] is set equal to SavedGmParams[ frame_to_show_map_idx ][ ref ][ j ] for ref = LAST_FRAME..ALTREF_FRAME, for j = 0..5.\n\t\tstate->GmParams = state->SavedGmParams[state->frame_state.frame_to_show_map_idx];",
"\t}\n}",
"static s32 find_latest_forward(u32 curFrameHint, u8 *shiftedOrderHints, u8 *usedFrame)\n{\n\tu32 i;\n\ts32 ref = -1;\n\ts32 latestOrderHint = 0;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\ts32 hint = shiftedOrderHints[i];\n\t\tif (!usedFrame[i] && ((u32)hint < curFrameHint) && (ref < 0 || hint >= latestOrderHint)) {\n\t\t\tref = i;\n\t\t\tlatestOrderHint = hint;\n\t\t}\n\t}\n\treturn ref;\n}",
"//see 7.8 of AV1 spec\nstatic void av1_set_frame_refs(AV1State *state, u8 last_frame_idx, u8 gold_frame_idx, s8 *ref_frame_idx)\n{\n\tu32 i;\n\tu8 usedFrame[AV1_NUM_REF_FRAMES];\n\tu8 shiftedOrderHints[AV1_NUM_REF_FRAMES];",
"\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++)\n\t\tref_frame_idx[i] = -1;",
"\tref_frame_idx[AV1_LAST_FRAME - AV1_LAST_FRAME] = last_frame_idx;\n\tref_frame_idx[AV1_GOLDEN_FRAME - AV1_LAST_FRAME] = gold_frame_idx;",
"\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\tusedFrame[i] = 0;\n\t}",
"\tusedFrame[last_frame_idx] = 1;\n\tusedFrame[gold_frame_idx] = 1;\n\tu32 curFrameHint = 1 << (state->OrderHintBits - 1);",
"\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\tshiftedOrderHints[i] = curFrameHint + av1_get_relative_dist(state->RefOrderHint[i], state->frame_state.order_hint, state);\n\t}",
"\tu8 lastOrderHint = shiftedOrderHints[last_frame_idx];\n\tu8 goldOrderHint = shiftedOrderHints[gold_frame_idx];",
"\t//It is a requirement of bitstream conformance that lastOrderHint is strictly less than curFrameHint.\n\tif (lastOrderHint >= curFrameHint) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] non conformant bitstream detected while setting up frame refs: lastOrderHint(%d) shall be stricly less than curFrameHint(%d)\\n\", lastOrderHint, curFrameHint));\n\t}\n\t//It is a requirement of bitstream conformance that goldOrderHint is strictly less than curFrameHint.\n\tif (goldOrderHint >= curFrameHint) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] non conformant bitstream detected while setting up frame refs: goldOrderHint(%d) shall be stricly less than curFrameHint(%d)\\n\", lastOrderHint, curFrameHint));\n\t}",
"\t//find_latest_backward() {\n\ts32 ref = -1;\n\ts32 latestOrderHint = 0;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\ts32 hint = shiftedOrderHints[i];\n\t\tif (!usedFrame[i] && ((u32)hint >= curFrameHint) && (ref < 0 || hint >= latestOrderHint)) {\n\t\t\tref = i;\n\t\t\tlatestOrderHint = hint;\n\t\t}\n\t}\n\tif (ref >= 0) {\n\t\tref_frame_idx[AV1_ALTREF_FRAME - AV1_LAST_FRAME] = ref;\n\t\tusedFrame[ref] = 1;\n\t}\n\t//find_earliest_backward() for BWDREF_FRAME\n\tref = -1;\n\ts32 earliestOrderHint = 0;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\ts32 hint = shiftedOrderHints[i];\n\t\tif (!usedFrame[i] && ((u32)hint >= curFrameHint) && (ref < 0 || hint < earliestOrderHint)) {\n\t\t\tref = i;\n\t\t\tearliestOrderHint = hint;\n\t\t}\n\t}\n\tif (ref >= 0) {\n\t\tref_frame_idx[AV1_BWDREF_FRAME - AV1_LAST_FRAME] = ref;\n\t\tusedFrame[ref] = 1;\n\t}",
"\t//find_earliest_backward() for ALTREF2_FRAME\n\tref = -1;\n\tearliestOrderHint = 0;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\ts32 hint = shiftedOrderHints[i];\n\t\tif (!usedFrame[i] && ((u32)hint >= curFrameHint) && (ref < 0 || hint < earliestOrderHint)) {\n\t\t\tref = i;\n\t\t\tearliestOrderHint = hint;\n\t\t}\n\t}\n\tif (ref >= 0) {\n\t\tref_frame_idx[AV1_ALTREF2_FRAME - AV1_LAST_FRAME] = ref;\n\t\tusedFrame[ref] = 1;\n\t}",
"\t//The remaining references are set to be forward references in anti-chronological order as follows:",
"\tconst u8 Ref_Frame_List[AV1_REFS_PER_FRAME - 2] = {\n\t\tAV1_LAST2_FRAME, AV1_LAST3_FRAME, AV1_BWDREF_FRAME, AV1_ALTREF2_FRAME, AV1_ALTREF_FRAME\n\t};",
"\tfor (i = 0; i < AV1_REFS_PER_FRAME - 2; i++) {\n\t\tu8 refFrame = Ref_Frame_List[i];\n\t\tif (ref_frame_idx[refFrame - AV1_LAST_FRAME] < 0) {\n\t\t\ts32 last_ref = find_latest_forward(curFrameHint, shiftedOrderHints, usedFrame);\n\t\t\tif (last_ref >= 0) {\n\t\t\t\tref_frame_idx[refFrame - AV1_LAST_FRAME] = last_ref;\n\t\t\t\tusedFrame[last_ref] = 1;\n\t\t\t}\n\t\t}\n\t}\n\t//Finally, any remaining references are set to the reference frame with smallest output order as follows:\n\tref = -1;\n\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\ts32 hint = shiftedOrderHints[i];\n\t\tif (ref < 0 || hint < earliestOrderHint) {\n\t\t\tref = i;\n\t\t\tearliestOrderHint = hint;\n\t\t}\n\t}\n\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\tif (ref_frame_idx[i] < 0) {\n\t\t\tref_frame_idx[i] = ref;\n\t\t}\n\t}\n}",
"\nstatic void av1_parse_uncompressed_header(GF_BitStream *bs, AV1State *state)\n{\n\tBool error_resilient_mode = GF_FALSE, allow_screen_content_tools = GF_FALSE, force_integer_mv = GF_FALSE;\n\tBool /*use_ref_frame_mvs = GF_FALSE,*/ FrameIsIntra = GF_FALSE, frame_size_override_flag = GF_FALSE;\n\tBool disable_cdf_update = GF_FALSE;\n\tu8 showable_frame;\n\tu8 primary_ref_frame;\n\tu16 idLen = 0;\n\tu32 idx;\n\ts8 ref_frame_idx[AV1_REFS_PER_FRAME];\n\tAV1StateFrame *frame_state = &state->frame_state;",
"\tif (state->frame_id_numbers_present_flag) {\n\t\tidLen = (state->additional_frame_id_length_minus_1 + state->delta_frame_id_length_minus_2 + 3);\n\t}\n\tframe_state->refresh_frame_flags = 0;",
"\tshowable_frame = 0;\n\tif (state->reduced_still_picture_header) {\n\t\tframe_state->key_frame = GF_TRUE;\n\t\tFrameIsIntra = GF_TRUE;\n\t\tframe_state->frame_type = AV1_KEY_FRAME;\n\t\tframe_state->show_frame = GF_TRUE;\n\t\tframe_state->show_existing_frame = 0;\n\t}\n\telse {\n\t\tframe_state->show_existing_frame = gf_bs_read_int_log(bs, 1, \"show_existing_frame\");\n\t\tif (frame_state->show_existing_frame == GF_TRUE) {\n\t\t\tframe_state->frame_to_show_map_idx = gf_bs_read_int_log(bs, 3, \"frame_to_show_map_idx\");\n\t\t\tframe_state->frame_type = state->RefFrameType[frame_state->frame_to_show_map_idx];",
"\t\t\tif (state->decoder_model_info_present_flag && !state->equal_picture_interval) {\n\t\t\t\tgf_bs_read_int_log(bs, state->frame_presentation_time_length, \"frame_presentation_time\");\n\t\t\t}",
"\t\t\tframe_state->refresh_frame_flags = 0;\n\t\t\tif (state->frame_id_numbers_present_flag) {\n\t\t\t\tgf_bs_read_int_log(bs, idLen, \"display_frame_id\");\n\t\t\t}\n\t\t\tif (frame_state->frame_type == AV1_KEY_FRAME) {\n\t\t\t\tframe_state->refresh_frame_flags = AV1_ALL_FRAMES;\n\t\t\t}\n\t\t\t/*\n\t\t\tif (film_grain_params_present) {\n\t\t\t\tload_grain_params(frame_to_show_map_idx)\n\t\t\t}*/\n\t\t\treturn;\n\t\t}\n\t\tframe_state->frame_type = gf_bs_read_int_log(bs, 2, \"frame_type\");\n\t\tFrameIsIntra = (frame_state->frame_type == AV1_INTRA_ONLY_FRAME || frame_state->frame_type == AV1_KEY_FRAME);\n\t\tframe_state->show_frame = gf_bs_read_int_log(bs, 1, \"show_frame\");\n\t\tif (frame_state->is_first_frame) {\n\t\t\tframe_state->key_frame = frame_state->seen_seq_header && frame_state->show_frame && frame_state->frame_type == AV1_KEY_FRAME && frame_state->seen_frame_header;\n\t\t}\n\t\tif (frame_state->show_frame && state->decoder_model_info_present_flag && !state->equal_picture_interval) {\n\t\t\tgf_bs_read_int_log(bs, state->frame_presentation_time_length, \"frame_presentation_time\");\n\t\t}\n\t\tif (frame_state->show_frame) {\n\t\t\tshowable_frame = frame_state->frame_type != AV1_KEY_FRAME;",
"\t\t}\n\t\telse {\n\t\t\tshowable_frame = gf_bs_read_int_log(bs, 1, \"showable_frame\");\n\t\t}\n\t\tif (frame_state->frame_type == AV1_SWITCH_FRAME || (frame_state->frame_type == AV1_KEY_FRAME && frame_state->show_frame))\n\t\t\terror_resilient_mode = GF_TRUE;\n\t\telse\n\t\t\terror_resilient_mode = gf_bs_read_int_log(bs, 1, \"error_resilient_mode\");\n\t}",
"\tif ((frame_state->frame_type == AV1_KEY_FRAME) && frame_state->show_frame) {\n\t\tu32 i;\n\t\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\t\tstate->RefValid[i] = 0;\n\t\t\tstate->RefOrderHint[i] = 0;\n\t\t}\n\t\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\t\tstate->OrderHints[AV1_LAST_FRAME + i] = 0;\n\t\t}\n\t}",
"\tdisable_cdf_update = gf_bs_read_int_log(bs, 1, \"disable_cdf_update\");\n\tif (state->seq_force_screen_content_tools == 2/*SELECT_SCREEN_CONTENT_TOOLS*/) {\n\t\tallow_screen_content_tools = gf_bs_read_int_log(bs, 1, \"allow_screen_content_tools\");\n\t}\n\telse {\n\t\tallow_screen_content_tools = state->seq_force_screen_content_tools;\n\t}\n\tif (allow_screen_content_tools) {\n\t\tif (state->seq_force_integer_mv == 2/*SELECT_INTEGER_MV*/) {\n\t\t\tforce_integer_mv = gf_bs_read_int_log(bs, 1, \"force_integer_mv\");\n\t\t}\n\t\telse {\n\t\t\tforce_integer_mv = state->seq_force_integer_mv;\n\t\t}\n\t}\n\telse {\n\t\tforce_integer_mv = 0;\n\t}\n\tif (FrameIsIntra) {\n\t\tforce_integer_mv = 1;\n\t}\n\tif (state->frame_id_numbers_present_flag) {\n\t\tgf_bs_read_int_log(bs, idLen, \"current_frame_id\");\n\t}\n\tif (frame_state->frame_type == AV1_SWITCH_FRAME)\n\t\tframe_size_override_flag = GF_TRUE;\n\telse if (state->reduced_still_picture_header)\n\t\tframe_size_override_flag = GF_FALSE;\n\telse\n\t\tframe_size_override_flag = gf_bs_read_int_log(bs, 1, \"frame_size_override_flag\");",
"\tframe_state->order_hint = gf_bs_read_int_log(bs, state->OrderHintBits, \"order_hint\");\n\tif (FrameIsIntra || error_resilient_mode) {\n\t\tprimary_ref_frame = AV1_PRIMARY_REF_NONE;\n\t}\n\telse {\n\t\tprimary_ref_frame = gf_bs_read_int_log(bs, 3, \"primary_ref_frame\");\n\t}",
"\tif (state->decoder_model_info_present_flag) {\n\t\tu8 buffer_removal_time_present_flag = gf_bs_read_int_log(bs, 1, \"buffer_removal_time_present_flag\");\n\t\tif (buffer_removal_time_present_flag) {\n\t\t\tu32 opNum;\n\t\t\tfor (opNum = 0; opNum < state->operating_points_count; opNum++) {\n\t\t\t\tif (state->decoder_model_present_for_this_op[opNum]) {\n\t\t\t\t\tu8 opPtIdc = state->operating_point_idc[opNum];\n\t\t\t\t\tu8 inTemporalLayer = (opPtIdc >> state->temporal_id) & 1;\n\t\t\t\t\tu8 inSpatialLayer = (opPtIdc >> (state->spatial_id + 8)) & 1;\n\t\t\t\t\tif (opPtIdc == 0 || (inTemporalLayer && inSpatialLayer)) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, state->buffer_removal_time_length, \"buffer_removal_time\", opNum);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\tif (frame_state->frame_type == AV1_SWITCH_FRAME || (frame_state->frame_type == AV1_KEY_FRAME && frame_state->show_frame)) {\n\t\tframe_state->refresh_frame_flags = AV1_ALL_FRAMES;\n\t}\n\telse {\n\t\tframe_state->refresh_frame_flags = gf_bs_read_int_log(bs, 8, \"refresh_frame_flags\");\n\t}\n\tif (!FrameIsIntra || frame_state->refresh_frame_flags != AV1_ALL_FRAMES) {\n\t\tif (error_resilient_mode && state->enable_order_hint) {\n\t\t\tu32 i = 0;\n\t\t\tfor (i = 0; i < AV1_NUM_REF_FRAMES; i++) {\n\t\t\t\tu8 ref_order_hint = gf_bs_read_int_log_idx(bs, state->OrderHintBits, \"ref_order_hint\", i);\n\t\t\t\tif (ref_order_hint != state->RefOrderHint[i]) {\n\t\t\t\t\tstate->RefValid[i] = 0;\n\t\t\t\t}\n\t\t\t\tstate->RefOrderHint[i] = ref_order_hint;\n\t\t\t}\n\t\t}\n\t}",
"\tu8 allow_intrabc = 0;\n\tif (frame_state->frame_type == AV1_KEY_FRAME) {\n\t\tav1_frame_size(bs, state, frame_size_override_flag);\n\t\tav1_render_size(bs);\n\t\tif (allow_screen_content_tools && state->UpscaledWidth == state->width) {\n\t\t\tallow_intrabc = gf_bs_read_int_log(bs, 1, \"allow_intrabc\");\n\t\t}\n\t}\n\telse {\n\t\tif (frame_state->frame_type == AV1_INTRA_ONLY_FRAME) {\n\t\t\tav1_frame_size(bs, state, frame_size_override_flag);\n\t\t\tav1_render_size(bs);\n\t\t\tif (allow_screen_content_tools && state->UpscaledWidth == state->width) {\n\t\t\t\tallow_intrabc = gf_bs_read_int_log(bs, 1, \"allow_intrabc\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tu32 i = 0;\n\t\t\tBool frame_refs_short_signaling = GF_FALSE;\n\t\t\tif (state->enable_order_hint) {\n\t\t\t\tframe_refs_short_signaling = gf_bs_read_int_log(bs, 1, \"frame_refs_short_signaling\");\n\t\t\t\tif (frame_refs_short_signaling) {\n\t\t\t\t\tu8 last_frame_idx = gf_bs_read_int_log(bs, 3, \"last_frame_idx\");\n\t\t\t\t\tu8 gold_frame_idx = gf_bs_read_int_log(bs, 3, \"gold_frame_idx\");\n\t\t\t\t\tav1_set_frame_refs(state, last_frame_idx, gold_frame_idx, ref_frame_idx);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\t\t\tif (!frame_refs_short_signaling)\n\t\t\t\t\tref_frame_idx[i] = gf_bs_read_int_log_idx(bs, 3, \"ref_frame_idx\", i);",
"\t\t\t\tif (state->frame_id_numbers_present_flag) {\n\t\t\t\t\tu32 n = state->delta_frame_id_length_minus_2 + 2;\n\t\t\t\t\t/*delta_frame_id_minus_1 =*/ gf_bs_read_int_log_idx(bs, n, \"delta_frame_id_minus1\", i);\n\t\t\t\t\t//DeltaFrameId = delta_frame_id_minus_1 + 1;\n\t\t\t\t\t//expectedFrameId[i] = ((current_frame_id + (1 << idLen) - DeltaFrameId) % (1 << idLen));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (frame_size_override_flag && !error_resilient_mode) {\n\t\t\t\tframe_size_with_refs(bs, state, frame_size_override_flag, ref_frame_idx);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tav1_frame_size(bs, state, frame_size_override_flag);\n\t\t\t\tav1_render_size(bs);\n\t\t\t}\n\t\t\tframe_state->allow_high_precision_mv = 0;\n\t\t\tif (!force_integer_mv) {\n\t\t\t\tframe_state->allow_high_precision_mv = gf_bs_read_int_log(bs, 1, \"allow_high_precision_mv\");\n\t\t\t}",
"\t\t\tread_interpolation_filter(bs);",
"\t\t\tgf_bs_read_int_log(bs, 1, \"is_motion_mode_switchable\");\n\t\t\tif (!(error_resilient_mode || !state->enable_ref_frame_mvs)) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"use_ref_frame_mvs\");\n\t\t\t}\n\t\t}\n\t}",
"\tif (!FrameIsIntra) {\n\t\tu32 i;\n\t\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\t\tu8 refFrame = AV1_LAST_FRAME + i;\n\t\t\tu8 ridx = ref_frame_idx[i];\n\t\t\tif (ridx >= 0) {\n\t\t\t\tu8 hint = state->RefOrderHint[ridx];\n\t\t\t\tstate->OrderHints[refFrame] = hint;\n\t\t\t\t/*\t\t\tif ( !enable_order_hint ) {\n\t\t\t\t\t\t\t\tRefFrameSignBias[ refFrame ] = 0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tRefFrameSignBias[ refFrame ] = get_relative_dist( hint, OrderHint) > 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t*/\n\t\t\t}",
"\t\t}\n\t}",
"\tif (!(state->reduced_still_picture_header || disable_cdf_update))\n\t\tgf_bs_read_int_log(bs, 1, \"disable_frame_end_update_cdf\");",
"\tif (primary_ref_frame == AV1_PRIMARY_REF_NONE) {\n\t\t//init_non_coeff_cdfs();\n\t\tav1_setup_past_independence(state);\n\t}\n\telse {\n\t\t//load_cdfs(ref_frame_idx[primary_ref_frame]);\n\t\tav1_load_previous(state, primary_ref_frame, ref_frame_idx);\n\t}",
"\tav1_parse_tile_info(bs, state);\n\t//quantization_params( ):\n\tu8 base_q_idx = gf_bs_read_int_log(bs, 8, \"base_q_idx\");\n\ts32 DeltaQUDc = 0;\n\ts32 DeltaQUAc = 0;\n\ts32 DeltaQVDc = 0;\n\ts32 DeltaQVAc = 0;\n\ts32 DeltaQYDc = av1_delta_q(bs, \"DeltaQYDc_coded\", \"DeltaQYDc\");\n\tif (!state->config->monochrome) {\n\t\tu8 diff_uv_delta = 0;\n\t\tif (state->separate_uv_delta_q)\n\t\t\tdiff_uv_delta = gf_bs_read_int_log(bs, 1, \"diff_uv_delta\");",
"\t\tDeltaQUDc = av1_delta_q(bs, \"DeltaQUDc_coded\", \"DeltaQUDc\");\n\t\tDeltaQUAc = av1_delta_q(bs, \"DeltaQUAc_coded\", \"DeltaQUAc\");\n\t\tif (diff_uv_delta) {\n\t\t\tDeltaQVDc = av1_delta_q(bs, \"DeltaQVDc_coded\", \"DeltaQVDc\");\n\t\t\tDeltaQVAc = av1_delta_q(bs, \"DeltaQVAc_coded\", \"DeltaQVAc\");\n\t\t}\n\t}\n\tif (gf_bs_read_int_log(bs, 1, \"using_qmatrix\")) {\n\t\tgf_bs_read_int_log(bs, 4, \"qm_y\");\n\t\tgf_bs_read_int_log(bs, 4, \"qm_u\");\n\t\tif (!state->separate_uv_delta_q) {\n\t\t\tgf_bs_read_int_log(bs, 4, \"qm_v\");\n\t\t}\n\t}",
"\tu8 seg_features_SEG_LVL_ALT_Q_enabled[8] = { 0,0,0,0,0,0,0,0 };\n\ts32 seg_features_SEG_LVL_ALT_Q[8] = { 0,0,0,0,0,0,0,0 };",
"\t//segmentation_params( ):\n\tu8 segmentation_enabled = gf_bs_read_int_log(bs, 1, \"segmentation_enabled\");\n\tif (segmentation_enabled) {\n\t\t/*u8 segmentation_temporal_update = 0;*/\n\t\tu8 segmentation_update_data = 1;\n\t\tif (primary_ref_frame != AV1_PRIMARY_REF_NONE) {\n\t\t\tu8 segmentation_update_map = gf_bs_read_int_log(bs, 1, \"segmentation_update_map\");\n\t\t\tif (segmentation_update_map == 1)\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"segmentation_temporal_update\");\n\t\t\tsegmentation_update_data = gf_bs_read_int_log(bs, 1, \"segmentation_update_data\");\n\t\t}\n\t\tif (segmentation_update_data == 1) {\n\t\t\tu32 i, j;\n\t\t\tfor (i = 0; i < 8/*=MAX_SEGMENTS*/; i++) {\n\t\t\t\tfor (j = 0; j < 8 /*=SEG_LVL_MAX*/; j++) {\n\t\t\t\t\tif (/*feature_enabled = */gf_bs_read_int_log_idx2(bs, 1, \"feature_enabled\", i, j) == 1) {\n\t\t\t\t\t\ts32 val;\n\t\t\t\t\t\tu32 bitsToRead = Segmentation_Feature_Bits[j];\n\t\t\t\t\t\t//this is SEG_LVL_ALT_Q\n\t\t\t\t\t\tif (!j) seg_features_SEG_LVL_ALT_Q_enabled[i] = 1;",
"\t\t\t\t\t\tif (Segmentation_Feature_Signed[j] == 1) {\n\t\t\t\t\t\t\tval = gf_bs_read_int_log_idx2(bs, 1 + bitsToRead, \"signed_feature_value\", i, j);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tval = gf_bs_read_int_log_idx2(bs, bitsToRead, \"feature_value\", i, j);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!j) seg_features_SEG_LVL_ALT_Q[i] = val;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//ignore all init steps\n\t\t}",
"\t}",
"\t//delta_q_params():\n\t/*u8 delta_q_res = 0;*/\n\tu8 delta_q_present = 0;\n\tif (base_q_idx > 0) {\n\t\tdelta_q_present = gf_bs_read_int_log(bs, 1, \"delta_q_present\");\n\t}\n\tif (delta_q_present) {\n\t\tgf_bs_read_int_log(bs, 2, \"delta_q_res\");\n\t}",
"\t//delta_lf_params():\n\tu8 delta_lf_present = 0;\n\t/*u8 delta_lf_res = 0;\n\tu8 delta_lf_multi = 0;*/\n\tif (delta_q_present) {\n\t\tif (!allow_intrabc) {\n\t\t\tdelta_lf_present = gf_bs_read_int_log(bs, 1, \"delta_lf_present\");\n\t\t}\n\t\tif (delta_lf_present) {\n\t\t\tgf_bs_read_int_log(bs, 2, \"delta_lf_res\");\n\t\t\tgf_bs_read_int_log(bs, 1, \"delta_lf_multi\");\n\t\t}\n\t}",
"\t//init lossless stuff!\n\tu8 CodedLossless = 1;\n\tfor (idx = 0; idx < 8; idx++) {\n\t\tu8 qindex = av1_get_qindex(GF_TRUE, idx, base_q_idx, delta_q_present, 0/*CurrentQIndex always ignored at this level of parsin*/, segmentation_enabled, seg_features_SEG_LVL_ALT_Q_enabled, seg_features_SEG_LVL_ALT_Q);\n\t\tBool LosslessArray = (qindex == 0) && (DeltaQYDc == 0) && (DeltaQUAc == 0) && (DeltaQUDc == 0) && (DeltaQVAc == 0) && (DeltaQVDc == 0);\n\t\tif (!LosslessArray)\n\t\t\tCodedLossless = 0;\n\t}\n\tBool AllLossless = CodedLossless && (state->width == state->UpscaledWidth);",
"\t//loop_filter_params():\n\tif (!CodedLossless && !allow_intrabc) {\n\t\tu8 loop_filter_level_0 = gf_bs_read_int_log(bs, 6, \"loop_filter_level_0\");\n\t\tu8 loop_filter_level_1 = gf_bs_read_int_log(bs, 6, \"loop_filter_level_1\");\n\t\tif (!state->config->monochrome) {\n\t\t\tif (loop_filter_level_0 || loop_filter_level_1) {\n\t\t\t\tgf_bs_read_int_log(bs, 6, \"loop_filter_level_2\");\n\t\t\t\tgf_bs_read_int_log(bs, 6, \"loop_filter_level_3\");\n\t\t\t}\n\t\t}\n\t\tgf_bs_read_int_log(bs, 3, \"loop_filter_sharpness\");\n\t\tu8 loop_filter_delta_enabled = gf_bs_read_int_log(bs, 1, \"loop_filter_delta_enabled\");\n\t\tif (loop_filter_delta_enabled == 1) {\n\t\t\tu8 loop_filter_delta_update = gf_bs_read_int_log(bs, 1, \"loop_filter_delta_update\");\n\t\t\tif (loop_filter_delta_update) {\n\t\t\t\tu32 i;\n\t\t\t\tfor (i = 0; i < 8/*TOTAL_REFS_PER_FRAME*/; i++) {\n\t\t\t\t\tu8 update_ref_delta = gf_bs_read_int_log_idx(bs, 1, \"update_ref_delta\", i);\n\t\t\t\t\tif (update_ref_delta == 1) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 1 + 6, \"loop_filter_ref_deltas\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (i = 0; i < 2; i++) {\n\t\t\t\t\tu8 update_mode_delta = gf_bs_read_int_log_idx(bs, 1, \"update_mode_delta\", i);\n\t\t\t\t\tif (update_mode_delta) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 1 + 6, \"loop_filter_mode_deltas\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//cdef_params( ):\n\tif (!CodedLossless && !allow_intrabc && state->enable_cdef) {\n\t\tgf_bs_read_int_log(bs, 2, \"cdef_damping_minus_3\");\n\t\tu8 cdef_bits = gf_bs_read_int_log(bs, 2, \"cdef_bits\");\n\t\tu32 i, num_cd = 1 << cdef_bits;\n\t\tfor (i = 0; i < num_cd; i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, 4, \"cdef_y_pri_strength\", i);\n\t\t\tgf_bs_read_int_log_idx(bs, 2, \"cdef_y_sec_strength\", i);\n\t\t\tif (!state->config->monochrome) {\n\t\t\t\tgf_bs_read_int_log_idx(bs, 4, \"cdef_uv_pri_strength\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 2, \"cdef_uv_sec_strength\", i);\n\t\t\t}\n\t\t}\n\t}",
"\t//lr_params( ) :\n\tif (!AllLossless && !allow_intrabc && state->enable_restoration) {\n\t\tu32 i, nb_planes = state->config->monochrome ? 1 : 3;\n\t\tu8 UsesLr = 0;\n\t\tu8 usesChromaLr = 0;\n\t\tfor (i = 0; i < nb_planes; i++) {\n\t\t\tu8 lr_type = gf_bs_read_int_log_idx(bs, 2, \"lr_type\", i);\n\t\t\t//FrameRestorationType[i] = Remap_Lr_Type[lr_type]\n\t\t\tif (lr_type != AV1_RESTORE_NONE) {\n\t\t\t\tUsesLr = 1;\n\t\t\t\tif (i > 0) {\n\t\t\t\t\tusesChromaLr = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (UsesLr) {\n\t\t\tif (state->use_128x128_superblock) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"lr_unit_shift_minus_1\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tu8 lr_unit_shift = gf_bs_read_int_log(bs, 1, \"lr_unit_shift\");\n\t\t\t\tif (lr_unit_shift) {\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"lr_unit_extra_shift\");\n\t\t\t\t\t//lr_unit_shift += lr_unit_extra_shift;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (state->config->chroma_subsampling_x && state->config->chroma_subsampling_y && usesChromaLr) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"lr_uv_shift\");\n\t\t\t}\n\t\t}\n\t}\n\t//read_tx_mode():\n\tif (CodedLossless == 1) {\n\t}\n\telse {\n\t\tgf_bs_read_int_log(bs, 1, \"tx_mode_select\");\n\t}",
"\t//frame_reference_mode( ):\n\tu8 reference_select = 0;\n\tif (FrameIsIntra) {\n\t}\n\telse {\n\t\treference_select = gf_bs_read_int_log(bs, 1, \"reference_select\");\n\t}",
"\t//skip_mode_params( ):\n\tu8 skipModeAllowed = 0;\n\tif (FrameIsIntra || !reference_select || !state->enable_order_hint) {\n\t}\n\telse {\n\t\tu32 i;\n\t\ts32 forwardIdx = -1;\n\t\ts32 backwardIdx = -1;\n\t\ts32 forwardHint = 0;\n\t\ts32 backwardHint = 0;\n\t\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\t\tu8 refHint = state->RefOrderHint[ref_frame_idx[i]];\n\t\t\tif (av1_get_relative_dist(refHint, frame_state->order_hint, state) < 0) {\n\t\t\t\tif (forwardIdx < 0 || av1_get_relative_dist(refHint, forwardHint, state) > 0) {\n\t\t\t\t\tforwardIdx = i;\n\t\t\t\t\tforwardHint = refHint;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (av1_get_relative_dist(refHint, frame_state->order_hint, state) > 0) {\n\t\t\t\tif (backwardIdx < 0 || av1_get_relative_dist(refHint, backwardHint, state) < 0) {\n\t\t\t\t\tbackwardIdx = i;\n\t\t\t\t\tbackwardHint = refHint;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (forwardIdx < 0) {\n\t\t\tskipModeAllowed = 0;\n\t\t}\n\t\telse if (backwardIdx >= 0) {\n\t\t\tskipModeAllowed = 1;\n\t\t\t//SkipModeFrame[0] = AV1_LAST_FRAME + MIN(forwardIdx, backwardIdx);\n\t\t\t//SkipModeFrame[1] = AV1_LAST_FRAME + MAX(forwardIdx, backwardIdx);\n\t\t}\n\t\telse {\n\t\t\ts32 secondForwardIdx = -1;\n\t\t\ts32 secondForwardHint = 0;\n\t\t\tfor (i = 0; i < AV1_REFS_PER_FRAME; i++) {\n\t\t\t\tu8 refHint = state->RefOrderHint[ref_frame_idx[i]];\n\t\t\t\tif (av1_get_relative_dist(refHint, forwardHint, state) < 0) {\n\t\t\t\t\tif (secondForwardIdx < 0 || av1_get_relative_dist(refHint, secondForwardHint, state) > 0) {\n\t\t\t\t\t\tsecondForwardIdx = i;\n\t\t\t\t\t\tsecondForwardHint = refHint;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (secondForwardIdx < 0) {\n\t\t\t\tskipModeAllowed = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tskipModeAllowed = 1;\n\t\t\t\t//SkipModeFrame[ 0 ] = LAST_FRAME + Min(forwardIdx, secondForwardIdx)\n\t\t\t\t//SkipModeFrame[ 1 ] = LAST_FRAME + Max(forwardIdx, secondForwardIdx)\n\t\t\t}\n\t\t}\n\t}\n\tif (skipModeAllowed) {\n\t\tgf_bs_read_int_log(bs, 1, \"skip_mode_present\");\n\t}",
"\n\tif (FrameIsIntra || error_resilient_mode || !state->enable_warped_motion) {",
"\t}\n\telse {\n\t\tgf_bs_read_int_log(bs, 1, \"allow_warped_motion\");\n\t}",
"\tgf_bs_read_int_log(bs, 1, \"reduced_tx\");",
"\t//global_motion_params( )\n\tu32 ref;\n\tfor (ref = AV1_LAST_FRAME; ref <= AV1_ALTREF_FRAME; ref++) {\n\t\tu32 i;\n\t\tfor (i = 0; i < 6; i++) {\n\t\t\tstate->GmParams.coefs[ref][i] = ((i % 3 == 2) ? 1 << WARPEDMODEL_PREC_BITS : 0);\n\t\t}\n\t}\n\tif (!FrameIsIntra) {\n\t\tu32 refs;\n\t\tfor (refs = AV1_LAST_FRAME; refs <= AV1_ALTREF_FRAME; refs++) {\n\t\t\tu8 type = AV1_GMC_IDENTITY;\n\t\t\tBool is_global = gf_bs_read_int_log_idx(bs, 1, \"is_global\", refs);\n\t\t\tif (is_global) {\n\t\t\t\tBool is_rot_zoom = gf_bs_read_int_log_idx(bs, 1, \"is_rot_zoom\", refs);\n\t\t\t\tif (is_rot_zoom) {\n\t\t\t\t\ttype = AV1_GMC_ROTZOOM;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tBool is_trans = gf_bs_read_int_log_idx(bs, 1, \"is_translation\", refs);\n\t\t\t\t\ttype = is_trans ? AV1_GMC_TRANSLATION : AV1_GMC_AFFINE;",
"\t\t\t\t}\n\t\t\t}",
"\t\t\tif (type >= AV1_GMC_ROTZOOM) {\n\t\t\t\tav1_read_global_param(state, bs, type, refs, 2);\n\t\t\t\tav1_read_global_param(state, bs, type, refs, 3);\n\t\t\t\tif (type == AV1_GMC_AFFINE) {\n\t\t\t\t\tav1_read_global_param(state, bs, type, refs, 4);\n\t\t\t\t\tav1_read_global_param(state, bs, type, refs, 5);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstate->GmParams.coefs[refs][4] = -state->GmParams.coefs[refs][3];\n\t\t\t\t\tstate->GmParams.coefs[refs][5] = state->GmParams.coefs[refs][2];",
"\t\t\t\t}\n\t\t\t}\n\t\t\tif (type >= AV1_GMC_TRANSLATION) {\n\t\t\t\tav1_read_global_param(state, bs, type, refs, 0);\n\t\t\t\tav1_read_global_param(state, bs, type, refs, 1);\n\t\t\t}\n\t\t}\n\t}",
"\t//film_grain_params()\n\tif (!state->film_grain_params_present || (!state->frame_state.show_frame && !showable_frame)) {\n\t}\n\telse {\n\t\tu8 apply_grain = gf_bs_read_int_log(bs, 1, \"apply_grain\");\n\t\tif (apply_grain) {\n\t\t\tgf_bs_read_int_log(bs, 16, \"grain_seed\");\n\t\t\tu8 update_grain = 1;\n\t\t\tif (state->frame_state.frame_type == AV1_INTER_FRAME) {\n\t\t\t\tupdate_grain = gf_bs_read_int_log(bs, 1, \"update_grain\");\n\t\t\t}\n\t\t\tif (!update_grain) {\n\t\t\t\tgf_bs_read_int_log(bs, 3, \"film_grain_params_ref_idx\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tu32 i, num_y_points = gf_bs_read_int_log(bs, 4, \"num_y_points\");\n\t\t\t\tfor (i = 0; i < num_y_points; i++) {\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_y_value\", i);\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_y_scaling\", i);\n\t\t\t\t}\n\t\t\t\tu8 chroma_scaling_from_luma = 0;\n\t\t\t\tif (!state->config->monochrome)\n\t\t\t\t\tchroma_scaling_from_luma = gf_bs_read_int_log(bs, 1, \"chroma_scaling_from_luma\");",
"\t\t\t\tu8 num_cb_points = 0;\n\t\t\t\tu8 num_cr_points = 0;\n\t\t\t\tif (state->config->monochrome || chroma_scaling_from_luma ||\n\t\t\t\t\t((state->config->chroma_subsampling_x == 1) && (state->config->chroma_subsampling_y == 1) && (num_y_points == 0))\n\t\t\t\t\t) {\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnum_cb_points = gf_bs_read_int_log(bs, 4, \"num_cb_points\");\n\t\t\t\t\tfor (i = 0; i < num_cb_points; i++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_cb_value\", i);\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_cb_scaling\", i);\n\t\t\t\t\t}\n\t\t\t\t\tnum_cr_points = gf_bs_read_int_log(bs, 4, \"num_cr_points\");\n\t\t\t\t\tfor (i = 0; i < num_cr_points; i++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_cr_value\", i);\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"point_cr_scaling\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_bs_read_int_log(bs, 2, \"grain_scaling_minus_8\");\n\t\t\t\tu8 ar_coeff_lag = gf_bs_read_int_log(bs, 2, \"ar_coeff_lag\");\n\t\t\t\tu16 numPosLuma = 2 * ar_coeff_lag * (ar_coeff_lag + 1);\n\t\t\t\tu16 numPosChroma = numPosLuma;\n\t\t\t\tif (num_y_points) {\n\t\t\t\t\tnumPosChroma = numPosLuma + 1;\n\t\t\t\t\tfor (i = 0; i < numPosLuma; i++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"ar_coeffs_y_plus_128\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (chroma_scaling_from_luma || num_cb_points) {\n\t\t\t\t\tfor (i = 0; i < numPosChroma; i++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"ar_coeffs_cb_plus_128\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (chroma_scaling_from_luma || num_cr_points) {\n\t\t\t\t\tfor (i = 0; i < numPosChroma; i++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"ar_coeffs_cr_plus_128\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_bs_read_int_log(bs, 2, \"ar_coeff_shift_minus_6\");\n\t\t\t\tgf_bs_read_int_log(bs, 2, \"grain_scale_shift\");\n\t\t\t\tif (num_cb_points) {\n\t\t\t\t\tgf_bs_read_int_log(bs, 8, \"cb_mult\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 8, \"cb_luma_mult\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 9, \"cb_offset\");\n\t\t\t\t}\n\t\t\t\tif (num_cr_points) {\n\t\t\t\t\tgf_bs_read_int_log(bs, 8, \"cr_mult\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 8, \"cr_luma_mult\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 9, \"cr_offset\");\n\t\t\t\t}\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"overlap_flag\");\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"clip_to_restricted_range\");\n\t\t\t}\n\t\t}\n\t}",
"\t//end of uncompressed header !!\n}",
"GF_EXPORT\nvoid gf_av1_init_state(AV1State *state)\n{\n\tif (!state) return;\n\tmemset(state, 0, sizeof(AV1State));\n\tstate->color_primaries = 2;\n\tstate->transfer_characteristics = 2;\n\tstate->matrix_coefficients = 2;\n}",
"GF_EXPORT\nvoid gf_av1_reset_state(AV1State *state, Bool is_destroy)\n{\n\tGF_List *l1, *l2;",
"\tif (state->frame_state.header_obus) {\n\t\twhile (gf_list_count(state->frame_state.header_obus)) {\n\t\t\tGF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.header_obus);\n\t\t\tif (a->obu) gf_free(a->obu);\n\t\t\tgf_free(a);\n\t\t}\n\t}",
"\tif (state->frame_state.frame_obus) {\n\t\twhile (gf_list_count(state->frame_state.frame_obus)) {\n\t\t\tGF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.frame_obus);\n\t\t\tif (a->obu) gf_free(a->obu);\n\t\t\tgf_free(a);\n\t\t}\n\t}\n\tl1 = state->frame_state.frame_obus;\n\tl2 = state->frame_state.header_obus;\n\tmemset(&state->frame_state, 0, sizeof(AV1StateFrame));\n\tstate->frame_state.is_first_frame = GF_TRUE;",
"\tif (is_destroy) {\n\t\tgf_list_del(l1);\n\t\tgf_list_del(l2);\n\t\tif (state->bs) {\n\t\t\tu32 size;\n\t\t\tgf_bs_get_content_no_truncate(state->bs, &state->frame_obus, &size, &state->frame_obus_alloc);\n\t\t\tgf_bs_del(state->bs);\n\t\t}\n\t\tstate->bs = NULL;\n\t}\n\telse {\n\t\tstate->frame_state.frame_obus = l1;\n\t\tstate->frame_state.header_obus = l2;\n\t\tif (state->bs)\n\t\t\tgf_bs_seek(state->bs, 0);\n\t}\n}",
"static GF_Err av1_parse_tile_group(GF_BitStream *bs, AV1State *state, u64 obu_start, u64 obu_size)\n{\n\tu32 TileNum, tg_start = 0, tg_end = 0;\n\tBool numTiles = state->tileCols * state->tileRows;\n\tBool tile_start_and_end_present_flag = GF_FALSE;\n\tGF_Err e = GF_OK;\n\tif (numTiles > 1)\n\t\ttile_start_and_end_present_flag = gf_bs_read_int_log(bs, 1, \"tile_start_and_end_present_flag\");",
"\tif (numTiles == 1 || !tile_start_and_end_present_flag) {\n\t\ttg_start = 0;\n\t\ttg_end = numTiles - 1;\n\t\t/*state->frame_state.tg[0].start_idx = 0;\n\t\tstate->frame_state.tg[0].end_idx = numTiles - 1;*/\n\t}\n\telse {\n\t\tu32 tileBits = state->tileColsLog2 + state->tileRowsLog2;\n\t\t/*state->frame_state.tg[state->frame_state.tg_idx].start_idx*/ tg_start = gf_bs_read_int_log(bs, tileBits, \"tg_start\");\n\t\t/*state->frame_state.tg[state->frame_state.tg_idx].end_idx*/ tg_end = gf_bs_read_int_log(bs, tileBits, \"tg_end\");\n\t}\n\t/*state->frame_state.tg_idx++;*/",
"\tgf_bs_align(bs);",
"\tif (tg_end >= GF_ARRAY_LENGTH(state->frame_state.tiles))\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;",
"\tstate->frame_state.nb_tiles_in_obu = 0;\n\tfor (TileNum = tg_start; TileNum <= tg_end; TileNum++) {\n\t\tu32 tile_start_offset, tile_size;\n\t\t/*u32 tileRow = TileNum / state->tileCols;\n\t\tu32 tileCol = TileNum % state->tileCols;*/\n\t\tBool lastTile = TileNum == tg_end;\n\t\tu64 pos = gf_bs_get_position(bs);\n\t\tif (lastTile) {\n\t\t\ttile_start_offset = (u32)(pos - obu_start);\n\t\t\ttile_size = (u32)(obu_size - (pos - obu_start));\n\t\t}\n\t\telse {\n\t\t\tu64 tile_size_minus_1 = aom_av1_le(bs, state->tile_size_bytes, \"tile_size_minus_1\");\n\t\t\tpos = gf_bs_get_position(bs);\n\t\t\ttile_start_offset = (u32)(pos - obu_start);\n\t\t\ttile_size = (u32)(tile_size_minus_1 + 1/* + state->tile_size_bytes*/);\n\t\t}",
"\n\t\tif (tile_start_offset + tile_size > obu_size) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AV1] Error parsing tile group, tile %d start %d + size %d exceeds OBU length %d\\n\", TileNum, tile_start_offset, tile_size, obu_size));\n\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\tbreak;\n\t\t}",
"\t\tstate->frame_state.tiles[state->frame_state.nb_tiles_in_obu].obu_start_offset = tile_start_offset;\n\t\tstate->frame_state.tiles[state->frame_state.nb_tiles_in_obu].size = tile_size;\n\t\tgf_bs_skip_bytes(bs, tile_size);\n\t\tstate->frame_state.nb_tiles_in_obu++;\n\t}\n\tif (tg_end == numTiles - 1) {\n\t\tav1_decode_frame_wrapup(state);\n\t}\n\treturn e;\n}",
"static void av1_parse_frame_header(GF_BitStream *bs, AV1State *state)\n{\n\tAV1StateFrame *frame_state = &state->frame_state;\n\tif (frame_state->seen_frame_header == GF_FALSE) {\n\t\tu64 pos = gf_bs_get_position(bs);\n\t\tstate->frame_state.show_existing_frame = GF_FALSE;\n\t\tframe_state->seen_frame_header = GF_TRUE;\n\t\tav1_parse_uncompressed_header(bs, state);\n\t\tstate->frame_state.is_first_frame = GF_FALSE;\n\t\tstate->frame_state.uncompressed_header_bytes = (u32) (gf_bs_get_position(bs) - pos);",
"\t\tif (state->frame_state.show_existing_frame) {\n\t\t\tav1_decode_frame_wrapup(state);\n\t\t\tframe_state->seen_frame_header = GF_FALSE;\n\t\t}\n\t\telse {\n\t\t\t//TileNum = 0;\n\t\t\tframe_state->seen_frame_header = GF_TRUE;\n\t\t}\n\t}\n}",
"static GF_Err av1_parse_frame(GF_BitStream *bs, AV1State *state, u64 obu_start, u64 obu_size)\n{\n\tav1_parse_frame_header(bs, state);\n\t//byte alignment\n\tgf_bs_align(bs);\n\treturn av1_parse_tile_group(bs, state, obu_start, obu_size);\n}",
"static void on_aom_av1_eos(void *_state)\n{\n\tAV1State *state = (AV1State *)_state;\n\tstate->bs_overread = GF_TRUE;\n}",
"GF_EXPORT\nGF_Err gf_av1_parse_obu(GF_BitStream *bs, ObuType *obu_type, u64 *obu_size, u32 *obu_hdr_size, AV1State *state)\n{\n\tGF_Err e = GF_OK;\n\tu32 i, hdr_size;\n\tu64 pos = gf_bs_get_position(bs);",
"\tif (!bs || !obu_type || !state)\n\t\treturn GF_BAD_PARAM;",
"\tstate->bs_overread = GF_FALSE;\n\tgf_bs_set_eos_callback(bs, on_aom_av1_eos, state);",
"\tstate->obu_extension_flag = state->obu_has_size_field = 0;\n\tstate->temporal_id = state->spatial_id = 0;\n\tstate->frame_state.uncompressed_header_bytes = 0;\n\te = gf_av1_parse_obu_header(bs, obu_type, &state->obu_extension_flag, &state->obu_has_size_field, &state->temporal_id, &state->spatial_id);\n\tif (e)\n\t\treturn e;",
"\tif (state->obu_has_size_field) {\n\t\t*obu_size = (u32)gf_av1_leb128_read(bs, NULL);\n\t}\n\telse {\n\t\tif (*obu_size >= 1 + state->obu_extension_flag) {\n\t\t\t*obu_size = *obu_size - 1 - state->obu_extension_flag;\n\t\t}\n\t\telse {\n\t\t\tGF_LOG(state->config ? GF_LOG_WARNING : GF_LOG_DEBUG, GF_LOG_CODING, (\"[AV1] computed OBU size \"LLD\" (input value = \"LLU\"). Skipping.\\n\", *obu_size - 1 - state->obu_extension_flag, *obu_size));\n\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t}\n\thdr_size = (u32)(gf_bs_get_position(bs) - pos);\n\tif ((gf_bs_available(bs) < *obu_size) || state->bs_overread) {\n\t\tgf_bs_seek(bs, pos);\n\t\treturn GF_BUFFER_TOO_SMALL;\n\t}\n\t*obu_size += hdr_size;\n\tif (obu_hdr_size) *obu_hdr_size = hdr_size;",
"\n\tif (*obu_type != OBU_SEQUENCE_HEADER && *obu_type != OBU_TEMPORAL_DELIMITER &&\n\t\tstate->OperatingPointIdc != 0 && state->obu_extension_flag == 1)\n\t{\n\t\tu32 inTemporalLayer = (state->OperatingPointIdc >> state->temporal_id) & 1;\n\t\tu32 inSpatialLayer = (state->OperatingPointIdc >> (state->spatial_id + 8)) & 1;\n\t\tif (!inTemporalLayer || !inSpatialLayer) {\n\t\t\t*obu_type = -1;\n\t\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\t\treturn GF_OK;\n\t\t}\n\t}",
"\te = GF_OK;",
"\t/* for AVIF a1lx */\n\tfor (i = state->spatial_id; i < 4; i++) {\n\t\tstate->layer_size[i] = (u32) (pos + *obu_size);\n\t}",
"\tswitch (*obu_type) {\n\tcase OBU_SEQUENCE_HEADER:\n\t\tav1_parse_sequence_header_obu(bs, state);\n\t\tif (gf_bs_get_position(bs) > pos + *obu_size) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] Sequence header parsing consumed too many bytes !\\n\"));\n\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;",
"\tcase OBU_METADATA:\n#if 0\n\t\t//TODO + sample groups\n\t\tconst ObuMetadataType metadata_type = (u32)read_leb128(bs, NULL); we should check for 16 bits limit(AV1MetadataSampleGroupEntry) for ISOBMFF bindings, see https ://github.com/AOMediaCodec/av1-isobmff/pull/86#issuecomment-416659538\n\t\tif (metadata_type == OBU_METADATA_TYPE_ITUT_T35) {\n\t\t}\n\t\telse if (metadata_type == OBU_METADATA_TYPE_HDR_CLL) {\n\t\t}\n\t\telse if (metadata_type == OBU_METADATA_TYPE_HDR_MDCV) {\n\t\t}\n\t\telse if (metadata_type == OBU_METADATA_TYPE_SCALABILITY) {\n\t\t}\n\t\telse if (metadata_type == METADATA_TYPE_TIMECODE) {\n\t\t}\n#endif\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CODING, (\"[AV1] parsing for metadata is not implemented. Forwarding.\\n\"));",
"\t\tif (gf_bs_get_position(bs) > pos + *obu_size) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] Metadata parsing consumed too many bytes !\\n\"));\n\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;",
"\tcase OBU_FRAME_HEADER:\n\tcase OBU_REDUNDANT_FRAME_HEADER:\n\t\tif (state->config) {\n\t\t\tav1_parse_frame_header(bs, state);\n\t\t\tif (gf_bs_get_position(bs) > pos + *obu_size) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] Frame header parsing consumed too many bytes !\\n\"));\n\t\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t}\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;\n\tcase OBU_FRAME:\n\t\te = av1_parse_frame(bs, state, pos, *obu_size);\n\t\tif (gf_bs_get_position(bs) != pos + *obu_size) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] Frame parsing did not consume the right number of bytes !\\n\"));\n\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t}\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;\n\tcase OBU_TILE_GROUP:\n\t\tif (state->config) {\n\t\t\te = av1_parse_tile_group(bs, state, pos, *obu_size);\n\t\t\tif (gf_bs_get_position(bs) != pos + *obu_size) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] Tile group parsing did not consume the right number of bytes !\\n\"));\n\t\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t}\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;\n\tcase OBU_TEMPORAL_DELIMITER:\n\t\tstate->frame_state.seen_frame_header = GF_FALSE;\n\tcase OBU_PADDING:\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;\n\tdefault:\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[AV1] unknown OBU type %u (size \"LLU\"). Skipping.\\n\", *obu_type, *obu_size));\n\t\tgf_bs_seek(bs, pos + *obu_size);\n\t\tbreak;\n\t}\n\treturn e;\n}",
"\nGF_EXPORT\nGF_Err gf_media_prores_parse_bs(GF_BitStream *bs, GF_ProResFrameInfo *prores_frame)\n{\n\tu32 i, j;\n\tu64 start, pos;\n\tmemset(prores_frame, 0, sizeof(GF_ProResFrameInfo));",
"\tstart = gf_bs_get_position(bs);\n\tif (gf_bs_available(bs) < 10)\n\t\treturn GF_BUFFER_TOO_SMALL;",
"\tprores_frame->frame_size = gf_bs_read_u32(bs);\n\tprores_frame->frame_identifier = gf_bs_read_u32(bs);\n\tif (prores_frame->frame_identifier != GF_4CC('i','c','p','f')) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[ProRes] Invalid frame identifier, expected \\\"icpf\\\" got \\\"%s\\\"\\n\", gf_4cc_to_str(prores_frame->frame_identifier) ));\n\t\tgf_bs_seek(bs, start);\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\t/*parse frame header*/\n\tpos = gf_bs_get_position(bs);\n\tprores_frame->frame_hdr_size = gf_bs_read_u16(bs);\n\tif (gf_bs_available(bs) + 2 < prores_frame->frame_hdr_size) {\n\t\tgf_bs_seek(bs, start);\n\t\treturn GF_BUFFER_TOO_SMALL;\n\t}\n\tgf_bs_read_u8(bs);\n\tprores_frame->version = gf_bs_read_u8(bs);\n\tprores_frame->encoder_id = gf_bs_read_u32(bs);\n\tprores_frame->width = gf_bs_read_u16(bs);\n\tprores_frame->height = gf_bs_read_u16(bs);\n\tprores_frame->chroma_format = gf_bs_read_int(bs, 2);\n\tgf_bs_read_int(bs, 2);\n\tprores_frame->interlaced_mode = gf_bs_read_int(bs, 2);\n\tgf_bs_read_int(bs, 2);\n\tprores_frame->aspect_ratio_information = gf_bs_read_int(bs, 4);\n\tprores_frame->framerate_code = gf_bs_read_int(bs, 4);\n\tprores_frame->color_primaries = gf_bs_read_u8(bs);\n\tprores_frame->transfer_characteristics = gf_bs_read_u8(bs);\n\tprores_frame->matrix_coefficients = gf_bs_read_u8(bs);\n\tgf_bs_read_int(bs, 4);\n\tprores_frame->alpha_channel_type = gf_bs_read_int(bs, 4);\n\tgf_bs_read_int(bs, 14);\n\tprores_frame->load_luma_quant_matrix = gf_bs_read_int(bs, 1);\n\tprores_frame->load_chroma_quant_matrix = gf_bs_read_int(bs, 1);\n\tif (prores_frame->load_luma_quant_matrix) {\n\t\tfor (i=0; i<8; i++) {\n\t\t\tfor (j=0; j<8; j++) {\n\t\t\t\tprores_frame->luma_quant_matrix[i][j] = gf_bs_read_u8(bs);\n\t\t\t}\n\t\t}\n\t}\n\tif (prores_frame->load_chroma_quant_matrix) {\n\t\tfor (i=0; i<8; i++) {\n\t\t\tfor (j=0; j<8; j++) {\n\t\t\t\tprores_frame->chroma_quant_matrix[i][j] = gf_bs_read_u8(bs);\n\t\t\t}\n\t\t}\n\t}\n\tpos = gf_bs_get_position(bs) - pos;\n\tif (pos != prores_frame->frame_hdr_size) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[ProRes] Invalid frame header size, expected %d got %d\\n\", prores_frame->frame_hdr_size, (u32) pos));\n\t\tgf_bs_seek(bs, start);\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\tprores_frame->nb_pic = ((prores_frame->interlaced_mode==1) || (prores_frame->interlaced_mode==2)) ? 2 : 1;\n\tgf_bs_seek(bs, start);",
"\treturn GF_OK;\n}",
"#endif /*GPAC_DISABLE_AV_PARSERS*/",
"GF_EXPORT\nu8 gf_mp3_version(u32 hdr)\n{\n\treturn ((hdr >> 19) & 0x3);\n}",
"GF_EXPORT\nconst char *gf_mp3_version_name(u32 hdr)\n{\n\tu32 v = gf_mp3_version(hdr);\n\tswitch (v) {\n\tcase 0:\n\t\treturn \"MPEG-2.5\";\n\tcase 1:\n\t\treturn \"Reserved\";\n\tcase 2:\n\t\treturn \"MPEG-2\";\n\tcase 3:\n\t\treturn \"MPEG-1\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n}",
"#ifndef GPAC_DISABLE_AV_PARSERS",
"GF_EXPORT\nu8 gf_mp3_layer(u32 hdr)\n{\n\treturn 4 - (((hdr >> 17) & 0x3));\n}",
"GF_EXPORT\nu8 gf_mp3_num_channels(u32 hdr)\n{\n\tif (((hdr >> 6) & 0x3) == 3) return 1;\n\treturn 2;\n}",
"GF_EXPORT\nu16 gf_mp3_sampling_rate(u32 hdr)\n{\n\tu16 res;\n\t/* extract the necessary fields from the MP3 header */\n\tu8 version = gf_mp3_version(hdr);\n\tu8 sampleRateIndex = (hdr >> 10) & 0x3;",
"\tswitch (sampleRateIndex) {\n\tcase 0:\n\t\tres = 44100;\n\t\tbreak;\n\tcase 1:\n\t\tres = 48000;\n\t\tbreak;\n\tcase 2:\n\t\tres = 32000;\n\t\tbreak;\n\tdefault:\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[MPEG-1/2 Audio] Samplerate index not valid\\n\"));\n\t\treturn 0;\n\t}\n\t/*reserved or MPEG-1*/\n\tif (version & 1) return res;",
"\t/*MPEG-2*/\n\tres /= 2;\n\t/*MPEG-2.5*/\n\tif (version == 0) res /= 2;\n\treturn res;\n}",
"GF_EXPORT\nu16 gf_mp3_window_size(u32 hdr)\n{\n\tu8 version = gf_mp3_version(hdr);\n\tu8 layer = gf_mp3_layer(hdr);",
"\tif (layer == 3) {\n\t\tif (version == 3) return 1152;\n\t\treturn 576;\n\t}\n\tif (layer == 2) return 1152;\n\treturn 384;\n}",
"GF_EXPORT\nu8 gf_mp3_object_type_indication(u32 hdr)\n{\n\tswitch (gf_mp3_version(hdr)) {\n\tcase 3:\n\t\treturn GF_CODECID_MPEG_AUDIO;\n\tcase 2:\n\tcase 0:\n\t\treturn GF_CODECID_MPEG2_PART3;\n\tdefault:\n\t\treturn 0x00;\n\t}\n}",
"/*aligned bitrate parsing with libMAD*/",
"static\nu32 const bitrate_table[5][15] = {\n\t/* MPEG-1 */\n\t{\t0, 32000, 64000, 96000, 128000, 160000, 192000, 224000, /* Layer I */\n\t\t256000, 288000, 320000, 352000, 384000, 416000, 448000\n\t},\n\t{\t0, 32000, 48000, 56000, 64000, 80000, 96000, 112000, /* Layer II */\n\t\t128000, 160000, 192000, 224000, 256000, 320000, 384000\n\t},\n\t{\t0, 32000, 40000, 48000, 56000, 64000, 80000, 96000, /* Layer III */\n\t\t112000, 128000, 160000, 192000, 224000, 256000, 320000\n\t},",
"\t/* MPEG-2 LSF */\n\t{\t0, 32000, 48000, 56000, 64000, 80000, 96000, 112000, /* Layer I */\n\t\t128000, 144000, 160000, 176000, 192000, 224000, 256000\n\t},\n\t{\t0, 8000, 16000, 24000, 32000, 40000, 48000, 56000, /* Layers */\n\t\t64000, 80000, 96000, 112000, 128000, 144000, 160000\n\t} /* II & III */\n};",
"\nu32 gf_mp3_bit_rate(u32 hdr)\n{\n\tu8 version = gf_mp3_version(hdr);\n\tu8 layer = gf_mp3_layer(hdr);\n\tu8 bitRateIndex = (hdr >> 12) & 0xF;\n\tu32 lidx;\n\t/*MPEG-1*/\n\tif (version & 1) {\n\t\tif (!layer) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[MPEG-1/2 Audio] layer index not valid\\n\"));\n\t\t\treturn 0;\n\t\t}\n\t\tlidx = layer - 1;\n\t}\n\t/*MPEG-2/2.5*/\n\telse {\n\t\tlidx = 3 + (layer >> 1);\n\t}\n\tif (lidx>4) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[MPEG-1/2 Audio] layer index not valid\\n\"));\n\t\treturn 0;\n\t}\n\treturn bitrate_table[lidx][bitRateIndex];\n}",
"",
"GF_EXPORT\nu16 gf_mp3_frame_size(u32 hdr)\n{\n\tu8 version = gf_mp3_version(hdr);\n\tu8 layer = gf_mp3_layer(hdr);\n\tu32 pad = ((hdr >> 9) & 0x1) ? 1 : 0;\n\tu32 bitrate = gf_mp3_bit_rate(hdr);\n\tu32 samplerate = gf_mp3_sampling_rate(hdr);",
"\tu32 frameSize = 0;\n\tif (!samplerate || !bitrate) return 0;",
"\tif (layer == 1) {\n\t\tframeSize = ((12 * bitrate / samplerate) + pad) * 4;\n\t}\n\telse {\n\t\tu32 slots_per_frame = 144;\n\t\tif ((layer == 3) && !(version & 1)) slots_per_frame = 72;\n\t\tframeSize = (slots_per_frame * bitrate / samplerate) + pad;\n\t}\n\treturn (u16)frameSize;\n}",
"\nGF_EXPORT\nu32 gf_mp3_get_next_header(FILE* in)\n{\n\tu8 b, state = 0;\n\tu32 dropped = 0;\n\tunsigned char bytes[4];\n\tbytes[0] = bytes[1] = bytes[2] = bytes[3] = 0;",
"\twhile (1) {\n\t\tif (gf_fread(&b, 1, in) == 0) return 0;",
"\t\tif (state == 3) {\n\t\t\tbytes[state] = b;\n\t\t\treturn GF_4CC((u32)bytes[0], bytes[1], bytes[2], bytes[3]);\n\t\t}\n\t\tif (state == 2) {\n\t\t\tif (((b & 0xF0) == 0) || ((b & 0xF0) == 0xF0) || ((b & 0x0C) == 0x0C)) {\n\t\t\t\tif (bytes[1] == 0xFF) state = 1;\n\t\t\t\telse state = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 3;\n\t\t\t}\n\t\t}\n\t\tif (state == 1) {\n\t\t\tif (((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = 0;\n\t\t\t}\n\t\t}",
"\t\tif (state == 0) {\n\t\t\tif (b == 0xFF) {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif ((dropped == 0) && ((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {\n\t\t\t\t\tbytes[0] = (u8)0xFF;\n\t\t\t\t\tbytes[1] = b;\n\t\t\t\t\tstate = 2;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tdropped++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}",
"GF_EXPORT\nu32 gf_mp3_get_next_header_mem(const u8 *buffer, u32 size, u32 *pos)\n{\n\tu32 cur;\n\tu8 b, state = 0;\n\tu32 dropped = 0;\n\tunsigned char bytes[4];\n\tbytes[0] = bytes[1] = bytes[2] = bytes[3] = 0;",
"\tcur = 0;\n\t*pos = 0;\n\twhile (cur < size) {\n\t\tb = (u8)buffer[cur];\n\t\tcur++;",
"\t\tif (state == 3) {\n\t\t\tu32 val;\n\t\t\tbytes[state] = b;\n\t\t\tval = GF_4CC((u32)bytes[0], bytes[1], bytes[2], bytes[3]);\n\t\t\tif (gf_mp3_frame_size(val)) {\n\t\t\t\t*pos = dropped;\n\t\t\t\treturn val;\n\t\t\t}\n\t\t\tstate = 0;\n\t\t\tdropped = cur;\n\t\t}\n\t\tif (state == 2) {\n\t\t\tif (((b & 0xF0) == 0) || ((b & 0xF0) == 0xF0) || ((b & 0x0C) == 0x0C)) {\n\t\t\t\tif (bytes[1] == 0xFF) {\n\t\t\t\t\tstate = 1;\n\t\t\t\t\tdropped += 1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstate = 0;\n\t\t\t\t\tdropped = cur;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 3;\n\t\t\t}\n\t\t}\n\t\tif (state == 1) {\n\t\t\tif (((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = 0;\n\t\t\t\tdropped = cur;\n\t\t\t}\n\t\t}",
"\t\tif (state == 0) {\n\t\t\tif (b == 0xFF) {\n\t\t\t\tbytes[state] = b;\n\t\t\t\tstate = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdropped++;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}",
"#endif /*GPAC_DISABLE_AV_PARSERS*/",
"\nGF_EXPORT\nBool gf_avc_is_rext_profile(u8 profile_idc)\n{\n\tswitch (profile_idc) {\n\tcase 100:\n\tcase 110:\n\tcase 122:\n\tcase 244:\n\tcase 44:\n\tcase 83:\n\tcase 86:\n\tcase 118:\n\tcase 128:\n\tcase 138:\n\tcase 139:\n\tcase 134:\n\tcase 135:\n\t\treturn GF_TRUE;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n}",
"GF_EXPORT\nconst char *gf_avc_get_profile_name(u8 video_prof)\n{\n\tswitch (video_prof) {\n\tcase 0x42:\n\t\treturn \"Baseline\";\n\tcase 0x4D:\n\t\treturn \"Main\";\n\tcase 0x53:\n\t\treturn \"Scalable Baseline\";\n\tcase 0x56:\n\t\treturn \"Scalable High\";\n\tcase 0x58:\n\t\treturn \"Extended\";\n\tcase 0x64:\n\t\treturn \"High\";\n\tcase 0x6E:\n\t\treturn \"High 10\";\n\tcase 0x7A:\n\t\treturn \"High 4:2:2\";\n\tcase 0x90:\n\tcase 0xF4:\n\t\treturn \"High 4:4:4\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n}",
"GF_EXPORT\nconst char *gf_hevc_get_profile_name(u8 video_prof)\n{\n\tswitch (video_prof) {\n\tcase 0x01:\n\t\treturn \"Main\";\n\tcase 0x02:\n\t\treturn \"Main 10\";\n\tcase 0x03:\n\t\treturn \"Main Still Picture\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n}\nGF_EXPORT\nconst char *gf_avc_hevc_get_chroma_format_name(u8 chroma_format)\n{\n\tswitch (chroma_format) {\n\tcase 1:\n\t\treturn \"YUV 4:2:0\";\n\tcase 2:\n\t\treturn \"YUV 4:2:2\";\n\tcase 3:\n\t\treturn \"YUV 4:4:4\";\n\tdefault:\n\t\treturn \"Unknown\";\n\t}\n}",
"#ifndef GPAC_DISABLE_AV_PARSERS",
"u32 gf_bs_read_ue_log_idx3(GF_BitStream *bs, const char *fname, s32 idx1, s32 idx2, s32 idx3)\n{\n\tu32 val=0, code;\n\ts32 nb_lead = -1;\n\tu32 bits = 0;\n\tfor (code=0; !code; nb_lead++) {\n\t\tif (nb_lead>=32) {",
"\t\t\tbreak;\n\t\t}",
"\t\tcode = gf_bs_read_int(bs, 1);\n\t\tbits++;",
"\t}",
"\tif (nb_lead>=32) {\n\t\t//gf_bs_read_int keeps returning 0 on EOS, so if no more bits available, rbsp was truncated otherwise code is broken in rbsp)\n\t\t//we only test once nb_lead>=32 to avoid testing at each bit read\n\t\tif (!gf_bs_available(bs)) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[Core] exp-golomb read failed, not enough bits in bitstream !\\n\"));\n\t\t} else {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[Core] corrupted exp-golomb code, %d leading zeros, max 31 allowed !\\n\", nb_lead));\n\t\t}\n\t\treturn 0;",
"\t}",
"\tif (nb_lead) {\n\t\tu32 leads=1;\n\t\tval = gf_bs_read_int(bs, nb_lead);\n\t\tleads <<= nb_lead;\n\t\tleads -= 1;\n\t\tval += leads;\n//\t\tval += (1 << nb_lead) - 1;\n\t\tbits += nb_lead;\n\t}",
"\tif (fname) {\n\t\tgf_bs_log_idx(bs, bits, fname, val, idx1, idx2, idx3);\n\t}\n\treturn val;\n}",
"#define gf_bs_read_ue_log_idx2(_bs, _fname, _idx1, _idx2) gf_bs_read_ue_log_idx3(_bs, _fname, (s32) _idx1, (s32) _idx2, -1)\n#define gf_bs_read_ue_log_idx(_bs, _fname, _idx) gf_bs_read_ue_log_idx3(_bs, _fname, (s32) _idx, -1, -1)\n#define gf_bs_read_ue_log(_bs, _fname) gf_bs_read_ue_log_idx3(_bs, _fname, -1, -1, -1)",
"\nu32 gf_bs_read_ue(GF_BitStream *bs)\n{\n\treturn gf_bs_read_ue_log(bs, NULL);\n}",
"s32 gf_bs_read_se(GF_BitStream *bs)\n{\n\tu32 v = gf_bs_read_ue(bs);\n\tif ((v & 0x1) == 0) return (s32)(0 - (v >> 1));\n\treturn (v + 1) >> 1;\n}",
"s32 gf_bs_read_se_log_idx2(GF_BitStream *bs, const char *fname, s32 idx1, s32 idx2)\n{\n\ts32 res = gf_bs_read_se(bs);\n\tif (fname)\n\t\tgf_bs_log_idx(bs, -1, fname, res, idx1, idx2, -1);\n\treturn res;\n}\n#define gf_bs_read_se_log_idx(_bs, _fname, _idx) gf_bs_read_se_log_idx2(_bs, _fname, (s32) _idx, -1)\n#define gf_bs_read_se_log(_bs, _fname) gf_bs_read_se_log_idx2(_bs, _fname, -1, -1)",
"",
"void gf_bs_write_ue(GF_BitStream *bs, u32 num) {\n\ts32 length = 1;\n\ts32 temp = ++num;",
"\twhile (temp != 1) {\n\t\ttemp >>= 1;\n\t\tlength += 2;\n\t}",
"\tgf_bs_write_int(bs, 0, length >> 1);\n\tgf_bs_write_int(bs, num, (length + 1) >> 1);\n}",
"void gf_bs_write_se(GF_BitStream *bs, s32 num)\n{\n\tu32 v;\n\tif (num <= 0)\n\t\tv = (-1 * num) << 1;\n\telse\n\t\tv = (num << 1) - 1;",
"\tgf_bs_write_ue(bs, v);\n}",
"u32 gf_media_nalu_is_start_code(GF_BitStream *bs)\n{\n\tu8 s1, s2, s3, s4;\n\tBool is_sc = 0;\n\tu64 pos = gf_bs_get_position(bs);\n\ts1 = gf_bs_read_int(bs, 8);\n\ts2 = gf_bs_read_int(bs, 8);\n\tif (!s1 && !s2) {\n\t\ts3 = gf_bs_read_int(bs, 8);\n\t\tif (s3 == 0x01) is_sc = 3;\n\t\telse if (!s3) {\n\t\t\ts4 = gf_bs_read_int(bs, 8);\n\t\t\tif (s4 == 0x01) is_sc = 4;\n\t\t}\n\t}\n\tgf_bs_seek(bs, pos + is_sc);\n\treturn is_sc;\n}",
"/*read that amount of data at each IO access rather than fetching byte by byte...*/\n#define AVC_CACHE_SIZE\t4096",
"static u32 gf_media_nalu_locate_start_code_bs(GF_BitStream *bs, Bool locate_trailing)\n{\n\tu32 v, bpos, nb_cons_zeros = 0;\n\tchar avc_cache[AVC_CACHE_SIZE];\n\tu64 end, cache_start, load_size;\n\tu64 start = gf_bs_get_position(bs);\n\tif (start < 3) return 0;",
"\tload_size = 0;\n\tbpos = 0;\n\tcache_start = 0;\n\tend = 0;\n\tv = 0xffffffff;\n\twhile (!end) {\n\t\t/*refill cache*/\n\t\tif (bpos == (u32)load_size) {\n\t\t\tif (!gf_bs_available(bs)) break;\n\t\t\tload_size = gf_bs_available(bs);\n\t\t\tif (load_size > AVC_CACHE_SIZE) load_size = AVC_CACHE_SIZE;\n\t\t\tbpos = 0;\n\t\t\tcache_start = gf_bs_get_position(bs);\n\t\t\tgf_bs_read_data(bs, avc_cache, (u32)load_size);\n\t\t}\n\t\tv = ( (v<<8) & 0xFFFFFF00) | ((u32) avc_cache[bpos]);\n\t\tbpos++;",
"\t\tif (locate_trailing) {\n\t\t\tif ((v & 0x000000FF) == 0) nb_cons_zeros++;\n\t\t\telse nb_cons_zeros = 0;\n\t\t}",
"\t\tif (v == 0x00000001) end = cache_start + bpos - 4;\n\t\telse if ((v & 0x00FFFFFF) == 0x00000001) end = cache_start + bpos - 3;\n\t}",
"\tgf_bs_seek(bs, start);\n\tif (!end) end = gf_bs_get_size(bs);\n\tif (locate_trailing) {\n\t\tif (nb_cons_zeros >= 3)\n\t\t\treturn (u32)(end - start - nb_cons_zeros);\n\t}\n\treturn (u32)(end - start);\n}",
"GF_EXPORT\nu32 gf_media_nalu_next_start_code_bs(GF_BitStream *bs)\n{\n\treturn gf_media_nalu_locate_start_code_bs(bs, 0);\n}",
"GF_EXPORT\nu32 gf_media_nalu_next_start_code(const u8 *data, u32 data_len, u32 *sc_size)\n{\n\tu32 avail = data_len;\n\tconst u8 *cur = data;",
"\twhile (cur) {\n\t\tu32 v, bpos;\n\t\tu8 *next_zero = memchr(cur, 0, avail);\n\t\tif (!next_zero) return data_len;",
"\t\tv = 0xffffff00;\n\t\tbpos = (u32)(next_zero - data) + 1;\n\t\twhile (1) {\n\t\t\tu8 cval;\n\t\t\tif (bpos == (u32)data_len)\n\t\t\t\treturn data_len;",
"\t\t\tcval = data[bpos];\n\t\t\tv = ((v << 8) & 0xFFFFFF00) | ((u32)cval);\n\t\t\tbpos++;\n\t\t\tif (v == 0x00000001) {\n\t\t\t\t*sc_size = 4;\n\t\t\t\treturn bpos - 4;\n\t\t\t}\n\t\t\telse if ((v & 0x00FFFFFF) == 0x00000001) {\n\t\t\t\t*sc_size = 3;\n\t\t\t\treturn bpos - 3;\n\t\t\t}\n\t\t\tif (cval)\n\t\t\t\tbreak;\n\t\t}\n\t\tif (bpos >= data_len)\n\t\t\tbreak;\n\t\tcur = data + bpos;\n\t\tavail = data_len - bpos;\n\t}\n\treturn data_len;\n}",
"Bool gf_media_avc_slice_is_intra(AVCState *avc)\n{\n\tswitch (avc->s_info.slice_type) {\n\tcase GF_AVC_TYPE_I:\n\tcase GF_AVC_TYPE2_I:\n\tcase GF_AVC_TYPE_SI:\n\tcase GF_AVC_TYPE2_SI:\n\t\treturn 1;\n\tdefault:\n\t\treturn 0;\n\t}\n}",
"#if 0 //unused\nBool gf_media_avc_slice_is_IDR(AVCState *avc)\n{\n\tif (avc->sei.recovery_point.valid)\n\t{\n\t\tavc->sei.recovery_point.valid = 0;\n\t\treturn 1;\n\t}\n\tif (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE)\n\t\treturn 0;\n\treturn gf_media_avc_slice_is_intra(avc);\n}\n#endif",
"static const struct {\n\tu32 w, h;\n} avc_hevc_sar[] = {\n\t{ 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 },\n\t{ 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },\n\t{ 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },\n\t{ 64, 33 }, { 160,99 }, { 4, 3 }, { 3, 2 },\n\t{ 2, 1 }\n};",
"\n/*ISO 14496-10 (N11084) E.1.2*/\nstatic void avc_parse_hrd_parameters(GF_BitStream *bs, AVC_HRD *hrd)\n{\n\tint i, cpb_cnt_minus1;",
"\tcpb_cnt_minus1 = gf_bs_read_ue_log(bs, \"cpb_cnt_minus1\");\n\tif (cpb_cnt_minus1 > 31)\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] invalid cpb_cnt_minus1 value: %d (expected in [0;31])\\n\", cpb_cnt_minus1));\n\tgf_bs_read_int_log(bs, 4, \"bit_rate_scale\");\n\tgf_bs_read_int_log(bs, 4, \"cpb_size_scale\");",
"\t/*for( SchedSelIdx = 0; SchedSelIdx <= cpb_cnt_minus1; SchedSelIdx++ ) {*/\n\tfor (i = 0; i <= cpb_cnt_minus1; i++) {\n\t\tgf_bs_read_ue_log_idx(bs, \"bit_rate_value_minus1\", i);\n\t\tgf_bs_read_ue_log_idx(bs, \"cpb_size_value_minus1\", i);\n\t\tgf_bs_read_int_log_idx(bs, 1, \"cbr_flag\", i);\n\t}\n\tgf_bs_read_int_log(bs, 5, \"initial_cpb_removal_delay_length_minus1\");\n\thrd->cpb_removal_delay_length_minus1 = gf_bs_read_int_log(bs, 5, \"cpb_removal_delay_length_minus1\");\n\thrd->dpb_output_delay_length_minus1 = gf_bs_read_int_log(bs, 5, \"dpb_output_delay_length_minus1\");\n\thrd->time_offset_length = gf_bs_read_int_log(bs, 5, \"time_offset_length\");\n\treturn;\n}",
"/*returns the nal_size without emulation prevention bytes*/\nu32 gf_media_nalu_emulation_bytes_add_count(u8 *buffer, u32 nal_size)\n{\n\tu32 i = 0, emulation_bytes_count = 0;\n\tu8 num_zero = 0;",
"\twhile (i < nal_size) {\n\t\t/*ISO 14496-10: \"Within the NAL unit, any four-byte sequence that starts with 0x000003\n\t\tother than the following sequences shall not occur at any byte-aligned position:\n\t\t\\96 0x00000300\n\t\t\\96 0x00000301\n\t\t\\96 0x00000302\n\t\t\\96 0x00000303\"\n\t\t*/\n\t\tif (num_zero == 2 && (u8)buffer[i] < 0x04) {\n\t\t\t/*emulation code found*/\n\t\t\tnum_zero = 0;\n\t\t\temulation_bytes_count++;\n\t\t\tif (!buffer[i])\n\t\t\t\tnum_zero = 1;\n\t\t}\n\t\telse {\n\t\t\tif (!buffer[i])\n\t\t\t\tnum_zero++;\n\t\t\telse\n\t\t\t\tnum_zero = 0;\n\t\t}\n\t\ti++;\n\t}\n\treturn emulation_bytes_count;\n}",
"u32 gf_media_nalu_add_emulation_bytes(const u8 *buffer_src, u8 *buffer_dst, u32 nal_size)\n{\n\tu32 i = 0, emulation_bytes_count = 0;\n\tu8 num_zero = 0;",
"\twhile (i < nal_size) {\n\t\t/*ISO 14496-10: \"Within the NAL unit, any four-byte sequence that starts with 0x000003\n\t\tother than the following sequences shall not occur at any byte-aligned position:\n\t\t0x00000300\n\t\t0x00000301\n\t\t0x00000302\n\t\t0x00000303\"\n\t\t*/\n\t\tif (num_zero == 2 && (u8)buffer_src[i] < 0x04) {\n\t\t\t/*add emulation code*/\n\t\t\tnum_zero = 0;\n\t\t\tbuffer_dst[i + emulation_bytes_count] = 0x03;\n\t\t\temulation_bytes_count++;\n\t\t\tif (!buffer_src[i])\n\t\t\t\tnum_zero = 1;\n\t\t}\n\t\telse {\n\t\t\tif (!buffer_src[i])\n\t\t\t\tnum_zero++;\n\t\t\telse\n\t\t\t\tnum_zero = 0;\n\t\t}\n\t\tbuffer_dst[i + emulation_bytes_count] = buffer_src[i];\n\t\ti++;\n\t}\n\treturn nal_size + emulation_bytes_count;\n}",
"/*returns the nal_size without emulation prevention bytes*/\nu32 gf_media_nalu_emulation_bytes_remove_count(const u8 *buffer, u32 nal_size)\n{\n\tu32 i = 0, emulation_bytes_count = 0;\n\tu8 num_zero = 0;\n\tif (!buffer || !nal_size) return 0;",
"\twhile (i < nal_size)\n\t{\n\t\t/*ISO 14496-10: \"Within the NAL unit, any four-byte sequence that starts with 0x000003\n\t\t other than the following sequences shall not occur at any byte-aligned position:\n\t\t \\96 0x00000300\n\t\t \\96 0x00000301\n\t\t \\96 0x00000302\n\t\t \\96 0x00000303\"\n\t\t*/\n\t\tif (num_zero == 2\n\t\t\t&& buffer[i] == 0x03\n\t\t\t&& i + 1 < nal_size /*next byte is readable*/\n\t\t\t&& (u8)buffer[i + 1] < 0x04)\n\t\t{\n\t\t\t/*emulation code found*/\n\t\t\tnum_zero = 0;\n\t\t\temulation_bytes_count++;\n\t\t\ti++;\n\t\t}",
"\t\tif (!buffer[i])\n\t\t\tnum_zero++;\n\t\telse\n\t\t\tnum_zero = 0;",
"\t\ti++;\n\t}",
"\treturn emulation_bytes_count;\n}",
"/*nal_size is updated to allow better error detection*/\nGF_EXPORT\nu32 gf_media_nalu_remove_emulation_bytes(const u8 *buffer_src, u8 *buffer_dst, u32 nal_size)\n{\n\tu32 i = 0, emulation_bytes_count = 0;\n\tu8 num_zero = 0;",
"\twhile (i < nal_size)\n\t{\n\t\t/*ISO 14496-10: \"Within the NAL unit, any four-byte sequence that starts with 0x000003\n\t\t other than the following sequences shall not occur at any byte-aligned position:\n\t\t 0x00000300\n\t\t 0x00000301\n\t\t 0x00000302\n\t\t 0x00000303\"\n\t\t*/\n\t\tif (num_zero == 2\n\t\t\t&& buffer_src[i] == 0x03\n\t\t\t&& i + 1 < nal_size /*next byte is readable*/\n\t\t\t&& (u8)buffer_src[i + 1] < 0x04)\n\t\t{\n\t\t\t/*emulation code found*/\n\t\t\tnum_zero = 0;\n\t\t\temulation_bytes_count++;\n\t\t\ti++;\n\t\t}",
"\t\tbuffer_dst[i - emulation_bytes_count] = buffer_src[i];",
"\t\tif (!buffer_src[i])\n\t\t\tnum_zero++;\n\t\telse\n\t\t\tnum_zero = 0;",
"\t\ti++;\n\t}",
"\treturn nal_size - emulation_bytes_count;\n}",
"static s32 gf_avc_read_sps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos, u32 nal_hdr)\n{\n\tAVC_SPS *sps;\n\ts32 mb_width, mb_height, sps_id = -1;\n\tu32 profile_idc, level_idc, pcomp, i, chroma_format_idc, cl = 0, cr = 0, ct = 0, cb = 0, luma_bd, chroma_bd;\n\tu8 separate_colour_plane_flag = 0;",
"\tif (!vui_flag_pos) {\n\t\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\t}",
"\tif (!bs) {\n\t\treturn -1;\n\t}",
"\tif (!nal_hdr) {\n\t\tgf_bs_read_int_log(bs, 1, \"forbidden_zero_bit\");\n\t\tgf_bs_read_int_log(bs, 2, \"nal_ref_idc\");\n\t\tgf_bs_read_int_log(bs, 5, \"nal_unit_type\");\n\t}\n\tprofile_idc = gf_bs_read_int_log(bs, 8, \"profile_idc\");",
"\tpcomp = gf_bs_read_int_log(bs, 8, \"profile_compatibility\");\n\t/*sanity checks*/\n\tif (pcomp & 0x3)\n\t\treturn -1;",
"\tlevel_idc = gf_bs_read_int_log(bs, 8, \"level_idc\");",
"\t/*SubsetSps is used to be sure that AVC SPS are not going to be scratched\n\tby subset SPS. According to the SVC standard, subset SPS can have the same sps_id\n\tthan its base layer, but it does not refer to the same SPS. */\n\tsps_id = gf_bs_read_ue_log(bs, \"sps_id\") + GF_SVC_SSPS_ID_SHIFT * subseq_sps;\n\tif ((sps_id < 0) || (sps_id >= 32)) {\n\t\treturn -1;\n\t}",
"\tluma_bd = chroma_bd = 0;\n\tsps = &avc->sps[sps_id];\n\tchroma_format_idc = sps->ChromaArrayType = 1;\n\tsps->state |= subseq_sps ? AVC_SUBSPS_PARSED : AVC_SPS_PARSED;",
"\t/*High Profile and SVC*/\n\tswitch (profile_idc) {\n\tcase 100:\n\tcase 110:\n\tcase 122:\n\tcase 244:\n\tcase 44:\n\t\t/*sanity checks: note1 from 7.4.2.1.1 of iso/iec 14496-10-N11084*/\n\t\tif (pcomp & 0xE0)\n\t\t\treturn -1;\n\tcase 83:\n\tcase 86:\n\tcase 118:\n\tcase 128:\n\t\tchroma_format_idc = gf_bs_read_ue_log(bs, \"chroma_format_idc\");\n\t\tsps->ChromaArrayType = chroma_format_idc;\n\t\tif (chroma_format_idc == 3) {\n\t\t\tseparate_colour_plane_flag = gf_bs_read_int_log(bs, 1, \"separate_colour_plane_flag\");\n\t\t\t/*\n\t\t\tDepending on the value of separate_colour_plane_flag, the value of the variable ChromaArrayType is assigned as follows.\n\t\t\t\\96\tIf separate_colour_plane_flag is equal to 0, ChromaArrayType is set equal to chroma_format_idc.\n\t\t\t\\96\tOtherwise (separate_colour_plane_flag is equal to 1), ChromaArrayType is set equal to 0.\n\t\t\t*/\n\t\t\tif (separate_colour_plane_flag) sps->ChromaArrayType = 0;\n\t\t}\n\t\tluma_bd = gf_bs_read_ue_log(bs, \"luma_bit_depth\");\n\t\tchroma_bd = gf_bs_read_ue_log(bs, \"chroma_bit_depth\");\n\t\t/*qpprime_y_zero_transform_bypass_flag = */ gf_bs_read_int_log(bs, 1, \"qpprime_y_zero_transform_bypass_flag\");\n\t\t/*seq_scaling_matrix_present_flag*/\n\t\tif (gf_bs_read_int_log(bs, 1, \"seq_scaling_matrix_present_flag\")) {\n\t\t\tu32 k;\n\t\t\tfor (k = 0; k < 8; k++) {\n\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"seq_scaling_list_present_flag\", k)) {\n\t\t\t\t\tu32 z, last = 8, next = 8;\n\t\t\t\t\tu32 sl = k < 6 ? 16 : 64;\n\t\t\t\t\tfor (z = 0; z < sl; z++) {\n\t\t\t\t\t\tif (next) {\n\t\t\t\t\t\t\ts32 delta = gf_bs_read_se(bs);\n\t\t\t\t\t\t\tnext = (last + delta + 256) % 256;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlast = next ? next : last;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}",
"\tsps->profile_idc = profile_idc;\n\tsps->level_idc = level_idc;\n\tsps->prof_compat = pcomp;\n\tsps->log2_max_frame_num = gf_bs_read_ue_log(bs, \"log2_max_frame_num\") + 4;\n\tsps->poc_type = gf_bs_read_ue_log(bs, \"poc_type\");\n\tsps->chroma_format = chroma_format_idc;\n\tsps->luma_bit_depth_m8 = luma_bd;\n\tsps->chroma_bit_depth_m8 = chroma_bd;",
"\tif (sps->poc_type == 0) {\n\t\tsps->log2_max_poc_lsb = gf_bs_read_ue_log(bs, \"log2_max_poc_lsb\") + 4;\n\t}\n\telse if (sps->poc_type == 1) {\n\t\tsps->delta_pic_order_always_zero_flag = gf_bs_read_int_log(bs, 1, \"delta_pic_order_always_zero_flag\");\n\t\tsps->offset_for_non_ref_pic = gf_bs_read_se_log(bs, \"offset_for_non_ref_pic\");\n\t\tsps->offset_for_top_to_bottom_field = gf_bs_read_se_log(bs, \"offset_for_top_to_bottom_field\");\n\t\tsps->poc_cycle_length = gf_bs_read_ue_log(bs, \"poc_cycle_length\");\n\t\tif (sps->poc_cycle_length > GF_ARRAY_LENGTH(sps->offset_for_ref_frame)) {\n\t\t\tsps->poc_cycle_length = 255;\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[avc-h264] offset_for_ref_frame overflow from poc_cycle_length\\n\"));\n\t\t\treturn -1;\n\t\t}\n\t\tfor (i = 0; i < sps->poc_cycle_length; i++)\n\t\t\tsps->offset_for_ref_frame[i] = gf_bs_read_se_log_idx(bs, \"offset_for_ref_frame\", i);\n\t}\n\tif (sps->poc_type > 2) {\n\t\treturn -1;\n\t}\n\tsps->max_num_ref_frames = gf_bs_read_ue_log(bs, \"max_num_ref_frames\");\n\tsps->gaps_in_frame_num_value_allowed_flag = gf_bs_read_int_log(bs, 1, \"gaps_in_frame_num_value_allowed_flag\");\n\tmb_width = gf_bs_read_ue_log(bs, \"pic_width_in_mbs_minus1\") + 1;\n\tmb_height = gf_bs_read_ue_log(bs, \"pic_height_in_map_units_minus1\") + 1;",
"\tsps->frame_mbs_only_flag = gf_bs_read_int_log(bs, 1, \"frame_mbs_only_flag\");",
"\tsps->width = mb_width * 16;\n\tsps->height = (2 - sps->frame_mbs_only_flag) * mb_height * 16;",
"\tif (!sps->frame_mbs_only_flag) sps->mb_adaptive_frame_field_flag = gf_bs_read_int_log(bs, 1, \"mb_adaptive_frame_field_flag\");\n\tgf_bs_read_int_log(bs, 1, \"direct_8x8_inference_flag\");",
"\tif (gf_bs_read_int_log(bs, 1, \"frame_cropping_flag\")) {\n\t\tint CropUnitX, CropUnitY, SubWidthC = -1, SubHeightC = -1;",
"\t\tif (chroma_format_idc == 1) {\n\t\t\tSubWidthC = 2; SubHeightC = 2;\n\t\t}\n\t\telse if (chroma_format_idc == 2) {\n\t\t\tSubWidthC = 2; SubHeightC = 1;\n\t\t}\n\t\telse if ((chroma_format_idc == 3) && (separate_colour_plane_flag == 0)) {\n\t\t\tSubWidthC = 1; SubHeightC = 1;\n\t\t}",
"\t\tif (sps->ChromaArrayType == 0) {\n\t\t\tassert(SubWidthC == -1);\n\t\t\tCropUnitX = 1;\n\t\t\tCropUnitY = 2 - sps->frame_mbs_only_flag;\n\t\t}\n\t\telse {\n\t\t\tCropUnitX = SubWidthC;\n\t\t\tCropUnitY = SubHeightC * (2 - sps->frame_mbs_only_flag);\n\t\t}",
"\t\tcl = gf_bs_read_ue_log(bs, \"frame_crop_left_offset\");\n\t\tcr = gf_bs_read_ue_log(bs, \"frame_crop_right_offset\");\n\t\tct = gf_bs_read_ue_log(bs, \"frame_crop_top_offset\");\n\t\tcb = gf_bs_read_ue_log(bs, \"frame_crop_bottom_offset\");",
"\t\tsps->width -= CropUnitX * (cl + cr);\n\t\tsps->height -= CropUnitY * (ct + cb);\n\t\tcl *= CropUnitX;\n\t\tcr *= CropUnitX;\n\t\tct *= CropUnitY;\n\t\tcb *= CropUnitY;\n\t}\n\tsps->crop.left = cl;\n\tsps->crop.right = cr;\n\tsps->crop.top = ct;\n\tsps->crop.bottom = cb;",
"\tif (vui_flag_pos) {\n\t\t*vui_flag_pos = (u32)gf_bs_get_bit_offset(bs);\n\t}\n\t/*vui_parameters_present_flag*/\n\tsps->vui_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vui_parameters_present_flag\");\n\tif (sps->vui_parameters_present_flag) {\n\t\tsps->vui.aspect_ratio_info_present_flag = gf_bs_read_int_log(bs, 1, \"aspect_ratio_info_present_flag\");\n\t\tif (sps->vui.aspect_ratio_info_present_flag) {\n\t\t\ts32 aspect_ratio_idc = gf_bs_read_int_log(bs, 8, \"aspect_ratio_idc\");\n\t\t\tif (aspect_ratio_idc == 255) {\n\t\t\t\tsps->vui.par_num = gf_bs_read_int_log(bs, 16, \"aspect_ratio_num\");\n\t\t\t\tsps->vui.par_den = gf_bs_read_int_log(bs, 16, \"aspect_ratio_den\");\n\t\t\t}\n\t\t\telse if (aspect_ratio_idc < GF_ARRAY_LENGTH(avc_hevc_sar) ) {\n\t\t\t\tsps->vui.par_num = avc_hevc_sar[aspect_ratio_idc].w;\n\t\t\t\tsps->vui.par_den = avc_hevc_sar[aspect_ratio_idc].h;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] Unknown aspect_ratio_idc: your video may have a wrong aspect ratio. Contact the GPAC team!\\n\"));\n\t\t\t}\n\t\t}\n\t\tsps->vui.overscan_info_present_flag = gf_bs_read_int_log(bs, 1, \"overscan_info_present_flag\");\n\t\tif (sps->vui.overscan_info_present_flag)\n\t\t\tgf_bs_read_int_log(bs, 1, \"overscan_appropriate_flag\");",
"\t\t/* default values */\n\t\tsps->vui.video_format = 5;\n\t\tsps->vui.colour_primaries = 2;\n\t\tsps->vui.transfer_characteristics = 2;\n\t\tsps->vui.matrix_coefficients = 2;\n\t\t/* now read values if possible */\n\t\tsps->vui.video_signal_type_present_flag = gf_bs_read_int_log(bs, 1, \"video_signal_type_present_flag\");\n\t\tif (sps->vui.video_signal_type_present_flag) {\n\t\t\tsps->vui.video_format = gf_bs_read_int_log(bs, 3, \"video_format\");\n\t\t\tsps->vui.video_full_range_flag = gf_bs_read_int_log(bs, 1, \"video_full_range_flag\");\n\t\t\tsps->vui.colour_description_present_flag = gf_bs_read_int_log(bs, 1, \"colour_description_present_flag\");\n\t\t\tif (sps->vui.colour_description_present_flag) {\n\t\t\t\tsps->vui.colour_primaries = gf_bs_read_int_log(bs, 8, \"colour_primaries\");\n\t\t\t\tsps->vui.transfer_characteristics = gf_bs_read_int_log(bs, 8, \"transfer_characteristics\");\n\t\t\t\tsps->vui.matrix_coefficients = gf_bs_read_int_log(bs, 8, \"matrix_coefficients\");\n\t\t\t}\n\t\t}",
"\t\tif (gf_bs_read_int_log(bs, 1, \"chroma_location_info_present_flag\")) {\n\t\t\tgf_bs_read_ue_log(bs, \"chroma_sample_location_type_top_field\");\n\t\t\tgf_bs_read_ue_log(bs, \"chroma_sample_location_type_bottom_field\");\n\t\t}",
"\t\tsps->vui.timing_info_present_flag = gf_bs_read_int_log(bs, 1, \"timing_info_present_flag\");\n\t\tif (sps->vui.timing_info_present_flag) {\n\t\t\tsps->vui.num_units_in_tick = gf_bs_read_int_log(bs, 32, \"num_units_in_tick\");\n\t\t\tsps->vui.time_scale = gf_bs_read_int_log(bs, 32, \"time_scale\");\n\t\t\tsps->vui.fixed_frame_rate_flag = gf_bs_read_int_log(bs, 1, \"fixed_frame_rate_flag\");\n\t\t}",
"\t\tsps->vui.nal_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"nal_hrd_parameters_present_flag\");\n\t\tif (sps->vui.nal_hrd_parameters_present_flag)\n\t\t\tavc_parse_hrd_parameters(bs, &sps->vui.hrd);",
"\t\tsps->vui.vcl_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vcl_hrd_parameters_present_flag\");\n\t\tif (sps->vui.vcl_hrd_parameters_present_flag)\n\t\t\tavc_parse_hrd_parameters(bs, &sps->vui.hrd);",
"\t\tif (sps->vui.nal_hrd_parameters_present_flag || sps->vui.vcl_hrd_parameters_present_flag)\n\t\t\tsps->vui.low_delay_hrd_flag = gf_bs_read_int_log(bs, 1, \"low_delay_hrd_flag\");",
"\t\tsps->vui.pic_struct_present_flag = gf_bs_read_int_log(bs, 1, \"pic_struct_present_flag\");\n\t}\n\t/*end of seq_parameter_set_data*/",
"\tif (subseq_sps) {\n\t\tif ((profile_idc == 83) || (profile_idc == 86)) {\n\t\t\tu8 extended_spatial_scalability_idc;\n\t\t\t/*parsing seq_parameter_set_svc_extension*/",
"\t\t\tgf_bs_read_int_log(bs, 1, \"inter_layer_deblocking_filter_control_present_flag\");\n\t\t\textended_spatial_scalability_idc = gf_bs_read_int_log(bs, 2, \"extended_spatial_scalability_idc\");\n\t\t\tif (sps->ChromaArrayType == 1 || sps->ChromaArrayType == 2) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"chroma_phase_x_plus1_flag\");\n\t\t\t}\n\t\t\tif (sps->ChromaArrayType == 1) {\n\t\t\t\tgf_bs_read_int_log(bs, 2, \"chroma_phase_y_plus1\");\n\t\t\t}\n\t\t\tif (extended_spatial_scalability_idc == 1) {\n\t\t\t\tif (sps->ChromaArrayType > 0) {\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"seq_ref_layer_chroma_phase_x_plus1_flag\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 2, \"seq_ref_layer_chroma_phase_y_plus1\");\n\t\t\t\t}\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_left_offset\");\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_top_offset\");\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_right_offset\");\n\t\t\t\tgf_bs_read_se_log(bs, \"seq_scaled_ref_layer_bottom_offset\");\n\t\t\t}\n\t\t\tif (gf_bs_read_int_log(bs, 1, \"seq_tcoeff_level_prediction_flag\")) {\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"adaptive_tcoeff_level_prediction_flag\");\n\t\t\t}\n\t\t\tgf_bs_read_int_log(bs, 1, \"slice_header_restriction_flag\");",
"\t\t\tif (gf_bs_read_int_log(bs, 1, \"svc_vui_parameters_present\")) {\n\t\t\t\tu32 vui_ext_num_entries_minus1 = gf_bs_read_ue_log(bs, \"vui_ext_num_entries_minus1\");",
"\t\t\t\tfor (i = 0; i <= vui_ext_num_entries_minus1; i++) {\n\t\t\t\t\tu8 vui_ext_nal_hrd_parameters_present_flag, vui_ext_vcl_hrd_parameters_present_flag, vui_ext_timing_info_present_flag;\n\t\t\t\t\tgf_bs_read_int_log(bs, 3, \"vui_ext_dependency_id\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 4, \"vui_ext_quality_id\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 3, \"vui_ext_temporal_id\");\n\t\t\t\t\tvui_ext_timing_info_present_flag = gf_bs_read_int_log(bs, 1, \"vui_ext_timing_info_present_flag\");\n\t\t\t\t\tif (vui_ext_timing_info_present_flag) {\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 32, \"vui_ext_num_units_in_tick\");\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 32, \"vui_ext_time_scale\");\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"vui_ext_fixed_frame_rate_flag\");\n\t\t\t\t\t}\n\t\t\t\t\tvui_ext_nal_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vui_ext_nal_hrd_parameters_present_flag\");\n\t\t\t\t\tif (vui_ext_nal_hrd_parameters_present_flag) {\n\t\t\t\t\t\t//hrd_parameters( )\n\t\t\t\t\t}\n\t\t\t\t\tvui_ext_vcl_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vui_ext_vcl_hrd_parameters_present_flag\");\n\t\t\t\t\tif (vui_ext_vcl_hrd_parameters_present_flag) {\n\t\t\t\t\t\t//hrd_parameters( )\n\t\t\t\t\t}\n\t\t\t\t\tif (vui_ext_nal_hrd_parameters_present_flag || vui_ext_vcl_hrd_parameters_present_flag) {\n\t\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"vui_ext_low_delay_hrd_flag\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"vui_ext_pic_struct_present_flag\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if ((profile_idc == 118) || (profile_idc == 128)) {\n\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CODING, (\"[avc-h264] MVC parsing not implemented - skipping parsing end of Subset SPS\\n\"));\n\t\t\treturn sps_id;\n\t\t}",
"\t\tif (gf_bs_read_int_log(bs, 1, \"additional_extension2\")) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] skipping parsing end of Subset SPS (additional_extension2)\\n\"));\n\t\t\treturn sps_id;\n\t\t}\n\t}\n\treturn sps_id;\n}",
"GF_EXPORT\ns32 gf_avc_read_sps_bs(GF_BitStream *bs, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos)\n{\n\treturn gf_avc_read_sps_bs_internal(bs, avc, subseq_sps, vui_flag_pos, 0);\n}",
"GF_EXPORT\ns32 gf_avc_read_sps(const u8 *sps_data, u32 sps_size, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos)\n{\n\ts32 sps_id = -1;\n\tGF_BitStream *bs;\n\tchar *sps_data_without_emulation_bytes = NULL;\n\tu32 sps_data_without_emulation_bytes_size = 0;",
"\tif (vui_flag_pos) {\n\t\t/*SPS still contains emulation bytes*/\n\t\tsps_data_without_emulation_bytes = gf_malloc(sps_size * sizeof(char));\n\t\tsps_data_without_emulation_bytes_size = gf_media_nalu_remove_emulation_bytes(sps_data, sps_data_without_emulation_bytes, sps_size);\n\t\tbs = gf_bs_new(sps_data_without_emulation_bytes, sps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);",
"\t\t*vui_flag_pos = 0;\n\t}\n\telse {\n\t\tbs = gf_bs_new(sps_data, sps_size, GF_BITSTREAM_READ);\n\t}",
"\tif (!bs) {\n\t\tsps_id = -1;\n\t\tgoto exit;\n\t}",
"\tsps_id = gf_avc_read_sps_bs(bs, avc, subseq_sps, vui_flag_pos);",
"exit:\n\tgf_bs_del(bs);\n\tif (sps_data_without_emulation_bytes) gf_free(sps_data_without_emulation_bytes);\n\treturn sps_id;\n}",
"static s32 gf_avc_read_pps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 nal_hdr)\n{\n\ts32 pps_id;\n\tAVC_PPS *pps;",
"\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tif (!nal_hdr) {\n\t\tgf_bs_read_int_log(bs, 1, \"forbidden_zero_bit\");\n\t\tgf_bs_read_int_log(bs, 2, \"nal_ref_idc\");\n\t\tgf_bs_read_int_log(bs, 5, \"nal_unit_type\");\n\t}\n\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\tif ((pps_id<0) || (pps_id >= 255)) {\n\t\treturn -1;\n\t}\n\tpps = &avc->pps[pps_id];\n\tpps->id = pps_id;",
"\tif (!pps->status) pps->status = 1;\n\tpps->sps_id = gf_bs_read_ue_log(bs, \"sps_id\");\n\tif ((pps->sps_id<0) || (pps->sps_id >= 32)) {\n\t\tpps->sps_id = 0;\n\t\treturn -1;\n\t}\n\t/*sps_id may be refer to regular SPS or subseq sps, depending on the coded slice referring to the pps*/\n\tif (!avc->sps[pps->sps_id].state && !avc->sps[pps->sps_id + GF_SVC_SSPS_ID_SHIFT].state) {\n\t\treturn -1;\n\t}\n\tavc->pps_active_idx = pps->id; /*set active sps*/\n\tavc->sps_active_idx = pps->sps_id; /*set active sps*/\n\tpps->entropy_coding_mode_flag = gf_bs_read_int_log(bs, 1, \"entropy_coding_mode_flag\");\n\tpps->pic_order_present = gf_bs_read_int_log(bs, 1, \"pic_order_present\");\n\tpps->slice_group_count = gf_bs_read_ue_log(bs, \"slice_group_count_minus1\") + 1;\n\tif (pps->slice_group_count > 1) {\n\t\tu32 iGroup;\n\t\tpps->mb_slice_group_map_type = gf_bs_read_ue_log(bs, \"mb_slice_group_map_type\");\n\t\tif (pps->mb_slice_group_map_type == 0) {\n\t\t\tfor (iGroup = 0; iGroup <= pps->slice_group_count - 1; iGroup++)\n\t\t\t\tgf_bs_read_ue_log_idx(bs, \"run_length_minus1\", iGroup);\n\t\t}\n\t\telse if (pps->mb_slice_group_map_type == 2) {\n\t\t\tfor (iGroup = 0; iGroup < pps->slice_group_count - 1; iGroup++) {\n\t\t\t\tgf_bs_read_ue_log_idx(bs, \"top_left\", iGroup);\n\t\t\t\tgf_bs_read_ue_log_idx(bs, \"bottom_right\", iGroup);\n\t\t\t}\n\t\t}\n\t\telse if (pps->mb_slice_group_map_type == 3 || pps->mb_slice_group_map_type == 4 || pps->mb_slice_group_map_type == 5) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"slice_group_change_direction_flag\");\n\t\t\tgf_bs_read_ue_log(bs, \"slice_group_change_rate_minus1\");\n\t\t}\n\t\telse if (pps->mb_slice_group_map_type == 6) {\n\t\t\tu32 i;\n\t\t\tpps->pic_size_in_map_units_minus1 = gf_bs_read_ue_log(bs, \"pic_size_in_map_units_minus1\");\n\t\t\tfor (i = 0; i <= pps->pic_size_in_map_units_minus1; i++) {\n\t\t\t\tgf_bs_read_int_log_idx(bs, (u32)ceil(log(pps->slice_group_count) / log(2)), \"slice_group_id\", i);\n\t\t\t}\n\t\t}\n\t}\n\tpps->num_ref_idx_l0_default_active_minus1 = gf_bs_read_ue_log(bs, \"num_ref_idx_l0_default_active_minus1\");\n\tpps->num_ref_idx_l1_default_active_minus1 = gf_bs_read_ue_log(bs, \"num_ref_idx_l1_default_active_minus1\");",
"\t/*\n\tif ((pps->ref_count[0] > 32) || (pps->ref_count[1] > 32)) goto exit;\n\t*/",
"\tpps->weighted_pred_flag = gf_bs_read_int_log(bs, 1, \"weighted_pred_flag\");\n\tgf_bs_read_int_log(bs, 2, \"weighted_bipred_idc\");\n\tgf_bs_read_se_log(bs, \"init_qp_minus26\");\n\tgf_bs_read_se_log(bs, \"init_qs_minus26\");\n\tgf_bs_read_se_log(bs, \"chroma_qp_index_offset\");\n\tpps->deblocking_filter_control_present_flag = gf_bs_read_int_log(bs, 1, \"deblocking_filter_control_present_flag\");\n\tgf_bs_read_int_log(bs, 1, \"constrained_intra_pred\");\n\tpps->redundant_pic_cnt_present = gf_bs_read_int_log(bs, 1, \"redundant_pic_cnt_present\");",
"\treturn pps_id;\n}",
"GF_EXPORT\ns32 gf_avc_read_pps_bs(GF_BitStream *bs, AVCState *avc)\n{\n\treturn gf_avc_read_pps_bs_internal(bs, avc, 0);\n}",
"GF_EXPORT\ns32 gf_avc_read_pps(const u8 *pps_data, u32 pps_size, AVCState *avc)\n{\n\tGF_BitStream *bs;\n\ts32 pps_id;",
"\t/*PPS still contains emulation bytes*/\n\tbs = gf_bs_new(pps_data, pps_size, GF_BITSTREAM_READ);\n\tif (!bs) {\n\t\treturn -1;\n\t}\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\tpps_id = gf_avc_read_pps_bs(bs, avc);\n\tgf_bs_del(bs);\n\treturn pps_id;\n}",
"#if 0 //unused",
"s32 gf_avc_read_sps_ext(const char *spse_data, u32 spse_size)\n{\n\tGF_BitStream *bs;\n\ts32 sps_id;",
"\tbs = gf_bs_new(spse_data, spse_size, GF_BITSTREAM_READ);\n\tsps_id = gf_avc_read_sps_ext_bs(bs);",
"\tgf_bs_del(bs);\n\treturn sps_id;\n}\n#endif",
"static s32 SVC_ReadNal_header_extension(GF_BitStream *bs, SVC_NALUHeader *NalHeader)\n{\n\tgf_bs_read_int_log(bs, 1, \"reserved_one_bit\");\n\tNalHeader->idr_pic_flag = gf_bs_read_int_log(bs, 1, \"idr_flag\");\n\tNalHeader->priority_id = gf_bs_read_int_log(bs, 6, \"priority_id\");\n\tgf_bs_read_int_log(bs, 1, \"no_inter_layer_pred_flag\");\n\tNalHeader->dependency_id = gf_bs_read_int_log(bs, 3, \"DependencyId\");\n\tNalHeader->quality_id = gf_bs_read_int_log(bs, 4, \"quality_id\");\n\tNalHeader->temporal_id = gf_bs_read_int_log(bs, 3, \"temporal_id\");\n\tgf_bs_read_int_log(bs, 1, \"use_ref_base_pic_flag\");\n\tgf_bs_read_int_log(bs, 1, \"discardable_flag\");\n\tgf_bs_read_int_log(bs, 1, \"output_flag\");\n\tgf_bs_read_int_log(bs, 2, \"reserved_three_2bits\");\n\treturn 1;\n}",
"static void ref_pic_list_modification(GF_BitStream *bs, u32 slice_type) {\n\tif (slice_type % 5 != 2 && slice_type % 5 != 4) {\n\t\tif (gf_bs_read_int_log(bs, 1, \"ref_pic_list_modification_flag_l0\")) {\n\t\t\tu32 idx=0, modification_of_pic_nums_idc;\n\t\t\tdo {\n\t\t\t\tmodification_of_pic_nums_idc = gf_bs_read_ue_log_idx(bs, \"modification_of_pic_nums_idc\", idx);\n\t\t\t\tif (modification_of_pic_nums_idc == 0 || modification_of_pic_nums_idc == 1) {\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"abs_diff_pic_num_minus1\", idx);\n\t\t\t\t}\n\t\t\t\telse if (modification_of_pic_nums_idc == 2) {\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"long_term_pic_num\", idx);\n\t\t\t\t}\n\t\t\t\tidx++;\n\t\t\t} while ((modification_of_pic_nums_idc != 3) && gf_bs_available(bs));\n\t\t}\n\t}\n\tif (slice_type % 5 == 1) {\n\t\tif (gf_bs_read_int_log(bs, 1, \"ref_pic_list_modification_flag_l1\")) {\n\t\t\tu32 idx=0, modification_of_pic_nums_idc;\n\t\t\tdo {\n\t\t\t\tmodification_of_pic_nums_idc = gf_bs_read_ue_log_idx(bs, \"modification_of_pic_nums_idc\", idx);\n\t\t\t\tif (modification_of_pic_nums_idc == 0 || modification_of_pic_nums_idc == 1) {\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"abs_diff_pic_num_minus1\", idx);\n\t\t\t\t}\n\t\t\t\telse if (modification_of_pic_nums_idc == 2) {\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"long_term_pic_num\", idx);\n\t\t\t\t}\n\t\t\t\tidx++;\n\t\t\t} while ((modification_of_pic_nums_idc != 3) && gf_bs_available(bs));\n\t\t}\n\t}\n}",
"static void pred_weight_table(GF_BitStream *bs, u32 slice_type, u32 ChromaArrayType, u32 num_ref_idx_l0_active_minus1, u32 num_ref_idx_l1_active_minus1) {\n\tu32 i, j;\n\tgf_bs_read_ue_log(bs, \"luma_log2_weight_denom\");\n\tif (ChromaArrayType != 0) {\n\t\tgf_bs_read_ue_log(bs, \"chroma_log2_weight_denom\");\n\t}\n\tfor (i = 0; i <= num_ref_idx_l0_active_minus1; i++) {\n\t\tif (gf_bs_read_int_log_idx(bs, 1, \"luma_weight_l0_flag\", i)) {\n\t\t\tgf_bs_read_se_log_idx(bs, \"luma_weight_l0\", i);\n\t\t\tgf_bs_read_se_log_idx(bs, \"luma_offset_l0\", i);\n\t\t}\n\t\tif (ChromaArrayType != 0) {\n\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"chroma_weight_l0_flag\", i))\n\t\t\t\tfor (j = 0; j < 2; j++) {\n\t\t\t\t\tgf_bs_read_se_log_idx2(bs, \"chroma_weight_l0\", i, j);\n\t\t\t\t\tgf_bs_read_se_log_idx2(bs, \"chroma_offset_l0\", i, j);\n\t\t\t\t}\n\t\t}\n\t}\n\tif (slice_type % 5 == 1) {\n\t\tfor (i = 0; i <= num_ref_idx_l1_active_minus1; i++) {\n\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"luma_weight_l1_flag\", i)) {\n\t\t\t\tgf_bs_read_se_log_idx(bs, \"luma_weight_l1\", i);\n\t\t\t\tgf_bs_read_se_log_idx(bs, \"luma_offset_l1\", i);\n\t\t\t}\n\t\t\tif (ChromaArrayType != 0) {\n\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"chroma_weight_l1_flag\", i)) {\n\t\t\t\t\tfor (j = 0; j < 2; j++) {\n\t\t\t\t\t\tgf_bs_read_se_log_idx2(bs, \"chroma_weight_l1\", i, j);\n\t\t\t\t\t\tgf_bs_read_se_log_idx2(bs, \"chroma_offset_l1\", i, j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"static void dec_ref_pic_marking(GF_BitStream *bs, Bool IdrPicFlag) {\n\tif (IdrPicFlag) {\n\t\tgf_bs_read_int_log(bs, 1, \"no_output_of_prior_pics_flag\");\n\t\tgf_bs_read_int_log(bs, 1, \"long_term_reference_flag\");\n\t}\n\telse {\n\t\tif (gf_bs_read_int_log(bs, 1, \"adaptive_ref_pic_marking_mode_flag\")) {\n\t\t\tu32 idx=0, memory_management_control_operation;\n\t\t\tdo {\n\t\t\t\tmemory_management_control_operation = gf_bs_read_ue_log_idx(bs, \"memory_management_control_operation\", idx);\n\t\t\t\tif (memory_management_control_operation == 1 || memory_management_control_operation == 3)\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"difference_of_pic_nums_minus1\", idx);\n\t\t\t\tif (memory_management_control_operation == 2)\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"long_term_pic_num\", idx);\n\t\t\t\tif (memory_management_control_operation == 3 || memory_management_control_operation == 6)\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"long_term_frame_idx\", idx);\n\t\t\t\tif (memory_management_control_operation == 4)\n\t\t\t\t\tgf_bs_read_ue_log_idx(bs, \"max_long_term_frame_idx_plus1\", idx);\n\t\t\t\tidx++;\n\t\t\t} while (memory_management_control_operation != 0);\n\t\t}\n\t}\n}",
"static s32 avc_parse_slice(GF_BitStream *bs, AVCState *avc, Bool svc_idr_flag, AVCSliceInfo *si)\n{\n\ts32 pps_id, num_ref_idx_l0_active_minus1 = 0, num_ref_idx_l1_active_minus1 = 0;",
"\t/*s->current_picture.reference= h->nal_ref_idc != 0;*/\n\tgf_bs_read_ue_log(bs, \"first_mb_in_slice\");\n\tsi->slice_type = gf_bs_read_ue_log(bs, \"slice_type\");\n\tif (si->slice_type > 9) return -1;",
"\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\tif ((pps_id<0) || (pps_id > 255)) return -1;\n\tsi->pps = &avc->pps[pps_id];\n\tif (!si->pps->slice_group_count) return -2;\n\tsi->sps = &avc->sps[si->pps->sps_id];\n\tif (!si->sps->log2_max_frame_num) return -2;\n\tavc->sps_active_idx = si->pps->sps_id;\n\tavc->pps_active_idx = pps_id;",
"\tsi->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, \"frame_num\");",
"\tsi->field_pic_flag = 0;\n\tsi->bottom_field_flag = 0;\n\tif (!si->sps->frame_mbs_only_flag) {\n\t\tsi->field_pic_flag = gf_bs_read_int_log(bs, 1, \"field_pic_flag\");\n\t\tif (si->field_pic_flag)\n\t\t\tsi->bottom_field_flag = gf_bs_read_int_log(bs, 1, \"bottom_field_flag\");\n\t}",
"\tif ((si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) || svc_idr_flag)\n\t\tsi->idr_pic_id = gf_bs_read_ue_log(bs, \"idr_pic_id\");",
"\tif (si->sps->poc_type == 0) {\n\t\tsi->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, \"poc_lsb\");\n\t\tif (si->pps->pic_order_present && !si->field_pic_flag) {\n\t\t\tsi->delta_poc_bottom = gf_bs_read_se_log(bs, \"poc_lsb\");\n\t\t}\n\t}\n\telse if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) {\n\t\tsi->delta_poc[0] = gf_bs_read_se_log(bs, \"delta_poc0\");\n\t\tif ((si->pps->pic_order_present == 1) && !si->field_pic_flag)\n\t\t\tsi->delta_poc[1] = gf_bs_read_se_log(bs, \"delta_poc1\");\n\t}",
"\tif (si->pps->redundant_pic_cnt_present) {\n\t\tsi->redundant_pic_cnt = gf_bs_read_ue_log(bs, \"redundant_pic_cnt\");\n\t}",
"\tif (si->slice_type % 5 == GF_AVC_TYPE_B) {\n\t\tgf_bs_read_int_log(bs, 1, \"direct_spatial_mv_pred_flag\");\n\t}",
"\tnum_ref_idx_l0_active_minus1 = si->pps->num_ref_idx_l0_default_active_minus1;\n\tnum_ref_idx_l1_active_minus1 = si->pps->num_ref_idx_l1_default_active_minus1;",
"\tif (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_B) {\n\t\tBool num_ref_idx_active_override_flag = gf_bs_read_int_log(bs, 1, \"num_ref_idx_active_override_flag\");\n\t\tif (num_ref_idx_active_override_flag) {\n\t\t\tnum_ref_idx_l0_active_minus1 = gf_bs_read_ue_log(bs, \"num_ref_idx_l0_active_minus1\");\n\t\t\tif (si->slice_type % 5 == GF_AVC_TYPE_B) {\n\t\t\t\tnum_ref_idx_l1_active_minus1 = gf_bs_read_ue_log(bs, \"num_ref_idx_l1_active_minus1\");\n\t\t\t}\n\t\t}\n\t}",
"\tif (si->nal_unit_type == 20 || si->nal_unit_type == 21) {\n\t\t//ref_pic_list_mvc_modification(); /* specified in Annex H */\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[avc-h264] unimplemented ref_pic_list_mvc_modification() in slide header\\n\"));\n\t\tassert(0);\n\t\treturn -1;\n\t}\n\telse {\n\t\tref_pic_list_modification(bs, si->slice_type);\n\t}",
"\tif ((si->pps->weighted_pred_flag && (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP))\n\t\t|| (si->pps->weighted_bipred_idc == 1 && si->slice_type % 5 == GF_AVC_TYPE_B)) {\n\t\tpred_weight_table(bs, si->slice_type, si->sps->ChromaArrayType, num_ref_idx_l0_active_minus1, num_ref_idx_l1_active_minus1);\n\t}",
"\tif (si->nal_ref_idc != 0) {\n\t\tdec_ref_pic_marking(bs, (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE));\n\t}",
"\tif (si->pps->entropy_coding_mode_flag && si->slice_type % 5 != GF_AVC_TYPE_I && si->slice_type % 5 != GF_AVC_TYPE_SI) {\n\t\tgf_bs_read_ue_log(bs, \"cabac_init_idc\");\n\t}",
"\t/*slice_qp_delta = */gf_bs_read_se(bs);\n\tif (si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_SI) {\n\t\tif (si->slice_type % 5 == GF_AVC_TYPE_SP) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"sp_for_switch_flag\");\n\t\t}\n\t\tgf_bs_read_se_log(bs, \"slice_qs_delta\");\n\t}",
"\tif (si->pps->deblocking_filter_control_present_flag) {\n\t\tif (gf_bs_read_ue_log(bs, \"disable_deblocking_filter_idc\") != 1) {\n\t\t\tgf_bs_read_se_log(bs, \"slice_alpha_c0_offset_div2\");\n\t\t\tgf_bs_read_se_log(bs, \"slice_beta_offset_div2\");\n\t\t}\n\t}",
"\tif (si->pps->slice_group_count > 1 && si->pps->mb_slice_group_map_type >= 3 && si->pps->mb_slice_group_map_type <= 5) {\n\t\tgf_bs_read_int_log(bs, (u32)ceil(log1p((si->pps->pic_size_in_map_units_minus1 + 1) / (si->pps->slice_group_change_rate_minus1 + 1) ) / log(2)), \"slice_group_change_cycle\");\n\t}\n\treturn 0;\n}",
"\nstatic s32 svc_parse_slice(GF_BitStream *bs, AVCState *avc, AVCSliceInfo *si)\n{\n\ts32 pps_id;",
"\t/*s->current_picture.reference= h->nal_ref_idc != 0;*/\n\tgf_bs_read_ue_log(bs, \"first_mb_in_slice\");\n\tsi->slice_type = gf_bs_read_ue_log(bs, \"slice_type\");\n\tif (si->slice_type > 9) return -1;",
"\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");",
"\tif ((pps_id<0) || (pps_id > 255))",
"\t\treturn -1;\n\tsi->pps = &avc->pps[pps_id];\n\tsi->pps->id = pps_id;\n\tif (!si->pps->slice_group_count)\n\t\treturn -2;\n\tsi->sps = &avc->sps[si->pps->sps_id + GF_SVC_SSPS_ID_SHIFT];\n\tif (!si->sps->log2_max_frame_num)\n\t\treturn -2;",
"\tsi->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, \"frame_num\");",
"\tsi->field_pic_flag = 0;\n\tif (si->sps->frame_mbs_only_flag) {\n\t\t/*s->picture_structure= PICT_FRAME;*/\n\t}\n\telse {\n\t\tsi->field_pic_flag = gf_bs_read_int_log(bs, 1, \"field_pic_flag\");\n\t\tif (si->field_pic_flag) si->bottom_field_flag = gf_bs_read_int_log(bs, 1, \"bottom_field_flag\");\n\t}\n\tif (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE || si->NalHeader.idr_pic_flag)\n\t\tsi->idr_pic_id = gf_bs_read_ue_log(bs, \"idr_pic_id\");",
"\tif (si->sps->poc_type == 0) {\n\t\tsi->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, \"poc_lsb\");\n\t\tif (si->pps->pic_order_present && !si->field_pic_flag) {\n\t\t\tsi->delta_poc_bottom = gf_bs_read_se_log(bs, \"delta_poc_bottom\");\n\t\t}\n\t}\n\telse if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) {\n\t\tsi->delta_poc[0] = gf_bs_read_se_log(bs, \"delta_poc0\");\n\t\tif ((si->pps->pic_order_present == 1) && !si->field_pic_flag)\n\t\t\tsi->delta_poc[1] = gf_bs_read_se_log(bs, \"delta_poc1\");\n\t}\n\tif (si->pps->redundant_pic_cnt_present) {\n\t\tsi->redundant_pic_cnt = gf_bs_read_ue_log(bs, \"redundant_pic_cnt\");\n\t}\n\treturn 0;\n}",
"\nstatic s32 avc_parse_recovery_point_sei(GF_BitStream *bs, AVCState *avc)\n{\n\tAVCSeiRecoveryPoint *rp = &avc->sei.recovery_point;",
"\trp->frame_cnt = gf_bs_read_ue_log(bs, \"frame_cnt\");\n\trp->exact_match_flag = gf_bs_read_int_log(bs, 1, \"exact_match_flag\");\n\trp->broken_link_flag = gf_bs_read_int_log(bs, 1, \"broken_link_flag\");\n\trp->changing_slice_group_idc = gf_bs_read_int_log(bs, 2, \"changing_slice_group_idc\");\n\trp->valid = 1;",
"\treturn 0;\n}",
"/*for interpretation see ISO 14496-10 N.11084, table D-1*/\nstatic s32 avc_parse_pic_timing_sei(GF_BitStream *bs, AVCState *avc)\n{\n\tint sps_id = avc->sps_active_idx;\n\tconst char NumClockTS[] = { 1, 1, 1, 2, 2, 3, 3, 2, 3 };\n\tAVCSeiPicTiming *pt = &avc->sei.pic_timing;",
"\tif (sps_id < 0) {\n\t\t/*sps_active_idx equals -1 when no sps has been detected. In this case SEI should not be decoded.*/\n\t\tassert(0);\n\t\treturn 1;\n\t}\n\tif (avc->sps[sps_id].vui.nal_hrd_parameters_present_flag || avc->sps[sps_id].vui.vcl_hrd_parameters_present_flag) { /*CpbDpbDelaysPresentFlag, see 14496-10(2003) E.11*/\n\t\tgf_bs_read_int_log(bs, 1 + avc->sps[sps_id].vui.hrd.cpb_removal_delay_length_minus1, \"cpb_removal_delay_minus1\");\n\t\tgf_bs_read_int_log(bs, 1 + avc->sps[sps_id].vui.hrd.dpb_output_delay_length_minus1, \"dpb_output_delay_minus1\");\n\t}",
"\t/*ISO 14496-10 (2003), D.8.2: we need to get pic_struct in order to know if we display top field first or bottom field first*/\n\tif (avc->sps[sps_id].vui.pic_struct_present_flag) {\n\t\tint i;\n\t\tpt->pic_struct = gf_bs_read_int_log(bs, 4, \"pic_struct\");\n\t\tif (pt->pic_struct > 8) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[avc-h264] invalid pic_struct value %d\\n\", pt->pic_struct));\n\t\t\treturn 1;\n\t\t}",
"\t\tfor (i = 0; i < NumClockTS[pt->pic_struct]; i++) {\n\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"clock_timestamp_flag\", i)) {\n\t\t\t\tBool full_timestamp_flag;\n\t\t\t\tgf_bs_read_int_log_idx(bs, 2, \"ct_type\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 1, \"nuit_field_based_flag\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 5, \"counting_type\", i);\n\t\t\t\tfull_timestamp_flag = gf_bs_read_int_log_idx(bs, 1, \"full_timestamp_flag\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 1, \"discontinuity_flag\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 1, \"cnt_dropped_flag\", i);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"n_frames\", i);\n\t\t\t\tif (full_timestamp_flag) {\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 6, \"seconds_value\", i);\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 6, \"minutes_value\", i);\n\t\t\t\t\tgf_bs_read_int_log_idx(bs, 5, \"hours_value\", i);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"seconds_flag\", i)) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 6, \"seconds_value\", i);\n\t\t\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"minutes_flag\", i)) {\n\t\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 6, \"minutes_value\", i);\n\t\t\t\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"hours_flag\", i)) {\n\t\t\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 5, \"hours_value\", i);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (avc->sps[sps_id].vui.hrd.time_offset_length > 0)\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, avc->sps[sps_id].vui.hrd.time_offset_length, \"time_offset\", i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\treturn 0;\n}",
"\n#if !defined(GPAC_DISABLE_HEVC)\nstatic void avc_parse_itu_t_t35_sei(GF_BitStream* bs, AVCSeiItuTT35DolbyVision *dovi)\n{\n\tu8 itu_t_t35_country_code = gf_bs_read_u8(bs);\n\tu16 terminal_provider_code = gf_bs_read_u16(bs);\n\tu32 user_id = gf_bs_read_u32(bs);\n\tu8 data_type_code = gf_bs_read_u8(bs);\n\tif (itu_t_t35_country_code == 0xB5 && terminal_provider_code == 0x31 && user_id == 0x47413934 && (data_type_code == 0x8 || data_type_code == 0x9)) {\n\t\tdovi->rpu_flag = GF_TRUE;\n\t}\n}\n#endif",
"static void avc_compute_poc(AVCSliceInfo *si)\n{\n\tenum {\n\t\tAVC_PIC_FRAME,\n\t\tAVC_PIC_FIELD_TOP,\n\t\tAVC_PIC_FIELD_BOTTOM,\n\t} pic_type;\n\ts32 field_poc[2] = { 0,0 };\n\ts32 max_frame_num;",
"\tif (!si->sps) return;",
"\tmax_frame_num = 1 << (si->sps->log2_max_frame_num);",
"\t/* picture type */\n\tif (si->sps->frame_mbs_only_flag || !si->field_pic_flag) pic_type = AVC_PIC_FRAME;\n\telse if (si->bottom_field_flag) pic_type = AVC_PIC_FIELD_BOTTOM;\n\telse pic_type = AVC_PIC_FIELD_TOP;",
"\t/* frame_num_offset */\n\tif (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) {\n\t\tsi->poc_lsb_prev = 0;\n\t\tsi->poc_msb_prev = 0;\n\t\tsi->frame_num_offset = 0;\n\t}\n\telse {\n\t\tif (si->frame_num < si->frame_num_prev)\n\t\t\tsi->frame_num_offset = si->frame_num_offset_prev + max_frame_num;\n\t\telse\n\t\t\tsi->frame_num_offset = si->frame_num_offset_prev;\n\t}",
"\t/*ISO 14496-10 N.11084 8.2.1.1*/\n\tif (si->sps->poc_type == 0)\n\t{\n\t\tconst u32 max_poc_lsb = 1 << (si->sps->log2_max_poc_lsb);",
"\t\t/*ISO 14496-10 N.11084 eq (8-3)*/\n\t\tif ((si->poc_lsb < si->poc_lsb_prev) &&\n\t\t\t(si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2))\n\t\t\tsi->poc_msb = si->poc_msb_prev + max_poc_lsb;\n\t\telse if ((si->poc_lsb > si->poc_lsb_prev) &&\n\t\t\t(si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))\n\t\t\tsi->poc_msb = si->poc_msb_prev - max_poc_lsb;\n\t\telse\n\t\t\tsi->poc_msb = si->poc_msb_prev;",
"\t\t/*ISO 14496-10 N.11084 eq (8-4)*/\n\t\tif (pic_type != AVC_PIC_FIELD_BOTTOM)\n\t\t\tfield_poc[0] = si->poc_msb + si->poc_lsb;",
"\t\t/*ISO 14496-10 N.11084 eq (8-5)*/\n\t\tif (pic_type != AVC_PIC_FIELD_TOP) {\n\t\t\tif (!si->field_pic_flag)\n\t\t\t\tfield_poc[1] = field_poc[0] + si->delta_poc_bottom;\n\t\t\telse\n\t\t\t\tfield_poc[1] = si->poc_msb + si->poc_lsb;\n\t\t}\n\t}\n\t/*ISO 14496-10 N.11084 8.2.1.2*/\n\telse if (si->sps->poc_type == 1)\n\t{\n\t\tu32 i;\n\t\ts32 abs_frame_num, expected_delta_per_poc_cycle, expected_poc;",
"\t\tif (si->sps->poc_cycle_length)\n\t\t\tabs_frame_num = si->frame_num_offset + si->frame_num;\n\t\telse\n\t\t\tabs_frame_num = 0;",
"\t\tif (!si->nal_ref_idc && (abs_frame_num > 0)) abs_frame_num--;",
"\t\texpected_delta_per_poc_cycle = 0;\n\t\tfor (i = 0; i < si->sps->poc_cycle_length; i++)\n\t\t\texpected_delta_per_poc_cycle += si->sps->offset_for_ref_frame[i];",
"\t\tif (abs_frame_num > 0) {\n\t\t\tconst u32 poc_cycle_cnt = (abs_frame_num - 1) / si->sps->poc_cycle_length;\n\t\t\tconst u32 frame_num_in_poc_cycle = (abs_frame_num - 1) % si->sps->poc_cycle_length;",
"\t\t\texpected_poc = poc_cycle_cnt * expected_delta_per_poc_cycle;\n\t\t\tfor (i = 0; i <= frame_num_in_poc_cycle; i++)\n\t\t\t\texpected_poc += si->sps->offset_for_ref_frame[i];\n\t\t}\n\t\telse {\n\t\t\texpected_poc = 0;\n\t\t}",
"\t\tif (!si->nal_ref_idc) expected_poc += si->sps->offset_for_non_ref_pic;",
"\t\tfield_poc[0] = expected_poc + si->delta_poc[0];\n\t\tfield_poc[1] = field_poc[0] + si->sps->offset_for_top_to_bottom_field;\n\t\tif (pic_type == AVC_PIC_FRAME) field_poc[1] += si->delta_poc[1];\n\t}\n\t/*ISO 14496-10 N.11084 8.2.1.3*/\n\telse if (si->sps->poc_type == 2)\n\t{\n\t\tint poc;\n\t\tif (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) {\n\t\t\tpoc = 0;\n\t\t}\n\t\telse {\n\t\t\tconst int abs_frame_num = si->frame_num_offset + si->frame_num;\n\t\t\tpoc = 2 * abs_frame_num;\n\t\t\tif (!si->nal_ref_idc) poc -= 1;\n\t\t}\n\t\tfield_poc[0] = poc;\n\t\tfield_poc[1] = poc;\n\t}",
"\t/*ISO 14496-10 N.11084 eq (8-1)*/\n\tif (pic_type == AVC_PIC_FRAME)\n\t\tsi->poc = MIN(field_poc[0], field_poc[1]);\n\telse if (pic_type == AVC_PIC_FIELD_TOP)\n\t\tsi->poc = field_poc[0];\n\telse\n\t\tsi->poc = field_poc[1];\n}",
"GF_EXPORT\ns32 gf_avc_parse_nalu(GF_BitStream *bs, AVCState *avc)\n{\n\tu8 idr_flag;\n\ts32 slice, ret;\n\tu32 nal_hdr;\n\tAVCSliceInfo n_state;",
"\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tnal_hdr = gf_bs_read_u8(bs);",
"\tslice = 0;\n\tmemcpy(&n_state, &avc->s_info, sizeof(AVCSliceInfo));\n\tavc->last_nal_type_parsed = n_state.nal_unit_type = nal_hdr & 0x1F;\n\tn_state.nal_ref_idc = (nal_hdr >> 5) & 0x3;",
"\tidr_flag = 0;",
"\tswitch (n_state.nal_unit_type) {\n\tcase GF_AVC_NALU_ACCESS_UNIT:\n\tcase GF_AVC_NALU_END_OF_SEQ:\n\tcase GF_AVC_NALU_END_OF_STREAM:\n\t\tret = 1;\n\t\tbreak;",
"\tcase GF_AVC_NALU_SVC_SLICE:\n\t\tSVC_ReadNal_header_extension(bs, &n_state.NalHeader);\n\t\t// slice buffer - read the info and compare.\n\t\t/*ret = */svc_parse_slice(bs, avc, &n_state);\n\t\tif (avc->s_info.nal_ref_idc) {\n\t\t\tn_state.poc_lsb_prev = avc->s_info.poc_lsb;\n\t\t\tn_state.poc_msb_prev = avc->s_info.poc_msb;\n\t\t}\n\t\tavc_compute_poc(&n_state);",
"\t\tif (avc->s_info.poc != n_state.poc) {\n\t\t\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\t\t\treturn 1;\n\t\t}\n\t\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\t\treturn 0;",
"\tcase GF_AVC_NALU_SVC_PREFIX_NALU:\n\t\tSVC_ReadNal_header_extension(bs, &n_state.NalHeader);\n\t\treturn 0;",
"\tcase GF_AVC_NALU_IDR_SLICE:\n\tcase GF_AVC_NALU_NON_IDR_SLICE:\n\tcase GF_AVC_NALU_DP_A_SLICE:\n\tcase GF_AVC_NALU_DP_B_SLICE:\n\tcase GF_AVC_NALU_DP_C_SLICE:\n\t\tslice = 1;\n\t\t/* slice buffer - read the info and compare.*/\n\t\tret = avc_parse_slice(bs, avc, idr_flag, &n_state);\n\t\tif (ret < 0) return ret;\n\t\tret = 0;\n\t\tif (\n\t\t\t((avc->s_info.nal_unit_type > GF_AVC_NALU_IDR_SLICE) || (avc->s_info.nal_unit_type < GF_AVC_NALU_NON_IDR_SLICE))\n\t\t\t&& (avc->s_info.nal_unit_type != GF_AVC_NALU_SVC_SLICE)\n\t\t\t) {\n\t\t\tbreak;\n\t\t}\n\t\tif (avc->s_info.frame_num != n_state.frame_num) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}",
"\t\tif (avc->s_info.field_pic_flag != n_state.field_pic_flag) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif ((avc->s_info.nal_ref_idc != n_state.nal_ref_idc) &&\n\t\t\t(!avc->s_info.nal_ref_idc || !n_state.nal_ref_idc)) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tassert(avc->s_info.sps);",
"\t\tif (avc->s_info.sps->poc_type == n_state.sps->poc_type) {\n\t\t\tif (!avc->s_info.sps->poc_type) {\n\t\t\t\tif (!n_state.bottom_field_flag && (avc->s_info.poc_lsb != n_state.poc_lsb)) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (avc->s_info.delta_poc_bottom != n_state.delta_poc_bottom) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (avc->s_info.sps->poc_type == 1) {\n\t\t\t\tif (avc->s_info.delta_poc[0] != n_state.delta_poc[0]) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (avc->s_info.delta_poc[1] != n_state.delta_poc[1]) {\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\tif (n_state.nal_unit_type == GF_AVC_NALU_IDR_SLICE) {\n\t\t\tif (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE) { /*IdrPicFlag differs in value*/\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (avc->s_info.idr_pic_id != n_state.idr_pic_id) { /*both IDR and idr_pic_id differs*/\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 0, NULL, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;",
"\tcase GF_AVC_NALU_PIC_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_pps_bs_internal(bs, avc, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\tcase GF_AVC_NALU_SVC_SUBSEQ_PARAM:\n\t\tavc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 1, NULL, nal_hdr);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;\n\tcase GF_AVC_NALU_SEQ_PARAM_EXT:\n\t\tavc->last_ps_idx = (s32) gf_bs_read_ue(bs);\n\t\tif (avc->last_ps_idx < 0) return -1;\n\t\treturn 0;",
"\tcase GF_AVC_NALU_SEI:\n\tcase GF_AVC_NALU_FILLER_DATA:\n\t\treturn 0;",
"\tdefault:\n\t\tif (avc->s_info.nal_unit_type <= GF_AVC_NALU_IDR_SLICE) ret = 1;\n\t\t//To detect change of AU when multiple sps and pps in stream\n\t\telse if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEI && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)\n\t\t\tret = 1;\n\t\telse if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEQ_PARAM && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)\n\t\t\tret = 1;\n\t\telse\n\t\t\tret = 0;\n\t\tbreak;\n\t}",
"\t/* save _prev values */\n\tif (ret && avc->s_info.sps) {\n\t\tn_state.frame_num_offset_prev = avc->s_info.frame_num_offset;\n\t\tif ((avc->s_info.sps->poc_type != 2) || (avc->s_info.nal_ref_idc != 0))\n\t\t\tn_state.frame_num_prev = avc->s_info.frame_num;\n\t\tif (avc->s_info.nal_ref_idc) {\n\t\t\tn_state.poc_lsb_prev = avc->s_info.poc_lsb;\n\t\t\tn_state.poc_msb_prev = avc->s_info.poc_msb;\n\t\t}\n\t}\n\tif (slice)\n\t\tavc_compute_poc(&n_state);\n\tmemcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));\n\treturn ret;\n}",
"\nu32 gf_media_avc_reformat_sei(u8 *buffer, u32 nal_size, Bool isobmf_rewrite, AVCState *avc)\n{\n\tu32 ptype, psize, hdr, var;\n\tu32 start;\n\tGF_BitStream *bs;\n\tGF_BitStream *bs_dest = NULL;\n\tu8 nhdr;\n\tBool sei_removed = GF_FALSE;\n\tchar store;",
"\thdr = buffer[0];\n\tif ((hdr & 0x1F) != GF_AVC_NALU_SEI) return 0;",
"\tif (isobmf_rewrite) bs_dest = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);",
"\tbs = gf_bs_new(buffer, nal_size, GF_BITSTREAM_READ);\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tnhdr = gf_bs_read_int(bs, 8);\n\tif (bs_dest) gf_bs_write_int(bs_dest, nhdr, 8);",
"\t/*parse SEI*/\n\twhile (gf_bs_available(bs)) {\n\t\tBool do_copy;\n\t\tptype = 0;\n\t\twhile (1) {\n\t\t\tu8 v = gf_bs_read_int(bs, 8);\n\t\t\tptype += v;\n\t\t\tif (v != 0xFF) break;\n\t\t}",
"\t\tpsize = 0;\n\t\twhile (1) {\n\t\t\tu8 v = gf_bs_read_int(bs, 8);\n\t\t\tpsize += v;\n\t\t\tif (v != 0xFF) break;\n\t\t}",
"\t\tstart = (u32)gf_bs_get_position(bs);",
"\t\tdo_copy = 1;",
"\t\tif (start + psize >= nal_size) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] SEI user message type %d size error (%d but %d remain), keeping full SEI untouched\\n\", ptype, psize, nal_size - start));\n\t\t\tif (bs_dest) gf_bs_del(bs_dest);\n\t\t\treturn nal_size;\n\t\t}\n\t\tswitch (ptype) {\n\t\t\t/*remove SEI messages forbidden in MP4*/\n\t\tcase 3: /*filler data*/\n\t\tcase 10: /*sub_seq info*/\n\t\tcase 11: /*sub_seq_layer char*/\n\t\tcase 12: /*sub_seq char*/\n\t\t\tdo_copy = 0;\n\t\t\tsei_removed = GF_TRUE;\n\t\t\tbreak;\n\t\tcase 5: /*user unregistered */\n\t\t\tstore = buffer[start + psize];\n\t\t\tbuffer[start + psize] = 0;\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CODING, (\"[avc-h264] SEI user message %s\\n\", buffer + start + 16));\n\t\t\tbuffer[start + psize] = store;\n\t\t\tbreak;",
"\t\tcase 6: /*recovery point*/\n\t\t\tavc_parse_recovery_point_sei(bs, avc);\n\t\t\tbreak;",
"\t\tcase 1: /*pic_timing*/\n\t\t\tavc_parse_pic_timing_sei(bs, avc);\n\t\t\tbreak;",
"\t\tcase 0: /*buffering period*/\n\t\tcase 2: /*pan scan rect*/\n\t\tcase 4: /*user registered ITU t35*/\n\t\tcase 7: /*def_rec_pic_marking_repetition*/\n\t\tcase 8: /*spare_pic*/\n\t\tcase 9: /*scene info*/\n\t\tcase 13: /*full frame freeze*/\n\t\tcase 14: /*full frame freeze release*/\n\t\tcase 15: /*full frame snapshot*/\n\t\tcase 16: /*progressive refinement segment start*/\n\t\tcase 17: /*progressive refinement segment end*/\n\t\tcase 18: /*motion constrained slice group*/\n\t\tdefault: /*add all unknown SEIs*/\n\t\t\tbreak;\n\t\t}",
"\t\tif (do_copy && bs_dest) {\n\t\t\tvar = ptype;\n\t\t\twhile (var >= 255) {\n\t\t\t\tgf_bs_write_int(bs_dest, 0xFF, 8);\n\t\t\t\tvar -= 255;\n\t\t\t}\n\t\t\tgf_bs_write_int(bs_dest, var, 8);",
"\t\t\tvar = psize;\n\t\t\twhile (var >= 255) {\n\t\t\t\tgf_bs_write_int(bs_dest, 0xFF, 8);\n\t\t\t\tvar -= 255;\n\t\t\t}\n\t\t\tgf_bs_write_int(bs_dest, var, 8);\n\t\t\tgf_bs_seek(bs, start);",
"\t\t\t//bs_read_data does not skip EPB, read byte per byte\n\t\t\tvar = psize;\n\t\t\twhile (var) {\n\t\t\t\tgf_bs_write_u8(bs_dest, gf_bs_read_u8(bs));\n\t\t\t\tvar--;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tgf_bs_seek(bs, start);",
"\t\t\t//bs_skip_bytes does not skip EPB, skip byte per byte\n\t\t\twhile (psize) {\n\t\t\t\tgf_bs_read_u8(bs);\n\t\t\t\tpsize--;\n\t\t\t}\n\t\t}",
"\t\tif (gf_bs_available(bs) <= 2) {\n\t\t\tvar = gf_bs_read_int(bs, 8);\n\t\t\tif (var != 0x80) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[avc-h264] SEI user message has less than 2 bytes remaining but no end of sei found\\n\"));\n\t\t\t}\n\t\t\tif (bs_dest) gf_bs_write_int(bs_dest, 0x80, 8);\n\t\t\tbreak;\n\t\t}\n\t}\n\tgf_bs_del(bs);\n\t//we cannot compare final size and original size since original may have EPB and final does not yet have them\n\tif (bs_dest && sei_removed) {\n\t\tu8 *dst_no_epb = NULL;\n\t\tu32 dst_no_epb_size = 0;\n\t\tgf_bs_get_content(bs_dest, &dst_no_epb, &dst_no_epb_size);\n\t\tnal_size = gf_media_nalu_add_emulation_bytes(buffer, dst_no_epb, dst_no_epb_size);\n\t}\n\tif (bs_dest) gf_bs_del(bs_dest);\n\treturn nal_size;\n}",
"\nstatic u8 avc_hevc_get_sar_idx(u32 w, u32 h)\n{\n\tu32 i, count = GF_ARRAY_LENGTH(avc_hevc_sar);\n\tfor (i = 0; i < count; i++) {\n\t\tif ((avc_hevc_sar[i].w == w) && (avc_hevc_sar[i].h == h))\n\t\t\treturn i;\n\t}\n\treturn 0xFF;\n}",
"static void avc_hevc_rewrite_vui(GF_VUIInfo *vui_info, GF_BitStream *orig, GF_BitStream *mod)\n{\n\t/* VUI present flag*/\n\tBool vui_present_flag = gf_bs_read_int(orig, 1);",
"\t/*setup default values*/\n\tBool aspect_ratio_info_present_flag = 0;\n\ts32 aspect_ratio_idc = -1;\n\tu32 ar_n=0, ar_d=0;\n\tBool overscan_info_present_flag = 0;\n\tu32 overscan_info=0;\n\tu32 video_signal_type_present_flag=0;\n\tu32 video_format = 5;\n\tu32 video_full_range_flag = 0;\n\tu32 colour_description_present_flag = 0;\n\tu32 colour_primaries = 2;\n\tu32 transfer_characteristics = 2;\n\tu32 matrix_coefficients = 2;",
"\t//if VUI is present, read all SAR and overscan values\n\tif (vui_present_flag) { /* VUI found in input bitstream */\n\t\taspect_ratio_info_present_flag = gf_bs_read_int(orig, 1);\n\t\tif (aspect_ratio_info_present_flag) {\n\t\t\taspect_ratio_idc = gf_bs_read_int(orig, 8); /*aspect_ratio_idc*/\n\t\t\tif (aspect_ratio_idc == 255) {\n\t\t\t\tar_n = gf_bs_read_int(orig, 16); /*sar_width*/\n\t\t\t\tar_d = gf_bs_read_int(orig, 16); /*sar_height*/\n\t\t\t}\n\t\t}",
"\t\t/*overscan_info_present_flag */\n\t\toverscan_info_present_flag = gf_bs_read_int(orig, 1);\n\t\tif(overscan_info_present_flag) {\n\t\t\toverscan_info = gf_bs_read_int(orig, 1);\n\t\t}",
"\t\t/* read all video signal related flags first */\n\t\tvideo_signal_type_present_flag = gf_bs_read_int(orig, 1);\n\t\tif(video_signal_type_present_flag) {\n\t\t\tvideo_format = gf_bs_read_int(orig, 3);\n\t\t\tvideo_full_range_flag = gf_bs_read_int(orig, 1);\n\t\t\tcolour_description_present_flag = gf_bs_read_int(orig, 1);\n\t\t\tif(colour_description_present_flag) {\n\t\t\t\tcolour_primaries = gf_bs_read_int(orig, 8);\n\t\t\t\ttransfer_characteristics = gf_bs_read_int(orig, 8);\n\t\t\t\tmatrix_coefficients = gf_bs_read_int(orig, 8);\n\t\t\t}\n\t\t}\n\t}",
"\t//recompute values\n\t//no change\n\tif ((vui_info->ar_num<0) || (vui_info->ar_den<0)) {\n\t}\n\t//remove par\n\telse if ((vui_info->ar_num==0) || (vui_info->ar_den==0)) {\n\t\taspect_ratio_info_present_flag = 0;\n\t}\n\t//set par\n\telse {\n\t\taspect_ratio_info_present_flag = 1;\n\t\tar_n = vui_info->ar_num;\n\t\tar_d = vui_info->ar_den;\n\t\taspect_ratio_idc = avc_hevc_get_sar_idx((u32) ar_n, (u32) ar_d);\n\t}",
"\tif (vui_info->remove_video_info) {\n\t\tvideo_signal_type_present_flag = 0;\n\t}\n\t/* correct the values of each flags */\n\telse if ((vui_info->fullrange==0) && (vui_info->video_format==5) && (vui_info->color_prim==2) && (vui_info->color_tfc==2) && (vui_info->color_matrix==2)) {\n\t\tvideo_signal_type_present_flag = 0; /* all default, nothing to write*/\n\t} else {\n\t\tvideo_signal_type_present_flag = 1;\n\t\tvideo_format = (vui_info->video_format < 0) ? video_format : vui_info->video_format;\n\t\tvideo_full_range_flag = (vui_info->fullrange < 0) ? video_full_range_flag : vui_info->fullrange;\n\t\tif ((vui_info->color_prim==2) && (vui_info->color_tfc==2) && (vui_info->color_matrix==2)) {\n\t\t\tcolour_description_present_flag = 0;\n\t\t} else {\n\t\t\tcolour_description_present_flag = 1;\n\t\t\tcolour_primaries = (vui_info->color_prim < 0) ? colour_primaries : vui_info->color_prim;\n\t\t\ttransfer_characteristics = (vui_info->color_tfc < 0) ? transfer_characteristics : vui_info->color_tfc;\n\t\t\tmatrix_coefficients = (vui_info->color_matrix < 0) ? matrix_coefficients : vui_info->color_matrix;\n\t\t}\n\t\tif ((colour_primaries==2) && (transfer_characteristics==2) && (matrix_coefficients==2)) {\n\t\t\tcolour_description_present_flag = 0;\n\t\t\tif ((video_format==5) && (video_full_range_flag==0))\n\t\t\t\tvideo_signal_type_present_flag = 0;\n\t\t}\n\t}",
"\t//always rewrite VUI\n\tgf_bs_write_int(mod, 1, 1);\n\tgf_bs_write_int(mod, aspect_ratio_info_present_flag, 1);\n\tif (aspect_ratio_info_present_flag) {\n\t\tgf_bs_write_int(mod, aspect_ratio_idc, 8);\n\t\tif (aspect_ratio_idc == 255) {\n\t\t\tgf_bs_write_int(mod, ar_n, 16);\n\t\t\tgf_bs_write_int(mod, ar_d, 16);\n\t\t}\n\t\tif (vui_info->update) {\n\t\t\tvui_info->ar_num = ar_n;\n\t\t\tvui_info->ar_den = ar_d;\n\t\t}\n\t}\n\tgf_bs_write_int(mod, overscan_info_present_flag, 1);\n\tif (overscan_info_present_flag) {\n\t\tgf_bs_write_int(mod, overscan_info, 1);\n\t}",
"\tgf_bs_write_int(mod, video_signal_type_present_flag, 1);\n\tif (video_signal_type_present_flag) {\n\t\tgf_bs_write_int(mod, video_format, 3);\n\t\tgf_bs_write_int(mod, video_full_range_flag, 1);\n\t\tgf_bs_write_int(mod, colour_description_present_flag, 1);",
"\t\tif (colour_description_present_flag) {\n\t\t\tgf_bs_write_int(mod, colour_primaries, 8);\n\t\t\tgf_bs_write_int(mod, transfer_characteristics, 8);\n\t\t\tgf_bs_write_int(mod, matrix_coefficients, 8);\n\t\t}",
"\t\tif (vui_info->update) {\n\t\t\tvui_info->video_format = video_format;\n\t\t\tvui_info->fullrange = video_full_range_flag;\n\t\t\tif (colour_description_present_flag) {\n\t\t\t\tvui_info->color_prim = colour_primaries;\n\t\t\t\tvui_info->color_tfc = transfer_characteristics;\n\t\t\t\tvui_info->color_matrix = matrix_coefficients;\n\t\t\t}\n\t\t}\n\t}",
"\t/*no VUI in input bitstream but we just inserted one, set all remaining vui flags to 0*/\n\tif (!vui_present_flag) {\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*chroma_location_info_present_flag */\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*timing_info_present_flag*/\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*nal_hrd_parameters_present*/\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*vcl_hrd_parameters_present*/\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*pic_struct_present*/\n\t\tgf_bs_write_int(mod, 0, 1);\t\t/*bitstream_restriction*/\n\t}\n\t/*otherwise we copy over th bits from the input bitrate*/\n}",
"GF_Err gf_avc_change_vui(GF_AVCConfig *avcc, GF_VUIInfo *vui_info)\n{\n\tGF_BitStream *orig, *mod;\n\tAVCState avc;\n\tu32 i, bit_offset, flag;\n\ts32 idx;\n\tGF_AVCConfigSlot *slc;\n\torig = NULL;",
"\tmemset(&avc, 0, sizeof(AVCState));\n\tavc.sps_active_idx = -1;",
"\ti=0;\n\twhile ((slc = (GF_AVCConfigSlot *)gf_list_enum(avcc->sequenceParameterSets, &i))) {\n\t\tu8 *no_emulation_buf = NULL;\n\t\tu32 no_emulation_buf_size = 0, emulation_bytes = 0;\n\t\tidx = gf_avc_read_sps(slc->data, slc->size, &avc, 0, &bit_offset);\n\t\tif (idx<0) {\n\t\t\tif ( orig )\n\t\t\t\tgf_bs_del(orig);\n\t\t\tcontinue;\n\t\t}",
"\t\t/*SPS still contains emulation bytes*/\n\t\tno_emulation_buf = gf_malloc((slc->size - 1) * sizeof(char));\n\t\tno_emulation_buf_size = gf_media_nalu_remove_emulation_bytes(slc->data + 1, no_emulation_buf, slc->size - 1);",
"\t\torig = gf_bs_new(no_emulation_buf, no_emulation_buf_size, GF_BITSTREAM_READ);\n\t\tgf_bs_read_data(orig, no_emulation_buf, no_emulation_buf_size);\n\t\tgf_bs_seek(orig, 0);\n\t\tmod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);",
"\t\t/*copy over till vui flag*/\n\t\tassert(bit_offset >= 8);\n\t\twhile (bit_offset - 8/*bit_offset doesn't take care of the first byte (NALU type)*/) {\n\t\t\tflag = gf_bs_read_int(orig, 1);\n\t\t\tgf_bs_write_int(mod, flag, 1);\n\t\t\tbit_offset--;\n\t\t}",
"\t\tavc_hevc_rewrite_vui(vui_info, orig, mod);",
"\t\t/*finally copy over remaining*/\n\t\twhile (gf_bs_bits_available(orig)) {\n\t\t\tflag = gf_bs_read_int(orig, 1);\n\t\t\tgf_bs_write_int(mod, flag, 1);\n\t\t}\n\t\tgf_bs_del(orig);\n\t\torig = NULL;\n\t\tgf_free(no_emulation_buf);",
"\t\t/*set anti-emulation*/\n\t\tgf_bs_get_content(mod, &no_emulation_buf, &flag);\n\t\temulation_bytes = gf_media_nalu_emulation_bytes_add_count(no_emulation_buf, flag);\n\t\tif (flag+emulation_bytes+1>slc->size)\n\t\t\tslc->data = (char*)gf_realloc(slc->data, flag+emulation_bytes+1);\n\t\tslc->size = gf_media_nalu_add_emulation_bytes(no_emulation_buf, slc->data + 1, flag) + 1;",
"\t\tgf_bs_del(mod);\n\t\tgf_free(no_emulation_buf);\n\t}\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_media_avc_change_par(GF_AVCConfig *avcc, s32 ar_n, s32 ar_d)\n{\n\tGF_VUIInfo vuii;\n\tmemset(&vuii, 0, sizeof(GF_VUIInfo));\n\tvuii.ar_num = ar_n;\n\tvuii.ar_den = ar_d;\n\tvuii.fullrange = -1;\n\tvuii.video_format = -1;\n\tvuii.color_prim = -1;\n\tvuii.color_tfc = -1;\n\tvuii.color_matrix = -1;\n\treturn gf_avc_change_vui(avcc, &vuii);\n}",
"GF_EXPORT\nGF_Err gf_media_avc_change_color(GF_AVCConfig *avcc, s32 fullrange, s32 vidformat, s32 colorprim, s32 transfer, s32 colmatrix)\n{\n\tGF_VUIInfo vuii;\n\tmemset(&vuii, 0, sizeof(GF_VUIInfo));\n\tvuii.ar_num = -1;\n\tvuii.ar_den = -1;\n\tvuii.fullrange = fullrange;\n\tvuii.video_format = vidformat;\n\tvuii.color_prim = colorprim;\n\tvuii.color_tfc = transfer;\n\tvuii.color_matrix = colmatrix;\n\treturn gf_avc_change_vui(avcc, &vuii);\n}",
"\nGF_EXPORT\nGF_Err gf_avc_get_sps_info(u8 *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)\n{\n\tAVCState avc;\n\ts32 idx;\n\tmemset(&avc, 0, sizeof(AVCState));\n\tavc.sps_active_idx = -1;",
"\tidx = gf_avc_read_sps(sps_data, sps_size, &avc, 0, NULL);\n\tif (idx < 0) {\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\tif (sps_id) *sps_id = idx;",
"\tif (width) *width = avc.sps[idx].width;\n\tif (height) *height = avc.sps[idx].height;\n\tif (par_n) *par_n = avc.sps[idx].vui.par_num ? avc.sps[idx].vui.par_num : (u32)-1;\n\tif (par_d) *par_d = avc.sps[idx].vui.par_den ? avc.sps[idx].vui.par_den : (u32)-1;",
"\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_avc_get_pps_info(u8 *pps_data, u32 pps_size, u32 *pps_id, u32 *sps_id)\n{\n\tGF_BitStream *bs;\n\tGF_Err e = GF_OK;",
"\tbs = gf_bs_new(pps_data, pps_size, GF_BITSTREAM_READ);\n\tif (!bs) {\n\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\tgoto exit;\n\t}\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\t/*nal hdr*/ gf_bs_read_int(bs, 8);",
"\t*pps_id = gf_bs_read_ue(bs);\n\t*sps_id = gf_bs_read_ue(bs);",
"exit:\n\tgf_bs_del(bs);\n\treturn e;\n}",
"#ifndef GPAC_DISABLE_HEVC",
"/**********\nHEVC parsing\n**********/",
"Bool gf_hevc_slice_is_intra(HEVCState *hevc)\n{\n\tswitch (hevc->s_info.nal_unit_type) {\n\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\tcase GF_HEVC_NALU_SLICE_CRA:\n\t\treturn GF_TRUE;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n}",
"Bool gf_hevc_slice_is_IDR(HEVCState *hevc)\n{\n\tif (hevc->sei.recovery_point.valid)\n\t{\n\t\thevc->sei.recovery_point.valid = 0;\n\t\treturn GF_TRUE;\n\t}\n\tswitch (hevc->s_info.nal_unit_type) {\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\t\treturn GF_TRUE;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n}",
"static Bool hevc_parse_short_term_ref_pic_set(GF_BitStream *bs, HEVC_SPS *sps, u32 idx_rps)\n{\n\tu32 i;\n\tBool inter_ref_pic_set_prediction_flag = 0;\n\tif (idx_rps != 0)\n\t\tinter_ref_pic_set_prediction_flag = gf_bs_read_int_log_idx(bs, 1, \"inter_ref_pic_set_prediction_flag\", idx_rps);",
"\tif (inter_ref_pic_set_prediction_flag) {\n\t\tHEVC_ReferencePictureSets *ref_ps, *rps;\n\t\tu32 delta_idx_minus1 = 0;\n\t\tu32 ref_idx;\n\t\tu32 delta_rps_sign;\n\t\tu32 abs_delta_rps_minus1, nb_ref_pics;\n\t\ts32 deltaRPS;\n\t\tu32 k = 0, k0 = 0, k1 = 0;\n\t\tif (idx_rps == sps->num_short_term_ref_pic_sets)\n\t\t\tdelta_idx_minus1 = gf_bs_read_ue_log_idx(bs, \"delta_idx_minus1\", idx_rps);",
"\t\tassert(delta_idx_minus1 <= idx_rps - 1);\n\t\tref_idx = idx_rps - 1 - delta_idx_minus1;\n\t\tdelta_rps_sign = gf_bs_read_int_log_idx(bs, 1, \"delta_rps_sign\", idx_rps);\n\t\tabs_delta_rps_minus1 = gf_bs_read_ue_log_idx(bs, \"abs_delta_rps_minus1\", idx_rps);\n\t\tdeltaRPS = (1 - (delta_rps_sign << 1)) * (abs_delta_rps_minus1 + 1);",
"\t\trps = &sps->rps[idx_rps];\n\t\tref_ps = &sps->rps[ref_idx];\n\t\tnb_ref_pics = ref_ps->num_negative_pics + ref_ps->num_positive_pics;\n\t\tfor (i = 0; i <= nb_ref_pics; i++) {\n\t\t\ts32 ref_idc;\n\t\t\ts32 used_by_curr_pic_flag = gf_bs_read_int_log_idx2(bs, 1, \"used_by_curr_pic_flag\", idx_rps, i);\n\t\t\tref_idc = used_by_curr_pic_flag ? 1 : 0;\n\t\t\tif (!used_by_curr_pic_flag) {\n\t\t\t\tused_by_curr_pic_flag = gf_bs_read_int_log_idx2(bs, 1, \"used_by_curr_pic_flag\", idx_rps, i);\n\t\t\t\tref_idc = used_by_curr_pic_flag << 1;\n\t\t\t}\n\t\t\tif ((ref_idc == 1) || (ref_idc == 2)) {\n\t\t\t\ts32 deltaPOC = deltaRPS;\n\t\t\t\tif (i < nb_ref_pics)\n\t\t\t\t\tdeltaPOC += ref_ps->delta_poc[i];",
"\t\t\t\trps->delta_poc[k] = deltaPOC;",
"\t\t\t\tif (deltaPOC < 0) k0++;\n\t\t\t\telse k1++;",
"\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\trps->num_negative_pics = k0;\n\t\trps->num_positive_pics = k1;\n\t}\n\telse {\n\t\ts32 prev = 0, poc;\n\t\tsps->rps[idx_rps].num_negative_pics = gf_bs_read_ue_log_idx(bs, \"num_negative_pics\", idx_rps);\n\t\tsps->rps[idx_rps].num_positive_pics = gf_bs_read_ue_log_idx(bs, \"num_positive_pics\", idx_rps);\n\t\tif (sps->rps[idx_rps].num_negative_pics > 16)\n\t\t\treturn GF_FALSE;\n\t\tif (sps->rps[idx_rps].num_positive_pics > 16)\n\t\t\treturn GF_FALSE;\n\t\tfor (i = 0; i < sps->rps[idx_rps].num_negative_pics; i++) {\n\t\t\tu32 delta_poc_s0_minus1 = gf_bs_read_ue_log_idx2(bs, \"delta_poc_s0_minus1\", idx_rps, i);\n\t\t\tpoc = prev - delta_poc_s0_minus1 - 1;\n\t\t\tprev = poc;\n\t\t\tsps->rps[idx_rps].delta_poc[i] = poc;\n\t\t\tgf_bs_read_int_log_idx2(bs, 1, \"delta_poc_s0_minus1\", idx_rps, i);\n\t\t}\n\t\tfor (i = 0; i < sps->rps[idx_rps].num_positive_pics; i++) {\n\t\t\tu32 delta_poc_s1_minus1 = gf_bs_read_ue_log_idx2(bs, \"delta_poc_s1_minus1\" , idx_rps, i);\n\t\t\tpoc = prev + delta_poc_s1_minus1 + 1;\n\t\t\tprev = poc;\n\t\t\tsps->rps[idx_rps].delta_poc[i] = poc;\n\t\t\tgf_bs_read_int_log_idx2(bs, 1, \"used_by_curr_pic_s1_flag\", idx_rps, i);\n\t\t}\n\t}\n\treturn GF_TRUE;\n}",
"void hevc_pred_weight_table(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *si, HEVC_PPS *pps, HEVC_SPS *sps, u32 num_ref_idx_l0_active, u32 num_ref_idx_l1_active)\n{\n\tu32 i, num_ref_idx;\n\tBool first_pass = GF_TRUE;\n\tu8 luma_weights[20], chroma_weights[20];\n\tu32 ChromaArrayType = sps->separate_colour_plane_flag ? 0 : sps->chroma_format_idc;",
"\tnum_ref_idx = num_ref_idx_l0_active;",
"\tgf_bs_read_ue_log(bs, \"luma_log2_weight_denom\");\n\tif (ChromaArrayType != 0)\n\t\tgf_bs_read_se_log(bs, \"delta_chroma_log2_weight_denom\");",
"parse_weights:\n\tfor (i = 0; i < num_ref_idx; i++) {\n\t\tluma_weights[i] = gf_bs_read_int_log_idx(bs, 1, \"luma_weights\", i);\n\t\t//infered to be 0 if not present\n\t\tchroma_weights[i] = 0;\n\t}\n\tif (ChromaArrayType != 0) {\n\t\tfor (i = 0; i < num_ref_idx; i++) {\n\t\t\tchroma_weights[i] = gf_bs_read_int_log_idx(bs, 1, \"chroma_weights\", i);\n\t\t}\n\t}\n\tfor (i = 0; i < num_ref_idx; i++) {\n\t\tif (luma_weights[i]) {\n\t\t\tgf_bs_read_se_log_idx(bs, \"delta_luma_weight_l0\", i);\n\t\t\tgf_bs_read_se_log_idx(bs, \"luma_offset_l0\", i);\n\t\t}\n\t\tif (chroma_weights[i]) {\n\t\t\tgf_bs_read_se_log_idx(bs, \"delta_chroma_weight_l0_0\", i);\n\t\t\tgf_bs_read_se_log_idx(bs, \"delta_chroma_offset_l0_0\", i);",
"\t\t\tgf_bs_read_se_log_idx(bs, \"delta_chroma_weight_l0_1\", i);\n\t\t\tgf_bs_read_se_log_idx(bs, \"delta_chroma_offset_l0_1\", i);\n\t\t}\n\t}",
"\tif (si->slice_type == GF_HEVC_SLICE_TYPE_B) {\n\t\tif (!first_pass) return;\n\t\tfirst_pass = GF_FALSE;\n\t\tnum_ref_idx = num_ref_idx_l1_active;\n\t\tgoto parse_weights;\n\t}\n}",
"static\nBool ref_pic_lists_modification(GF_BitStream *bs, u32 slice_type, u32 num_ref_idx_l0_active, u32 num_ref_idx_l1_active)\n{\n\t//u32 i;\n\tBool ref_pic_list_modification_flag_l0 = gf_bs_read_int_log(bs, 1, \"ref_pic_list_modification_flag_l0\");\n\tif (ref_pic_list_modification_flag_l0) {\n\t\t/*for (i=0; i<num_ref_idx_l0_active; i++) {\n\t\t\tlist_entry_l0[i] = *//*gf_bs_read_int(bs, (u32)ceil(log(getNumPicTotalCurr())/log(2)));\n\t\t}*/\n\t\treturn GF_FALSE;\n\t}\n\tif (slice_type == GF_HEVC_SLICE_TYPE_B) {\n\t\tBool ref_pic_list_modification_flag_l1 = gf_bs_read_int_log(bs, 1, \"ref_pic_list_modification_flag_l1\");\n\t\tif (ref_pic_list_modification_flag_l1) {\n\t\t\t/*for (i=0; i<num_ref_idx_l1_active; i++) {\n\t\t\t\tlist_entry_l1[i] = *//*gf_bs_read_int(bs, (u32)ceil(log(getNumPicTotalCurr()) / log(2)));\n\t\t\t}*/\n\t\t\treturn GF_FALSE;\n\t\t}\n\t}",
"\treturn GF_TRUE;\n}",
"static\ns32 hevc_parse_slice_segment(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *si)\n{\n\tu32 i, j;\n\tu32 num_ref_idx_l0_active = 0, num_ref_idx_l1_active = 0;\n\tHEVC_PPS *pps;\n\tHEVC_SPS *sps;\n\ts32 pps_id;\n\tBool RapPicFlag = GF_FALSE;\n\tBool IDRPicFlag = GF_FALSE;",
"\tsi->first_slice_segment_in_pic_flag = gf_bs_read_int_log(bs, 1, \"first_slice_segment_in_pic_flag\");",
"\tswitch (si->nal_unit_type) {\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\t\tIDRPicFlag = GF_TRUE;\n\t\tRapPicFlag = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\tcase GF_HEVC_NALU_SLICE_CRA:\n\t\tRapPicFlag = GF_TRUE;\n\t\tbreak;\n\t}",
"\tif (RapPicFlag) {\n\t\tgf_bs_read_int_log(bs, 1, \"no_output_of_prior_pics_flag\");\n\t}",
"\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\tif ((pps_id<0) || (pps_id >= 64))\n\t\treturn -1;",
"\tpps = &hevc->pps[pps_id];\n\tsps = &hevc->sps[pps->sps_id];\n\tsi->sps = sps;\n\tsi->pps = pps;",
"\tif (!si->first_slice_segment_in_pic_flag && pps->dependent_slice_segments_enabled_flag) {\n\t\tsi->dependent_slice_segment_flag = gf_bs_read_int_log(bs, 1, \"dependent_slice_segment_flag\");\n\t}\n\telse {\n\t\tsi->dependent_slice_segment_flag = GF_FALSE;\n\t}",
"\tif (!si->first_slice_segment_in_pic_flag) {\n\t\tsi->slice_segment_address = gf_bs_read_int_log(bs, sps->bitsSliceSegmentAddress, \"slice_segment_address\");\n\t}\n\telse {\n\t\tsi->slice_segment_address = 0;\n\t}",
"\tif (!si->dependent_slice_segment_flag) {\n\t\tBool deblocking_filter_override_flag = 0;\n\t\tBool slice_temporal_mvp_enabled_flag = 0;\n\t\tBool slice_sao_luma_flag = 0;\n\t\tBool slice_sao_chroma_flag = 0;\n\t\tBool slice_deblocking_filter_disabled_flag = 0;",
"\t\t//\"slice_reserved_undetermined_flag[]\"\n\t\tgf_bs_read_int_log(bs, pps->num_extra_slice_header_bits, \"slice_reserved_undetermined_flag\");",
"\t\tsi->slice_type = gf_bs_read_ue_log(bs, \"slice_type\");",
"\t\tif (pps->output_flag_present_flag)\n\t\t\tgf_bs_read_int_log(bs, 1, \"pic_output_flag\");",
"\t\tif (sps->separate_colour_plane_flag == 1)\n\t\t\tgf_bs_read_int_log(bs, 2, \"colour_plane_id\");",
"\t\tif (IDRPicFlag) {\n\t\t\tsi->poc_lsb = 0;",
"\t\t\t//if not asked to parse full header, abort since we know the poc\n\t\t\tif (!hevc->full_slice_header_parse) return 0;",
"\t\t}\n\t\telse {\n\t\t\tsi->poc_lsb = gf_bs_read_int_log(bs, sps->log2_max_pic_order_cnt_lsb, \"poc_lsb\");",
"\t\t\t//if not asked to parse full header, abort once we have the poc\n\t\t\tif (!hevc->full_slice_header_parse) return 0;",
"\t\t\tif (gf_bs_read_int_log(bs, 1, \"short_term_ref_pic_set_sps_flag\") == 0) {\n\t\t\t\tBool ret = hevc_parse_short_term_ref_pic_set(bs, sps, sps->num_short_term_ref_pic_sets);\n\t\t\t\tif (!ret)\n\t\t\t\t\treturn -1;\n\t\t\t}\n\t\t\telse if (sps->num_short_term_ref_pic_sets > 1) {\n\t\t\t\tu32 numbits = 0;",
"\t\t\t\twhile ((u32)(1 << numbits) < sps->num_short_term_ref_pic_sets)\n\t\t\t\t\tnumbits++;\n\t\t\t\tif (numbits > 0)\n\t\t\t\t\tgf_bs_read_int_log(bs, numbits, \"short_term_ref_pic_set_idx\");\n\t\t\t\t/*else\n\t\t\t\t\tshort_term_ref_pic_set_idx = 0;*/\n\t\t\t}\n\t\t\tif (sps->long_term_ref_pics_present_flag) {\n\t\t\t\tu8 DeltaPocMsbCycleLt[32];\n\t\t\t\tu32 num_long_term_sps = 0;\n\t\t\t\tu32 num_long_term_pics = 0;",
"\t\t\t\tmemset(DeltaPocMsbCycleLt, 0, sizeof(u8) * 32);\n\t\t\t\t\n\t\t\t\tif (sps->num_long_term_ref_pic_sps > 0) {\n\t\t\t\t\tnum_long_term_sps = gf_bs_read_ue_log(bs, \"num_long_term_sps\");\n\t\t\t\t}\n\t\t\t\tnum_long_term_pics = gf_bs_read_ue_log(bs, \"num_long_term_pics\");",
"\t\t\t\tfor (i = 0; i < num_long_term_sps + num_long_term_pics; i++) {\n\t\t\t\t\tif (i < num_long_term_sps) {\n\t\t\t\t\t\tif (sps->num_long_term_ref_pic_sps > 1)\n\t\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, gf_get_bit_size(sps->num_long_term_ref_pic_sps), \"lt_idx_sps\", i);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, sps->log2_max_pic_order_cnt_lsb, \"PocLsbLt\", i);\n\t\t\t\t\t\tgf_bs_read_int_log_idx(bs, 1, \"UsedByCurrPicLt\", i);\n\t\t\t\t\t}\n\t\t\t\t\tif (gf_bs_read_int_log_idx(bs, 1, \"delta_poc_msb_present_flag\", i)) {\n\t\t\t\t\t\tif (i == 0 || i == num_long_term_sps)\n\t\t\t\t\t\t\tDeltaPocMsbCycleLt[i] = gf_bs_read_ue_log_idx(bs, \"DeltaPocMsbCycleLt\", i);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tDeltaPocMsbCycleLt[i] = gf_bs_read_ue_log_idx(bs, \"DeltaPocMsbCycleLt\", i) + DeltaPocMsbCycleLt[i - 1];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (sps->temporal_mvp_enable_flag)\n\t\t\t\tslice_temporal_mvp_enabled_flag = gf_bs_read_int_log(bs, 1, \"slice_temporal_mvp_enabled_flag\");\n\t\t}\n\t\tif (sps->sample_adaptive_offset_enabled_flag) {\n\t\t\tu32 ChromaArrayType = sps->separate_colour_plane_flag ? 0 : sps->chroma_format_idc;\n\t\t\tslice_sao_luma_flag = gf_bs_read_int_log(bs, 1, \"slice_sao_luma_flag\");\n\t\t\tif (ChromaArrayType != 0)\n\t\t\t\tslice_sao_chroma_flag = gf_bs_read_int_log(bs, 1, \"slice_sao_chroma_flag\");\n\t\t}",
"\t\tif (si->slice_type == GF_HEVC_SLICE_TYPE_P || si->slice_type == GF_HEVC_SLICE_TYPE_B) {\n\t\t\t//u32 NumPocTotalCurr;\n\t\t\tnum_ref_idx_l0_active = pps->num_ref_idx_l0_default_active;\n\t\t\tnum_ref_idx_l1_active = 0;\n\t\t\tif (si->slice_type == GF_HEVC_SLICE_TYPE_B)\n\t\t\t\tnum_ref_idx_l1_active = pps->num_ref_idx_l1_default_active;",
"\t\t\tif (gf_bs_read_int_log(bs, 1, \"num_ref_idx_active_override_flag\")) {\n\t\t\t\tnum_ref_idx_l0_active = 1 + gf_bs_read_ue_log(bs, \"num_ref_idx_l0_active\");\n\t\t\t\tif (si->slice_type == GF_HEVC_SLICE_TYPE_B)\n\t\t\t\t\tnum_ref_idx_l1_active = 1 + gf_bs_read_ue_log(bs, \"num_ref_idx_l1_active\");\n\t\t\t}",
"\t\t\tif (pps->lists_modification_present_flag /*TODO: && NumPicTotalCurr > 1*/) {\n\t\t\t\tif (!ref_pic_lists_modification(bs, si->slice_type, num_ref_idx_l0_active, num_ref_idx_l1_active)) {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[hevc] ref_pic_lists_modification( ) not implemented\\n\"));\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t}",
"\t\t\tif (si->slice_type == GF_HEVC_SLICE_TYPE_B)\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"mvd_l1_zero_flag\");\n\t\t\tif (pps->cabac_init_present_flag)\n\t\t\t\tgf_bs_read_int_log(bs, 1, \"cabac_init_flag\");",
"\t\t\tif (slice_temporal_mvp_enabled_flag) {\n\t\t\t\t// When collocated_from_l0_flag is not present, it is inferred to be equal to 1.\n\t\t\t\tBool collocated_from_l0_flag = 1;\n\t\t\t\tif (si->slice_type == GF_HEVC_SLICE_TYPE_B)\n\t\t\t\t\tcollocated_from_l0_flag = gf_bs_read_int_log(bs, 1, \"collocated_from_l0_flag\");",
"\t\t\t\tif ((collocated_from_l0_flag && (num_ref_idx_l0_active > 1))\n\t\t\t\t\t|| (!collocated_from_l0_flag && (num_ref_idx_l1_active > 1))\n\t\t\t\t) {\n\t\t\t\t\tgf_bs_read_ue_log(bs, \"collocated_ref_idx\");\n\t\t\t\t}\n\t\t\t}",
"\t\t\tif ((pps->weighted_pred_flag && si->slice_type == GF_HEVC_SLICE_TYPE_P)\n\t\t\t\t|| (pps->weighted_bipred_flag && si->slice_type == GF_HEVC_SLICE_TYPE_B)\n\t\t\t\t) {\n\t\t\t\thevc_pred_weight_table(bs, hevc, si, pps, sps, num_ref_idx_l0_active, num_ref_idx_l1_active);\n\t\t\t}\n\t\t\tgf_bs_read_ue_log(bs, \"five_minus_max_num_merge_cand\");\n\t\t}\n\t\tsi->slice_qp_delta_start_bits = (s32) (gf_bs_get_position(bs) - 1) * 8 + gf_bs_get_bit_position(bs);\n\t\tsi->slice_qp_delta = gf_bs_read_se_log(bs, \"slice_qp_delta\");",
"\t\tif (pps->slice_chroma_qp_offsets_present_flag) {\n\t\t\tgf_bs_read_se_log(bs, \"slice_cb_qp_offset\");\n\t\t\tgf_bs_read_se_log(bs, \"slice_cr_qp_offset\");\n\t\t}\n\t\tif (pps->deblocking_filter_override_enabled_flag) {\n\t\t\tdeblocking_filter_override_flag = gf_bs_read_int_log(bs, 1, \"deblocking_filter_override_flag\");\n\t\t}",
"\t\tif (deblocking_filter_override_flag) {\n\t\t\tslice_deblocking_filter_disabled_flag = gf_bs_read_int_log(bs, 1, \"slice_deblocking_filter_disabled_flag\");\n\t\t\tif (!slice_deblocking_filter_disabled_flag) {\n\t\t\t\tgf_bs_read_se_log(bs, \"slice_beta_offset_div2\");\n\t\t\t\tgf_bs_read_se_log(bs, \"slice_tc_offset_div2\");\n\t\t\t}\n\t\t}\n\t\tif (pps->loop_filter_across_slices_enabled_flag\n\t\t\t&& (slice_sao_luma_flag || slice_sao_chroma_flag || !slice_deblocking_filter_disabled_flag)\n\t\t) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"slice_loop_filter_across_slices_enabled_flag\");\n\t\t}\n\t}\n\t//dependent slice segment\n\telse {\n\t\t//if not asked to parse full header, abort\n\t\tif (!hevc->full_slice_header_parse) return 0;\n\t}",
"\tsi->entry_point_start_bits = ((u32)gf_bs_get_position(bs) - 1) * 8 + gf_bs_get_bit_position(bs);",
"\tif (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag) {\n\t\tu32 num_entry_point_offsets = gf_bs_read_ue_log(bs, \"num_entry_point_offsets\");\n\t\tif (num_entry_point_offsets > 0) {\n\t\t\tu32 offset = gf_bs_read_ue_log(bs, \"offset\") + 1;\n\t\t\tu32 segments = offset >> 4;\n\t\t\ts32 remain = (offset & 15);",
"\t\t\tfor (i = 0; i < num_entry_point_offsets; i++) {\n\t\t\t\t//u32 res = 0;\n\t\t\t\tfor (j = 0; j < segments; j++) {\n\t\t\t\t\t//res <<= 16;\n\t\t\t\t\t/*res +=*/ gf_bs_read_int(bs, 16);\n\t\t\t\t}\n\t\t\t\tif (remain) {\n\t\t\t\t\t//res <<= remain;\n\t\t\t\t\t/* res += */ gf_bs_read_int(bs, remain);\n\t\t\t\t}\n\t\t\t\t// entry_point_offset = val + 1; // +1; // +1 to get the size\n\t\t\t}\n\t\t}\n\t}",
"\tif (pps->slice_segment_header_extension_present_flag) {\n\t\tu32 size_ext = gf_bs_read_ue_log(bs, \"size_ext\");\n\t\twhile (size_ext) {\n\t\t\tgf_bs_read_int(bs, 8);\n\t\t\tsize_ext--;\n\t\t}\n\t}",
"\tsi->header_size_bits = (gf_bs_get_position(bs) - 1) * 8 + gf_bs_get_bit_position(bs); // av_parser.c modified on 16 jan. 2019 ",
"\tif (gf_bs_read_int_log(bs, 1, \"byte_align\") == 0) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"Error parsing slice header: byte_align not found at end of header !\\n\"));\n\t}",
"\tgf_bs_align(bs);\n\tsi->payload_start_offset = (s32)gf_bs_get_position(bs);\n\treturn 0;\n}",
"static void gf_hevc_vvc_parse_sei(char *buffer, u32 nal_size, HEVCState *hevc, VVCState *vvc)\n{\n\tu32 ptype, psize, hdr;\n\tu64 start;\n\tGF_BitStream *bs;",
"\thdr = buffer[0];\n\tif (((hdr & 0x7e) >> 1) != GF_HEVC_NALU_SEI_PREFIX) return;",
"\tbs = gf_bs_new(buffer, nal_size, GF_BITSTREAM_READ);\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tgf_bs_read_int(bs, 16);",
"\t/*parse SEI*/\n\twhile (gf_bs_available(bs)) {\n\t\tu32 consumed;\n\t\tptype = 0;\n\t\twhile (gf_bs_peek_bits(bs, 8, 0)==0xFF) {\n\t\t\tgf_bs_read_int(bs, 8);\n\t\t\tptype += 255;\n\t\t}\n\t\tptype += gf_bs_read_int(bs, 8);\n\t\tpsize = 0;\n\t\twhile (gf_bs_peek_bits(bs, 8, 0)==0xFF) {\n\t\t\tgf_bs_read_int(bs, 8);\n\t\t\tpsize += 255;\n\t\t}\n\t\tpsize += gf_bs_read_int(bs, 8);",
"\t\tstart = gf_bs_get_position(bs);\n\t\tif (start+psize >= nal_size) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[%s] SEI user message type %d size error (%d but %d remain), skipping SEI message\\n\", hevc ? \"HEVC\" : \"VVC\", ptype, psize, nal_size-start));\n\t\t\tbreak;\n\t\t}",
"\t\tswitch (ptype) {\n\t\tcase 4: /*user registered ITU-T T35*/\n\t\t\tif (hevc) {\n\t\t\t\tavc_parse_itu_t_t35_sei(bs, &hevc->sei.dovi);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}",
"\t\tgf_bs_align(bs);\n\t\tconsumed = (u32) (gf_bs_get_position(bs) - start);\n\t\tpsize-=consumed;\n\t\tgf_bs_skip_bytes(bs, psize);\n\t\tif (gf_bs_available(bs) <= 2)\n\t\t\tbreak;\n\t}\n\tgf_bs_del(bs);\n}",
"void gf_hevc_parse_sei(char *buffer, u32 nal_size, HEVCState *hevc)\n{\n\tgf_hevc_vvc_parse_sei(buffer, nal_size, hevc, NULL);\n}",
"static void hevc_compute_poc(HEVCSliceInfo *si)\n{\n\tu32 max_poc_lsb = 1 << (si->sps->log2_max_pic_order_cnt_lsb);",
"\t/*POC reset for IDR frames, NOT for CRA*/\n\tswitch (si->nal_unit_type) {\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\t\tsi->poc_lsb_prev = 0;\n\t\tsi->poc_msb_prev = 0;\n\t\tbreak;\n\t}",
"\tif ((si->poc_lsb < si->poc_lsb_prev) && (si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2))\n\t\tsi->poc_msb = si->poc_msb_prev + max_poc_lsb;\n\telse if ((si->poc_lsb > si->poc_lsb_prev) && (si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))\n\t\tsi->poc_msb = si->poc_msb_prev - max_poc_lsb;\n\telse\n\t\tsi->poc_msb = si->poc_msb_prev;",
"\tswitch (si->nal_unit_type) {\n\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\t\tsi->poc_msb = 0;\n\t\tbreak;\n\t}\n\tsi->poc = si->poc_msb + si->poc_lsb;\n}",
"\nstatic Bool hevc_parse_nal_header(GF_BitStream *bs, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tu32 val;\n\tval = gf_bs_read_int_log(bs, 1, \"forbidden_zero\");\n\tif (val) return GF_FALSE;",
"\tval = gf_bs_read_int_log(bs, 6, \"nuh_type\");\n\tif (nal_unit_type) *nal_unit_type = val;",
"\tval = gf_bs_read_int_log(bs, 6, \"layerID\");\n\tif (layer_id) *layer_id = val;",
"\tval = gf_bs_read_int_log(bs, 3, \"temporalID\");\n\tif (!val)\n\t\treturn GF_FALSE;\n\tval -= 1;\n\tif (temporal_id) *temporal_id = val;\n\treturn GF_TRUE;\n}",
"\nvoid hevc_profile_tier_level(GF_BitStream *bs, Bool ProfilePresentFlag, u8 MaxNumSubLayersMinus1, HEVC_ProfileTierLevel *ptl, u32 idx)\n{\n\tu32 i;\n\tif (ProfilePresentFlag) {\n\t\tptl->profile_space = gf_bs_read_int_log_idx(bs, 2, \"profile_space\", idx);\n\t\tptl->tier_flag = gf_bs_read_int_log_idx(bs, 1, \"tier_flag\", idx);\n\t\tptl->profile_idc = gf_bs_read_int_log_idx(bs, 5, \"profile_idc\", idx);",
"\t\tptl->profile_compatibility_flag = gf_bs_read_int_log_idx(bs, 32, \"profile_compatibility_flag\", idx);",
"\t\tptl->general_progressive_source_flag = gf_bs_read_int_log_idx(bs, 1, \"general_progressive_source_flag\", idx);\n\t\tptl->general_interlaced_source_flag = gf_bs_read_int_log_idx(bs, 1, \"general_interlaced_source_flag\", idx);\n\t\tptl->general_non_packed_constraint_flag = gf_bs_read_int_log_idx(bs, 1, \"general_non_packed_constraint_flag\", idx);\n\t\tptl->general_frame_only_constraint_flag = gf_bs_read_int_log_idx(bs, 1, \"general_frame_only_constraint_flag\", idx);\n\t\tptl->general_reserved_44bits = gf_bs_read_long_int(bs, 44);\n\t}\n\tptl->level_idc = gf_bs_read_int_log(bs, 8, \"level_idc\");\n\tfor (i = 0; i < MaxNumSubLayersMinus1; i++) {\n\t\tptl->sub_ptl[i].profile_present_flag = gf_bs_read_int_log_idx2(bs, 1, \"profile_present_flag\", idx, i);\n\t\tptl->sub_ptl[i].level_present_flag = gf_bs_read_int_log_idx2(bs, 1, \"level_present_flag\", idx, i);\n\t}\n\tif (MaxNumSubLayersMinus1 > 0) {\n\t\tfor (i = MaxNumSubLayersMinus1; i < 8; i++) {\n\t\t\t/*reserved_zero_2bits*/gf_bs_read_int(bs, 2);\n\t\t}\n\t}",
"\tfor (i = 0; i < MaxNumSubLayersMinus1; i++) {\n\t\tif (ptl->sub_ptl[i].profile_present_flag) {\n\t\t\tptl->sub_ptl[i].profile_space = gf_bs_read_int_log_idx2(bs, 2, \"sublayer_profile_space\", idx, i);\n\t\t\tptl->sub_ptl[i].tier_flag = gf_bs_read_int_log_idx2(bs, 1, \"sublayer_tier_flag\", idx, i);\n\t\t\tptl->sub_ptl[i].profile_idc = gf_bs_read_int_log_idx2(bs, 5, \"sublayer_profile_idc\", idx, i);\n\t\t\tptl->sub_ptl[i].profile_compatibility_flag = gf_bs_read_int_log_idx2(bs, 32, \"sublayer_profile_compatibility_flag\", idx, i);\n\t\t\t/*ptl->sub_ptl[i].progressive_source_flag =*/ gf_bs_read_int_log_idx2(bs, 1, \"sublayer_progressive_source_flag\", idx, i);\n\t\t\t/*ptl->sub_ptl[i].interlaced_source_flag =*/ gf_bs_read_int_log_idx2(bs, 1, \"sublayer_interlaced_source_flag\", idx, i);\n\t\t\t/*ptl->sub_ptl[i].non_packed_constraint_flag =*/ gf_bs_read_int_log_idx2(bs, 1, \"sublayer_non_packed_constraint_flag\", idx, i);\n\t\t\t/*ptl->sub_ptl[i].frame_only_constraint_flag =*/ gf_bs_read_int_log_idx2(bs, 1, \"sublayer_frame_only_constraint_flag\", idx, i);\n\t\t\t/*ptl->sub_ptl[i].reserved_44bits =*/ gf_bs_read_long_int(bs, 44);\n\t\t}\n\t\tif (ptl->sub_ptl[i].level_present_flag)\n\t\t\tptl->sub_ptl[i].level_idc = gf_bs_read_int_log_idx2(bs, 8, \"sublayer_level_idc\", idx, i);\n\t}\n}",
"static u32 scalability_type_to_idx(HEVC_VPS *vps, u32 scalability_type)\n{\n\tu32 idx = 0, type;\n\tfor (type = 0; type < scalability_type; type++) {\n\t\tidx += (vps->scalability_mask[type] ? 1 : 0);\n\t}\n\treturn idx;\n}",
"#define LHVC_VIEW_ORDER_INDEX 1\n#define LHVC_SCALABILITY_INDEX\t2",
"static u32 lhvc_get_scalability_id(HEVC_VPS *vps, u32 layer_id_in_vps, u32 scalability_type)\n{\n\tu32 idx;\n\tif (!vps->scalability_mask[scalability_type]) return 0;\n\tidx = scalability_type_to_idx(vps, scalability_type);\n\treturn vps->dimension_id[layer_id_in_vps][idx];\n}",
"static u32 lhvc_get_view_index(HEVC_VPS *vps, u32 id)\n{\n\treturn lhvc_get_scalability_id(vps, vps->layer_id_in_vps[id], LHVC_VIEW_ORDER_INDEX);\n}",
"static u32 lhvc_get_num_views(HEVC_VPS *vps)\n{\n\tu32 numViews = 1, i;\n\tfor (i = 0; i < vps->max_layers; i++) {\n\t\tu32 layer_id = vps->layer_id_in_nuh[i];\n\t\tif (i > 0 && (lhvc_get_view_index(vps, layer_id) != lhvc_get_scalability_id(vps, i - 1, LHVC_VIEW_ORDER_INDEX))) {\n\t\t\tnumViews++;\n\t\t}\n\t}\n\treturn numViews;\n}",
"static void lhvc_parse_rep_format(HEVC_RepFormat *fmt, GF_BitStream *bs, u32 idx)\n{\n\tu8 chroma_bitdepth_present_flag;\n\tfmt->pic_width_luma_samples = gf_bs_read_int_log_idx(bs, 16, \"pic_width_luma_samples\", idx);\n\tfmt->pic_height_luma_samples = gf_bs_read_int_log_idx(bs, 16, \"pic_height_luma_samples\", idx);\n\tchroma_bitdepth_present_flag = gf_bs_read_int_log_idx(bs, 1, \"chroma_bitdepth_present_flag\", idx);\n\tif (chroma_bitdepth_present_flag) {\n\t\tfmt->chroma_format_idc = gf_bs_read_int_log_idx(bs, 2, \"chroma_format_idc\", idx);",
"\t\tif (fmt->chroma_format_idc == 3)\n\t\t\tfmt->separate_colour_plane_flag = gf_bs_read_int_log_idx(bs, 1, \"separate_colour_plane_flag\", idx);\n\t\tfmt->bit_depth_luma = 8 + gf_bs_read_int_log_idx(bs, 4, \"bit_depth_luma_minus8\", idx);\n\t\tfmt->bit_depth_chroma = 8 + gf_bs_read_int_log_idx(bs, 4, \"bit_depth_chroma_minus8\", idx);\n\t}\n\tif (gf_bs_read_int_log_idx(bs, 1, \"conformance_window_vps_flag\", idx)) {\n\t\tgf_bs_read_ue_log_idx(bs, \"conf_win_vps_left_offset\", idx);\n\t\tgf_bs_read_ue_log_idx(bs, \"conf_win_vps_right_offset\", idx);\n\t\tgf_bs_read_ue_log_idx(bs, \"conf_win_vps_top_offset\", idx);\n\t\tgf_bs_read_ue_log_idx(bs, \"conf_win_vps_bottom_offset\", idx);\n\t}\n}",
"\nstatic Bool hevc_parse_vps_extension(HEVC_VPS *vps, GF_BitStream *bs)\n{\n\tu8 splitting_flag, vps_nuh_layer_id_present_flag, view_id_len;\n\tu32 i, j, num_scalability_types, num_add_olss, num_add_layer_set, num_indepentdent_layers, nb_bits, default_output_layer_idc = 0;\n\tu8 dimension_id_len[16], dim_bit_offset[16];\n\tu8 /*avc_base_layer_flag, */NumLayerSets, /*default_one_target_output_layer_flag, */rep_format_idx_present_flag, ols_ids_to_ls_idx;\n\tu8 layer_set_idx_for_ols_minus1[MAX_LHVC_LAYERS];\n\tu8 nb_output_layers_in_output_layer_set[MAX_LHVC_LAYERS + 1];\n\tu8 ols_highest_output_layer_id[MAX_LHVC_LAYERS + 1];",
"\tu32 k, d, r, p, iNuhLId, jNuhLId;\n\tu8 num_direct_ref_layers[64], num_pred_layers[64], num_layers_in_tree_partition[MAX_LHVC_LAYERS];\n\tu8 dependency_flag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS], id_pred_layers[64][MAX_LHVC_LAYERS];\n\t//\tu8 num_ref_layers[64];\n\t//\tu8 tree_partition_layer_id[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];\n\t//\tu8 id_ref_layers[64][MAX_LHVC_LAYERS];\n\t//\tu8 id_direct_ref_layers[64][MAX_LHVC_LAYERS];\n\tu8 layer_id_in_list_flag[64];\n\tBool OutputLayerFlag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];",
"\tvps->vps_extension_found = 1;\n\tif ((vps->max_layers > 1) && vps->base_layer_internal_flag)\n\t\thevc_profile_tier_level(bs, 0, vps->max_sub_layers - 1, &vps->ext_ptl[0], 0);",
"\tsplitting_flag = gf_bs_read_int_log(bs, 1, \"splitting_flag\");\n\tnum_scalability_types = 0;\n\tfor (i = 0; i < 16; i++) {\n\t\tvps->scalability_mask[i] = gf_bs_read_int_log_idx(bs, 1, \"scalability_mask\", i);\n\t\tnum_scalability_types += vps->scalability_mask[i];\n\t}\n\tif (num_scalability_types >= 16) {\n\t\tnum_scalability_types = 16;\n\t}\n\tdimension_id_len[0] = 0;\n\tfor (i = 0; i < (num_scalability_types - splitting_flag); i++) {\n\t\tdimension_id_len[i] = 1 + gf_bs_read_int_log_idx(bs, 3, \"dimension_id_len_minus1\", i);\n\t}",
"\tif (splitting_flag) {\n\t\tfor (i = 0; i < num_scalability_types; i++) {\n\t\t\tdim_bit_offset[i] = 0;\n\t\t\tfor (j = 0; j < i; j++)\n\t\t\t\tdim_bit_offset[i] += dimension_id_len[j];\n\t\t}\n\t\tdimension_id_len[num_scalability_types - 1] = 1 + (5 - dim_bit_offset[num_scalability_types - 1]);\n\t\tdim_bit_offset[num_scalability_types] = 6;\n\t}",
"\tvps_nuh_layer_id_present_flag = gf_bs_read_int_log(bs, 1, \"vps_nuh_layer_id_present_flag\");\n\tvps->layer_id_in_nuh[0] = 0;\n\tvps->layer_id_in_vps[0] = 0;\n\tfor (i = 1; i < vps->max_layers; i++) {\n\t\tif (vps_nuh_layer_id_present_flag) {\n\t\t\tvps->layer_id_in_nuh[i] = gf_bs_read_int_log_idx(bs, 6, \"layer_id_in_nuh\", i);\n\t\t}\n\t\telse {\n\t\t\tvps->layer_id_in_nuh[i] = i;\n\t\t}\n\t\tvps->layer_id_in_vps[vps->layer_id_in_nuh[i]] = i;",
"\t\tif (!splitting_flag) {\n\t\t\tfor (j = 0; j < num_scalability_types; j++) {\n\t\t\t\tvps->dimension_id[i][j] = gf_bs_read_int_log_idx2(bs, dimension_id_len[j], \"dimension_id\", i, j);\n\t\t\t}\n\t\t}\n\t}",
"\tif (splitting_flag) {\n\t\tfor (i = 0; i < vps->max_layers; i++)\n\t\t\tfor (j = 0; j < num_scalability_types; j++)\n\t\t\t\tvps->dimension_id[i][j] = ((vps->layer_id_in_nuh[i] & ((1 << dim_bit_offset[j + 1]) - 1)) >> dim_bit_offset[j]);\n\t}\n\telse {\n\t\tfor (j = 0; j < num_scalability_types; j++)\n\t\t\tvps->dimension_id[0][j] = 0;\n\t}",
"\tview_id_len = gf_bs_read_int_log(bs, 4, \"view_id_len\");\n\tif (view_id_len > 0) {\n\t\tfor (i = 0; i < lhvc_get_num_views(vps); i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, view_id_len, \"view_id_val\", i);\n\t\t}\n\t}",
"\tfor (i = 1; i < vps->max_layers; i++) {\n\t\tfor (j = 0; j < i; j++) {\n\t\t\tvps->direct_dependency_flag[i][j] = gf_bs_read_int_log_idx(bs, 1, \"direct_dependency_flag\", i);\n\t\t}\n\t}",
"\t//we do the test on MAX_LHVC_LAYERS and break in the loop to avoid a wrong GCC 4.8 warning on array bounds\n\tfor (i = 0; i < MAX_LHVC_LAYERS; i++) {\n\t\tif (i >= vps->max_layers) break;\n\t\tfor (j = 0; j < vps->max_layers; j++) {\n\t\t\tdependency_flag[i][j] = vps->direct_dependency_flag[i][j];\n\t\t\tfor (k = 0; k < i; k++)\n\t\t\t\tif (vps->direct_dependency_flag[i][k] && vps->direct_dependency_flag[k][j])\n\t\t\t\t\tdependency_flag[i][j] = 1;\n\t\t}\n\t}",
"\tfor (i = 0; i < vps->max_layers; i++) {\n\t\tiNuhLId = vps->layer_id_in_nuh[i];\n\t\td = r = p = 0;\n\t\tfor (j = 0; j < vps->max_layers; j++) {\n\t\t\tjNuhLId = vps->layer_id_in_nuh[j];\n\t\t\tif (vps->direct_dependency_flag[i][j]) {\n\t\t\t\t//\t\t\t\tid_direct_ref_layers[iNuhLId][d] = jNuhLId;\n\t\t\t\td++;\n\t\t\t}\n\t\t\tif (dependency_flag[i][j]) {\n\t\t\t\t//\t\t\t\tid_ref_layers[iNuhLId][r] = jNuhLId;\n\t\t\t\tr++;\n\t\t\t}",
"\t\t\tif (dependency_flag[j][i])\n\t\t\t\tid_pred_layers[iNuhLId][p++] = jNuhLId;\n\t\t}\n\t\tnum_direct_ref_layers[iNuhLId] = d;\n\t\t//\t\tnum_ref_layers[iNuhLId] = r;\n\t\tnum_pred_layers[iNuhLId] = p;\n\t}",
"\tmemset(layer_id_in_list_flag, 0, 64 * sizeof(u8));\n\tk = 0; //num_indepentdent_layers\n\tfor (i = 0; i < vps->max_layers; i++) {\n\t\tiNuhLId = vps->layer_id_in_nuh[i];\n\t\tif (!num_direct_ref_layers[iNuhLId]) {\n\t\t\tu32 h = 1;\n\t\t\t//tree_partition_layer_id[k][0] = iNuhLId;\n\t\t\tfor (j = 0; j < num_pred_layers[iNuhLId]; j++) {\n\t\t\t\tu32 predLId = id_pred_layers[iNuhLId][j];\n\t\t\t\tif (!layer_id_in_list_flag[predLId]) {\n\t\t\t\t\t//tree_partition_layer_id[k][h++] = predLId;\n\t\t\t\t\tlayer_id_in_list_flag[predLId] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnum_layers_in_tree_partition[k++] = h;\n\t\t}\n\t}\n\tnum_indepentdent_layers = k;",
"\tnum_add_layer_set = 0;\n\tif (num_indepentdent_layers > 1)\n\t\tnum_add_layer_set = gf_bs_read_ue_log(bs, \"num_add_layer_set\");",
"\tfor (i = 0; i < num_add_layer_set; i++)\n\t\tfor (j = 1; j < num_indepentdent_layers; j++) {\n\t\t\tnb_bits = 1;\n\t\t\twhile ((1 << nb_bits) < (num_layers_in_tree_partition[j] + 1))\n\t\t\t\tnb_bits++;\n\t\t\tgf_bs_read_int_log_idx2(bs, nb_bits, \"highest_layer_idx_plus1\", i, j);\n\t\t}",
"\n\tif (gf_bs_read_int_log(bs, 1, \"vps_sub_layers_max_minus1_present_flag\")) {\n\t\tfor (i = 0; i < vps->max_layers; i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, 3, \"sub_layers_vps_max_minus1\", i);\n\t\t}\n\t}",
"\tif (gf_bs_read_int_log(bs, 1, \"max_tid_ref_present_flag\")) {\n\t\tfor (i = 0; i < (vps->max_layers - 1); i++) {\n\t\t\tfor (j = i + 1; j < vps->max_layers; j++) {\n\t\t\t\tif (vps->direct_dependency_flag[j][i])\n\t\t\t\t\tgf_bs_read_int_log_idx2(bs, 3, \"max_tid_il_ref_pics_plus1\", i, j);\n\t\t\t}\n\t\t}\n\t}\n\tgf_bs_read_int_log(bs, 1, \"default_ref_layers_active_flag\");",
"\tvps->num_profile_tier_level = 1 + gf_bs_read_ue_log(bs, \"num_profile_tier_level\");\n\tif (vps->num_profile_tier_level > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Wrong number of PTLs in VPS %d\\n\", vps->num_profile_tier_level));\n\t\tvps->num_profile_tier_level = 1;\n\t\treturn GF_FALSE;\n\t}",
"\tfor (i = vps->base_layer_internal_flag ? 2 : 1; i < vps->num_profile_tier_level; i++) {\n\t\tBool vps_profile_present_flag = gf_bs_read_int_log_idx(bs, 1, \"vps_profile_present_flag\", i);\n\t\thevc_profile_tier_level(bs, vps_profile_present_flag, vps->max_sub_layers - 1, &vps->ext_ptl[i - 1], i-1);\n\t}",
"\tNumLayerSets = vps->num_layer_sets + num_add_layer_set;\n\tnum_add_olss = 0;",
"\tif (NumLayerSets > 1) {\n\t\tnum_add_olss = gf_bs_read_ue_log(bs, \"num_add_olss\");\n\t\tdefault_output_layer_idc = gf_bs_read_int_log(bs, 2, \"default_output_layer_idc\");\n\t\tdefault_output_layer_idc = default_output_layer_idc < 2 ? default_output_layer_idc : 2;\n\t}\n\tvps->num_output_layer_sets = num_add_olss + NumLayerSets;",
"\tif (vps->num_output_layer_sets > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Wrong number of output layer sets in VPS %d, max %d supported\\n\", vps->num_output_layer_sets, MAX_LHVC_LAYERS));\n\t\tvps->num_output_layer_sets = 1;\n\t\treturn GF_FALSE;\n\t}",
"\tlayer_set_idx_for_ols_minus1[0] = 1;\n\tvps->output_layer_flag[0][0] = 1;",
"\tfor (i = 0; i < vps->num_output_layer_sets; i++) {\n\t\tif ((NumLayerSets > 2) && (i >= NumLayerSets)) {\n\t\t\tnb_bits = 1;\n\t\t\twhile ((1 << nb_bits) < (NumLayerSets - 1))\n\t\t\t\tnb_bits++;\n\t\t\tlayer_set_idx_for_ols_minus1[i] = gf_bs_read_int_log_idx(bs, nb_bits, \"layer_set_idx_for_ols_minus1\", i);\n\t\t}\n\t\telse\n\t\t\tlayer_set_idx_for_ols_minus1[i] = 0;\n\t\tols_ids_to_ls_idx = i < NumLayerSets ? i : layer_set_idx_for_ols_minus1[i] + 1;",
"\t\tif ((i > (vps->num_layer_sets - 1)) || (default_output_layer_idc == 2)) {\n\t\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)\n\t\t\t\tvps->output_layer_flag[i][j] = gf_bs_read_int_log_idx2(bs, 1, \"output_layer_flag\", i, j);\n\t\t}",
"\t\tif ((default_output_layer_idc == 0) || (default_output_layer_idc == 1)) {\n\t\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\t\tif ((default_output_layer_idc == 0) || (vps->LayerSetLayerIdList[i][j] == vps->LayerSetLayerIdListMax[i]))\n\t\t\t\t\tOutputLayerFlag[i][j] = GF_TRUE;\n\t\t\t\telse\n\t\t\t\t\tOutputLayerFlag[i][j] = GF_FALSE;\n\t\t\t}\n\t\t}",
"\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\tif (OutputLayerFlag[i][j]) {\n\t\t\t\tu32 curLayerID;\n\t\t\t\tvps->necessary_layers_flag[i][j] = GF_TRUE;\n\t\t\t\tcurLayerID = vps->LayerSetLayerIdList[i][j];\n\t\t\t\tfor (k = 0; k < j; k++) {\n\t\t\t\t\tu32 refLayerId = vps->LayerSetLayerIdList[i][k];\n\t\t\t\t\tif (dependency_flag[vps->layer_id_in_vps[curLayerID]][vps->layer_id_in_vps[refLayerId]])\n\t\t\t\t\t\tvps->necessary_layers_flag[i][k] = GF_TRUE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvps->num_necessary_layers[i] = 0;\n\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\tif (vps->necessary_layers_flag[i][j])\n\t\t\t\tvps->num_necessary_layers[i] += 1;\n\t\t}",
"\t\tif (i == 0) {\n\t\t\tif (vps->base_layer_internal_flag) {\n\t\t\t\tif (vps->max_layers > 1)\n\t\t\t\t\tvps->profile_tier_level_idx[0][0] = 1;\n\t\t\t\telse\n\t\t\t\t\tvps->profile_tier_level_idx[0][0] = 0;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tnb_bits = 1;\n\t\twhile ((u32)(1 << nb_bits) < vps->num_profile_tier_level)\n\t\t\tnb_bits++;\n\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)\n\t\t\tif (vps->necessary_layers_flag[i][j] && vps->num_profile_tier_level)\n\t\t\t\tvps->profile_tier_level_idx[i][j] = gf_bs_read_int_log_idx2(bs, nb_bits, \"profile_tier_level_idx\", i, j);\n\t\t\telse\n\t\t\t\tvps->profile_tier_level_idx[i][j] = 0;",
"\n\t\tnb_output_layers_in_output_layer_set[i] = 0;\n\t\tfor (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {\n\t\t\tnb_output_layers_in_output_layer_set[i] += OutputLayerFlag[i][j];\n\t\t\tif (OutputLayerFlag[i][j]) {\n\t\t\t\tols_highest_output_layer_id[i] = vps->LayerSetLayerIdList[ols_ids_to_ls_idx][j];\n\t\t\t}\n\t\t}\n\t\tif (nb_output_layers_in_output_layer_set[i] == 1 && ols_highest_output_layer_id[i] > 0)\n\t\t\tvps->alt_output_layer_flag[i] = gf_bs_read_int_log_idx(bs, 1, \"alt_output_layer_flag\", i);\n\t}",
"\tvps->num_rep_formats = 1 + gf_bs_read_ue_log(bs, \"num_rep_formats_minus1\");\n\tif (vps->num_rep_formats > 16) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Wrong number of rep formats in VPS %d\\n\", vps->num_rep_formats));\n\t\tvps->num_rep_formats = 0;\n\t\treturn GF_FALSE;\n\t}",
"\tfor (i = 0; i < vps->num_rep_formats; i++) {\n\t\tlhvc_parse_rep_format(&vps->rep_formats[i], bs, i);\n\t}\n\tif (vps->num_rep_formats > 1)\n\t\trep_format_idx_present_flag = gf_bs_read_int_log(bs, 1, \"rep_format_idx_present_flag\");\n\telse\n\t\trep_format_idx_present_flag = 0;",
"\tvps->rep_format_idx[0] = 0;\n\tnb_bits = 1;\n\twhile ((u32)(1 << nb_bits) < vps->num_rep_formats)\n\t\tnb_bits++;\n\tfor (i = vps->base_layer_internal_flag ? 1 : 0; i < vps->max_layers; i++) {\n\t\tif (rep_format_idx_present_flag) {\n\t\t\tvps->rep_format_idx[i] = gf_bs_read_int_log_idx(bs, nb_bits, \"rep_format_idx\", i);\n\t\t}\n\t\telse {\n\t\t\tvps->rep_format_idx[i] = i < vps->num_rep_formats - 1 ? i : vps->num_rep_formats - 1;\n\t\t}\n\t}\n\t//TODO - we don't use the rest ...",
"\treturn GF_TRUE;\n}",
"static void sub_layer_hrd_parameters(GF_BitStream *bs, int subLayerId, u32 cpb_cnt, Bool sub_pic_hrd_params_present_flag, u32 idx1, u32 idx2)\n{\n\tu32 i;\n\tif (!gf_bs_available(bs)) return;",
"\tfor (i = 0; i <= cpb_cnt; i++) {\n\t\tgf_bs_read_ue_log_idx3(bs, \"bit_rate_value_minus1\", idx1, idx2, i);\n\t\tgf_bs_read_ue_log_idx3(bs, \"cpb_size_value_minus1\", idx1, idx2, i);\n\t\tif (sub_pic_hrd_params_present_flag) {\n\t\t\tgf_bs_read_ue_log_idx3(bs, \"cpb_size_du_value_minus1\", idx1, idx2, i);\n\t\t\tgf_bs_read_ue_log_idx3(bs, \"bit_rate_du_value_minus1\", idx1, idx2, i);\n\t\t}\n\t\tgf_bs_read_int_log_idx3(bs, 1, \"cbr_flag\", idx1, idx2, i);\n\t}\n}",
"static void hevc_parse_hrd_parameters(GF_BitStream *bs, Bool commonInfPresentFlag, int maxNumSubLayersMinus1, u32 idx)\n{\n\tint i;\n\tBool nal_hrd_parameters_present_flag = GF_FALSE;\n\tBool vcl_hrd_parameters_present_flag = GF_FALSE;\n\tBool sub_pic_hrd_params_present_flag = GF_FALSE;",
"\tif (commonInfPresentFlag) {\n\t\tnal_hrd_parameters_present_flag = gf_bs_read_int_log_idx(bs, 1, \"nal_hrd_parameters_present_flag\", idx);\n\t\tvcl_hrd_parameters_present_flag = gf_bs_read_int_log_idx(bs, 1, \"vcl_hrd_parameters_present_flag\", idx);\n\t\tif (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {\n\t\t\tsub_pic_hrd_params_present_flag = gf_bs_read_int_log_idx(bs, 1, \"sub_pic_hrd_params_present_flag\", idx);\n\t\t\tif (sub_pic_hrd_params_present_flag) {\n\t\t\t\tgf_bs_read_int_log_idx(bs, 8, \"tick_divisor_minus2\", idx);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 5, \"du_cpb_removal_delay_increment_length_minus1\", idx);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 1, \"sub_pic_cpb_params_in_pic_timing_sei_flag\", idx);\n\t\t\t\tgf_bs_read_int_log_idx(bs, 5, \"dpb_output_delay_du_length_minus1\", idx);\n\t\t\t}\n\t\t\tgf_bs_read_int_log_idx(bs, 4, \"bit_rate_scale\", idx);\n\t\t\tgf_bs_read_int_log_idx(bs, 4, \"cpb_size_scale\", idx);\n\t\t\tif (sub_pic_hrd_params_present_flag) {\n\t\t\t\tgf_bs_read_int_log_idx(bs, 4, \"cpb_size_du_scale\", idx);\n\t\t\t}\n\t\t\tgf_bs_read_int_log_idx(bs, 5, \"initial_cpb_removal_delay_length_minus1\", idx);\n\t\t\tgf_bs_read_int_log_idx(bs, 5, \"au_cpb_removal_delay_length_minus1\", idx);\n\t\t\tgf_bs_read_int_log_idx(bs, 5, \"dpb_output_delay_length_minus1\", idx);\n\t\t}\n\t}\n\tfor (i = 0; i <= maxNumSubLayersMinus1; i++) {\n\t\tBool fixed_pic_rate_general_flag_i = gf_bs_read_int_log_idx(bs, 1, \"fixed_pic_rate_general_flag\", idx);\n\t\tBool fixed_pic_rate_within_cvs_flag_i = GF_TRUE;\n\t\tBool low_delay_hrd_flag_i = GF_FALSE;\n\t\tu32 cpb_cnt_minus1_i = 0;\n\t\tif (!fixed_pic_rate_general_flag_i) {\n\t\t\tfixed_pic_rate_within_cvs_flag_i = gf_bs_read_int_log_idx(bs, 1, \"fixed_pic_rate_within_cvs_flag\", idx);\n\t\t}\n\t\tif (fixed_pic_rate_within_cvs_flag_i)\n\t\t\tgf_bs_read_ue_log_idx(bs, \"elemental_duration_in_tc_minus1\", idx);\n\t\telse\n\t\t\tlow_delay_hrd_flag_i = gf_bs_read_int_log_idx(bs, 1, \"low_delay_hrd_flag\", idx);\n\t\tif (!low_delay_hrd_flag_i) {\n\t\t\tcpb_cnt_minus1_i = gf_bs_read_ue_log_idx(bs, \"cpb_cnt_minus1\", idx);\n\t\t}\n\t\tif (nal_hrd_parameters_present_flag) {\n\t\t\tsub_layer_hrd_parameters(bs, i, cpb_cnt_minus1_i, sub_pic_hrd_params_present_flag, idx, i);\n\t\t}\n\t\tif (vcl_hrd_parameters_present_flag) {\n\t\t\tsub_layer_hrd_parameters(bs, i, cpb_cnt_minus1_i, sub_pic_hrd_params_present_flag, idx, i);\n\t\t}\n\t}\n}",
"static s32 gf_hevc_read_vps_bs_internal(GF_BitStream *bs, HEVCState *hevc, Bool stop_at_vps_ext)\n{\n\tu8 vps_sub_layer_ordering_info_present_flag, vps_extension_flag;\n\tu32 i, j;\n\ts32 vps_id;\n\tHEVC_VPS *vps;\n\tu8 layer_id_included_flag[MAX_LHVC_LAYERS][64];",
"\t//nalu header already parsed\n\tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");",
"\tif ((vps_id<0) || (vps_id >= 16)) return -1;",
"\tvps = &hevc->vps[vps_id];\n\tvps->bit_pos_vps_extensions = -1;\n\tif (!vps->state) {\n\t\tvps->id = vps_id;\n\t\tvps->state = 1;\n\t}",
"\tvps->base_layer_internal_flag = gf_bs_read_int_log(bs, 1, \"base_layer_internal_flag\");\n\tvps->base_layer_available_flag = gf_bs_read_int_log(bs, 1, \"base_layer_available_flag\");\n\tvps->max_layers = 1 + gf_bs_read_int_log(bs, 6, \"max_layers_minus1\");\n\tif (vps->max_layers > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] sorry, %d layers in VPS but only %d supported\\n\", vps->max_layers, MAX_LHVC_LAYERS));\n\t\treturn -1;\n\t}\n\tvps->max_sub_layers = gf_bs_read_int_log(bs, 3, \"max_sub_layers_minus1\") + 1;\n\tvps->temporal_id_nesting = gf_bs_read_int_log(bs, 1, \"temporal_id_nesting\");\n\tgf_bs_read_int_log(bs, 16, \"vps_reserved_ffff_16bits\");\n\thevc_profile_tier_level(bs, 1, vps->max_sub_layers - 1, &vps->ptl, 0);",
"\tvps_sub_layer_ordering_info_present_flag = gf_bs_read_int_log(bs, 1, \"vps_sub_layer_ordering_info_present_flag\");\n\tfor (i = (vps_sub_layer_ordering_info_present_flag ? 0 : vps->max_sub_layers - 1); i < vps->max_sub_layers; i++) {\n\t\tgf_bs_read_ue_log_idx(bs, \"vps_max_dec_pic_buffering_minus1\", i);\n\t\tgf_bs_read_ue_log_idx(bs, \"vps_max_num_reorder_pics\", i);\n\t\tgf_bs_read_ue_log_idx(bs, \"vps_max_latency_increase_plus1\", i);\n\t}\n\tvps->max_layer_id = gf_bs_read_int_log(bs, 6, \"max_layer_id\");\n\tif (vps->max_layer_id > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] VPS max layer ID %u but GPAC only supports %u\\n\", vps->max_layer_id, MAX_LHVC_LAYERS));\n\t\treturn -1;\n\t}\n\tvps->num_layer_sets = gf_bs_read_ue_log(bs, \"num_layer_sets_minus1\") + 1;\n\tif (vps->num_layer_sets > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Wrong number of layer sets in VPS %d\\n\", vps->num_layer_sets));\n\t\treturn -1;\n\t}\n\tfor (i = 1; i < vps->num_layer_sets; i++) {\n\t\tfor (j = 0; j <= vps->max_layer_id; j++) {\n\t\t\tlayer_id_included_flag[i][j] = gf_bs_read_int_log_idx2(bs, 1, \"layer_id_included_flag\", i, j);\n\t\t}\n\t}\n\tvps->num_layers_in_id_list[0] = 1;\n\tfor (i = 1; i < vps->num_layer_sets; i++) {\n\t\tu32 n, m;\n\t\tn = 0;\n\t\tfor (m = 0; m <= vps->max_layer_id; m++) {\n\t\t\tif (layer_id_included_flag[i][m]) {\n\t\t\t\tvps->LayerSetLayerIdList[i][n++] = m;\n\t\t\t\tif (vps->LayerSetLayerIdListMax[i] < m)\n\t\t\t\t\tvps->LayerSetLayerIdListMax[i] = m;\n\t\t\t}\n\t\t}\n\t\tvps->num_layers_in_id_list[i] = n;\n\t}\n\tif (gf_bs_read_int_log(bs, 1, \"vps_timing_info_present_flag\")) {\n\t\tu32 vps_num_hrd_parameters;\n\t\tgf_bs_read_int_log(bs, 32, \"vps_num_units_in_tick\");\n\t\tgf_bs_read_int_log(bs, 32, \"vps_time_scale\");\n\t\tif (gf_bs_read_int_log(bs, 1, \"vps_poc_proportional_to_timing_flag\")) {\n\t\t\tgf_bs_read_ue_log(bs, \"vps_num_ticks_poc_diff_one_minus1\");\n\t\t}\n\t\tvps_num_hrd_parameters = gf_bs_read_ue_log(bs, \"vps_num_hrd_parameters\");\n\t\tfor (i = 0; i < vps_num_hrd_parameters; i++) {\n\t\t\tBool cprms_present_flag = GF_TRUE;\n\t\t\tgf_bs_read_ue_log_idx(bs, \"hrd_layer_set_idx\", i);\n\t\t\tif (i > 0)\n\t\t\t\tcprms_present_flag = gf_bs_read_int_log(bs, 1, \"cprms_present_flag\");\n\t\t\thevc_parse_hrd_parameters(bs, cprms_present_flag, vps->max_sub_layers - 1, i);\n\t\t}\n\t}\n\tif (stop_at_vps_ext) {\n\t\treturn vps_id;\n\t}",
"\tvps_extension_flag = gf_bs_read_int_log(bs, 1, \"vps_extension_flag\");\n\tif (vps_extension_flag) {\n\t\tBool res;\n\t\tgf_bs_align(bs);\n\t\tres = hevc_parse_vps_extension(vps, bs);\n\t\tif (res != GF_TRUE) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Failed to parse VPS extensions\\n\"));\n\t\t\treturn -1;\n\t\t}\n\t\tif (gf_bs_read_int_log(bs, 1, \"vps_extension2_flag\")) {\n#if 0\n\t\t\twhile (gf_bs_available(bs)) {\n\t\t\t\t/*vps_extension_data_flag */ gf_bs_read_int(bs, 1);\n\t\t\t}\n#endif",
"\t\t}\n\t}\n\treturn vps_id;\n}",
"GF_EXPORT\ns32 gf_hevc_read_vps_ex(u8 *data, u32 *size, HEVCState *hevc, Bool remove_extensions)\n{\n\tGF_BitStream *bs;\n\tchar *data_without_emulation_bytes = NULL;\n\tu32 data_without_emulation_bytes_size = 0;\n\ts32 vps_id = -1;",
"\t/*still contains emulation bytes*/\n\tdata_without_emulation_bytes_size = remove_extensions ? gf_media_nalu_emulation_bytes_remove_count(data, (*size)) : 0;\n\tif (!data_without_emulation_bytes_size) {\n\t\tbs = gf_bs_new(data, (*size), GF_BITSTREAM_READ);\n\t\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\t}\n\t//when removing VPS ext, we have to get the full buffer without emulation prevention bytes becuase we do a bit-by-bit copy of the vps\n\telse {\n\t\tdata_without_emulation_bytes = gf_malloc((*size) * sizeof(char));\n\t\tdata_without_emulation_bytes_size = gf_media_nalu_remove_emulation_bytes(data, data_without_emulation_bytes, (*size));\n\t\tbs = gf_bs_new(data_without_emulation_bytes, data_without_emulation_bytes_size, GF_BITSTREAM_READ);\n\t}\n\tif (!bs) goto exit;",
"\n\tif (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) goto exit;",
"\tvps_id = gf_hevc_read_vps_bs_internal(bs, hevc, remove_extensions);\n\tif (vps_id < 0) goto exit;",
"\tif (remove_extensions) {\n\t\tu8 *new_vps;\n\t\tu32 new_vps_size, emulation_bytes;\n\t\tu32 bit_pos = gf_bs_get_bit_offset(bs);\n\t\tGF_BitStream *w_bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\t\tgf_bs_seek(bs, 0);\n\t\tgf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );\n\t\tgf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );\n\t\tgf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );\n\t\tgf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );\n\t\tgf_bs_write_u16(w_bs, gf_bs_read_u16(bs) );\n\t\tbit_pos -= 48;\n\t\twhile (bit_pos) {\n\t\t\tu32 v = gf_bs_read_int(bs, 1);\n\t\t\tgf_bs_write_int(w_bs, v, 1);\n\t\t\tbit_pos--;\n\t\t}\n\t\t/*vps extension flag*/\n\t\tgf_bs_write_int(w_bs, 0, 1);\n\t\tnew_vps = NULL;\n\t\tgf_bs_get_content(w_bs, &new_vps, &new_vps_size);\n\t\tgf_bs_del(w_bs);",
"\t\temulation_bytes = gf_media_nalu_emulation_bytes_add_count(new_vps, new_vps_size);\n\t\tif (emulation_bytes + new_vps_size > *size) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"Buffer too small to rewrite VPS - skipping rewrite\\n\"));\n\t\t}\n\t\telse {\n\t\t\t*size = gf_media_nalu_add_emulation_bytes(new_vps, data, new_vps_size);\n\t\t}\n\t\tif (new_vps)\n\t\t\tgf_free(new_vps);\n\t}",
"exit:\n\tif (bs)\n\t\tgf_bs_del(bs);\n\tif (data_without_emulation_bytes) gf_free(data_without_emulation_bytes);\n\treturn vps_id;\n}",
"GF_EXPORT\ns32 gf_hevc_read_vps(u8 *data, u32 size, HEVCState *hevc)\n{\n\treturn gf_hevc_read_vps_ex(data, &size, hevc, GF_FALSE);\n}",
"GF_EXPORT\ns32 gf_hevc_read_vps_bs(GF_BitStream *bs, HEVCState *hevc)\n{\n\tif (!bs || !hevc) return -1;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\tif (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) return -1;\n\treturn gf_hevc_read_vps_bs_internal(bs, hevc, GF_FALSE);\n}",
"static void hevc_scaling_list_data(GF_BitStream *bs)\n{\n\tu32 i, sizeId, matrixId;\n\tfor (sizeId = 0; sizeId < 4; sizeId++) {\n\t\tfor (matrixId = 0; matrixId < 6; matrixId += (sizeId == 3) ? 3 : 1) {\n\t\t\tu32 idx = sizeId*100 + 10*matrixId;\n\t\t\tu32 scaling_list_pred_mode_flag_sizeId_matrixId = gf_bs_read_int_log_idx(bs, 1, \"scaling_list_pred_mode_flag_sizeId_matrixId\", idx);\n\t\t\tif (!scaling_list_pred_mode_flag_sizeId_matrixId) {\n\t\t\t\tgf_bs_read_ue_log_idx(bs, \"scaling_list_pred_matrix_id_delta\", idx);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//u32 nextCoef = 8;\n\t\t\t\tu32 coefNum = MIN(64, (1 << (4 + (sizeId << 1))));\n\t\t\t\tif (sizeId > 1) {\n\t\t\t\t\tgf_bs_read_se_log_idx(bs, \"scaling_list_dc_coef_minus8\", idx);\n\t\t\t\t}\n\t\t\t\tfor (i = 0; i < coefNum; i++) {\n\t\t\t\t\tgf_bs_read_se_log_idx2(bs, \"scaling_list_delta_coef\", idx, i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"\nstatic const struct {\n\tu32 w, h;\n} hevc_sar[17] =\n{\n\t{ 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 },\n\t{ 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },\n\t{ 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },\n\t{ 64, 33 }, { 160,99 }, { 4,3}, { 3,2}, { 2,1}\n};",
"static s32 gf_hevc_read_sps_bs_internal(GF_BitStream *bs, HEVCState *hevc, u8 layer_id, u32 *vui_flag_pos)\n{\n\ts32 vps_id, sps_id = -1;\n\tu32 i, nb_CTUs, depth;\n\tHEVC_SPS *sps;\n\tHEVC_VPS *vps;\n\tHEVC_ProfileTierLevel ptl;\n\tBool multiLayerExtSpsFlag;\n\tu8 sps_ext_or_max_sub_layers_minus1, max_sub_layers_minus1;",
"\tif (vui_flag_pos) *vui_flag_pos = 0;",
"\t//nalu header already parsed\n\tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n\tif ((vps_id<0) || (vps_id >= 16)) {\n\t\treturn -1;\n\t}\n\tmemset(&ptl, 0, sizeof(ptl));\n\tmax_sub_layers_minus1 = 0;\n\tsps_ext_or_max_sub_layers_minus1 = 0;\n\tif (layer_id == 0)\n\t\tmax_sub_layers_minus1 = gf_bs_read_int_log(bs, 3, \"max_sub_layers_minus1\");\n\telse\n\t\tsps_ext_or_max_sub_layers_minus1 = gf_bs_read_int_log(bs, 3, \"sps_ext_or_max_sub_layers_minus1\");\n\tmultiLayerExtSpsFlag = (layer_id != 0) && (sps_ext_or_max_sub_layers_minus1 == 7);\n\tif (!multiLayerExtSpsFlag) {\n\t\tgf_bs_read_int_log(bs, 1, \"temporal_id_nesting_flag\");\n\t\thevc_profile_tier_level(bs, 1, max_sub_layers_minus1, &ptl, 0);\n\t}",
"\tsps_id = gf_bs_read_ue_log(bs, \"sps_id\");\n\tif ((sps_id < 0) || (sps_id >= 16)) {\n\t\treturn -1;\n\t}",
"\tsps = &hevc->sps[sps_id];\n\tif (!sps->state) {\n\t\tsps->state = 1;\n\t\tsps->id = sps_id;\n\t\tsps->vps_id = vps_id;\n\t}\n\tsps->ptl = ptl;\n\tvps = &hevc->vps[vps_id];\n\tsps->max_sub_layers_minus1 = 0;\n\tsps->sps_ext_or_max_sub_layers_minus1 = 0;",
"\t/* default values */\n\tsps->colour_primaries = 2;\n\tsps->transfer_characteristic = 2;\n\tsps->matrix_coeffs = 2;",
"\t//sps_rep_format_idx = 0;\n\tif (multiLayerExtSpsFlag) {\n\t\tsps->update_rep_format_flag = gf_bs_read_int_log(bs, 1, \"update_rep_format_flag\");\n\t\tif (sps->update_rep_format_flag) {\n\t\t\tsps->rep_format_idx = gf_bs_read_int_log(bs, 8, \"rep_format_idx\");\n\t\t}\n\t\telse {\n\t\t\tsps->rep_format_idx = vps->rep_format_idx[layer_id];\n\t\t}\n\t\tsps->width = vps->rep_formats[sps->rep_format_idx].pic_width_luma_samples;\n\t\tsps->height = vps->rep_formats[sps->rep_format_idx].pic_height_luma_samples;\n\t\tsps->chroma_format_idc = vps->rep_formats[sps->rep_format_idx].chroma_format_idc;\n\t\tsps->bit_depth_luma = vps->rep_formats[sps->rep_format_idx].bit_depth_luma;\n\t\tsps->bit_depth_chroma = vps->rep_formats[sps->rep_format_idx].bit_depth_chroma;\n\t\tsps->separate_colour_plane_flag = vps->rep_formats[sps->rep_format_idx].separate_colour_plane_flag;",
"\t\t//TODO this is crude ...\n\t\tsps->ptl = vps->ext_ptl[0];\n\t}\n\telse {\n\t\tsps->chroma_format_idc = gf_bs_read_ue_log(bs, \"chroma_format_idc\");\n\t\tif (sps->chroma_format_idc == 3)\n\t\t\tsps->separate_colour_plane_flag = gf_bs_read_int_log(bs, 1, \"separate_colour_plane_flag\");\n\t\tsps->width = gf_bs_read_ue_log(bs, \"width\");\n\t\tsps->height = gf_bs_read_ue_log(bs, \"height\");\n\t\tif ((sps->cw_flag = gf_bs_read_int_log(bs, 1, \"conformance_window_flag\"))) {\n\t\t\tu32 SubWidthC, SubHeightC;",
"\t\t\tif (sps->chroma_format_idc == 1) {\n\t\t\t\tSubWidthC = SubHeightC = 2;\n\t\t\t}\n\t\t\telse if (sps->chroma_format_idc == 2) {\n\t\t\t\tSubWidthC = 2;\n\t\t\t\tSubHeightC = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSubWidthC = SubHeightC = 1;\n\t\t\t}",
"\t\t\tsps->cw_left = gf_bs_read_ue_log(bs, \"conformance_window_left\");\n\t\t\tsps->cw_right = gf_bs_read_ue_log(bs, \"conformance_window_right\");\n\t\t\tsps->cw_top = gf_bs_read_ue_log(bs, \"conformance_window_top\");\n\t\t\tsps->cw_bottom = gf_bs_read_ue_log(bs, \"conformance_window_bottom\");",
"\t\t\tsps->width -= SubWidthC * (sps->cw_left + sps->cw_right);\n\t\t\tsps->height -= SubHeightC * (sps->cw_top + sps->cw_bottom);\n\t\t}\n\t\tsps->bit_depth_luma = 8 + gf_bs_read_ue_log(bs, \"bit_depth_luma_minus8\");\n\t\tsps->bit_depth_chroma = 8 + gf_bs_read_ue_log(bs, \"bit_depth_chroma_minus8\");\n\t}",
"\tsps->log2_max_pic_order_cnt_lsb = 4 + gf_bs_read_ue_log(bs, \"log2_max_pic_order_cnt_lsb_minus4\");",
"\tif (!multiLayerExtSpsFlag) {\n\t\tsps->sub_layer_ordering_info_present_flag = gf_bs_read_int_log(bs, 1, \"sub_layer_ordering_info_present_flag\");\n\t\tfor (i = sps->sub_layer_ordering_info_present_flag ? 0 : sps->max_sub_layers_minus1; i <= sps->max_sub_layers_minus1; i++) {\n\t\t\tgf_bs_read_ue_log_idx(bs, \"max_dec_pic_buffering\", i);\n\t\t\tgf_bs_read_ue_log_idx(bs, \"num_reorder_pics\", i);\n\t\t\tgf_bs_read_ue_log_idx(bs, \"max_latency_increase\", i);\n\t\t}\n\t}",
"\tsps->log2_min_luma_coding_block_size = 3 + gf_bs_read_ue_log(bs, \"log2_min_luma_coding_block_size_minus3\");\n\tsps->log2_diff_max_min_luma_coding_block_size = gf_bs_read_ue_log(bs, \"log2_diff_max_min_luma_coding_block_size\");\n\tsps->max_CU_width = (1 << (sps->log2_min_luma_coding_block_size + sps->log2_diff_max_min_luma_coding_block_size));\n\tsps->max_CU_height = (1 << (sps->log2_min_luma_coding_block_size + sps->log2_diff_max_min_luma_coding_block_size));",
"\tsps->log2_min_transform_block_size = 2 + gf_bs_read_ue_log(bs, \"log2_min_transform_block_size_minus2\");\n\tsps->log2_max_transform_block_size = sps->log2_min_transform_block_size + gf_bs_read_ue_log(bs, \"log2_max_transform_block_size\");",
"\tdepth = 0;\n\tsps->max_transform_hierarchy_depth_inter = gf_bs_read_ue_log(bs, \"max_transform_hierarchy_depth_inter\");\n\tsps->max_transform_hierarchy_depth_intra = gf_bs_read_ue_log(bs, \"max_transform_hierarchy_depth_intra\");\n\twhile ((u32)(sps->max_CU_width >> sps->log2_diff_max_min_luma_coding_block_size) > (u32)(1 << (sps->log2_min_transform_block_size + depth)))\n\t{\n\t\tdepth++;\n\t}\n\tsps->max_CU_depth = sps->log2_diff_max_min_luma_coding_block_size + depth;",
"\tnb_CTUs = ((sps->width + sps->max_CU_width - 1) / sps->max_CU_width) * ((sps->height + sps->max_CU_height - 1) / sps->max_CU_height);\n\tsps->bitsSliceSegmentAddress = 0;\n\twhile (nb_CTUs > (u32)(1 << sps->bitsSliceSegmentAddress)) {\n\t\tsps->bitsSliceSegmentAddress++;\n\t}",
"\tsps->scaling_list_enable_flag = gf_bs_read_int_log(bs, 1, \"scaling_list_enable_flag\");\n\tif (sps->scaling_list_enable_flag) {\n\t\tsps->infer_scaling_list_flag = 0;\n\t\tsps->scaling_list_ref_layer_id = 0;\n\t\tif (multiLayerExtSpsFlag) {\n\t\t\tsps->infer_scaling_list_flag = gf_bs_read_int_log(bs, 1, \"infer_scaling_list_flag\");\n\t\t}\n\t\tif (sps->infer_scaling_list_flag) {\n\t\t\tsps->scaling_list_ref_layer_id = gf_bs_read_int_log(bs, 6, \"scaling_list_ref_layer_id\");\n\t\t}\n\t\telse {\n\t\t\tsps->scaling_list_data_present_flag = gf_bs_read_int_log(bs, 1, \"scaling_list_data_present_flag\");\n\t\t\tif (sps->scaling_list_data_present_flag) {\n\t\t\t\thevc_scaling_list_data(bs);\n\t\t\t}\n\t\t}\n\t}\n\tsps->asymmetric_motion_partitions_enabled_flag = gf_bs_read_int_log(bs, 1, \"asymmetric_motion_partitions_enabled_flag\");\n\tsps->sample_adaptive_offset_enabled_flag = gf_bs_read_int_log(bs, 1, \"sample_adaptive_offset_enabled_flag\");\n\tif ( (sps->pcm_enabled_flag = gf_bs_read_int_log(bs, 1, \"pcm_enabled_flag\")) ) {\n\t\tsps->pcm_sample_bit_depth_luma_minus1 = gf_bs_read_int_log(bs, 4, \"pcm_sample_bit_depth_luma_minus1\");\n\t\tsps->pcm_sample_bit_depth_chroma_minus1 = gf_bs_read_int_log(bs, 4, \"pcm_sample_bit_depth_chroma_minus1\");\n\t\tsps->log2_min_pcm_luma_coding_block_size_minus3 = gf_bs_read_ue_log(bs, \"log2_min_pcm_luma_coding_block_size_minus3\");\n\t\tsps->log2_diff_max_min_pcm_luma_coding_block_size = gf_bs_read_ue_log(bs, \"log2_diff_max_min_pcm_luma_coding_block_size\");\n\t\tsps->pcm_loop_filter_disable_flag = gf_bs_read_int_log(bs, 1, \"pcm_loop_filter_disable_flag\");\n\t}\n\tsps->num_short_term_ref_pic_sets = gf_bs_read_ue_log(bs, \"num_short_term_ref_pic_sets\");\n\tif (sps->num_short_term_ref_pic_sets > 64) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Invalid number of short term reference picture sets %d\\n\", sps->num_short_term_ref_pic_sets));\n\t\treturn -1;\n\t}",
"\tfor (i = 0; i < sps->num_short_term_ref_pic_sets; i++) {\n\t\tBool ret = hevc_parse_short_term_ref_pic_set(bs, sps, i);\n\t\t/*cannot parse short_term_ref_pic_set, skip VUI parsing*/\n\t\tif (!ret) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] Invalid short_term_ref_pic_set\\n\"));\n\t\t\treturn -1;\n\t\t}\n\t}\n\tsps->long_term_ref_pics_present_flag = gf_bs_read_int_log(bs, 1, \"long_term_ref_pics_present_flag\");\n\tif (sps->long_term_ref_pics_present_flag) {\n\t\tsps->num_long_term_ref_pic_sps = gf_bs_read_ue_log(bs, \"num_long_term_ref_pic_sps\");\n\t\tfor (i = 0; i < sps->num_long_term_ref_pic_sps; i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, sps->log2_max_pic_order_cnt_lsb, \"lt_ref_pic_poc_lsb_sps\", i);\n\t\t\tgf_bs_read_int_log_idx(bs, 1, \"used_by_curr_pic_lt_sps_flag\", i);\n\t\t}\n\t}\n\tsps->temporal_mvp_enable_flag = gf_bs_read_int_log(bs, 1, \"temporal_mvp_enable_flag\");\n\tsps->strong_intra_smoothing_enable_flag = gf_bs_read_int_log(bs, 1, \"strong_intra_smoothing_enable_flag\");",
"\tif (vui_flag_pos)\n\t\t*vui_flag_pos = (u32)gf_bs_get_bit_offset(bs);",
"\tif ((sps->vui_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"vui_parameters_present_flag\")) ) {\n\t\tsps->aspect_ratio_info_present_flag = gf_bs_read_int_log(bs, 1, \"aspect_ratio_info_present_flag\");\n\t\tif (sps->aspect_ratio_info_present_flag) {\n\t\t\tsps->sar_idc = gf_bs_read_int_log(bs, 8, \"aspect_ratio_idc\");\n\t\t\tif (sps->sar_idc == 255) {\n\t\t\t\tsps->sar_width = gf_bs_read_int_log(bs, 16, \"aspect_ratio_width\");\n\t\t\t\tsps->sar_height = gf_bs_read_int_log(bs, 16, \"aspect_ratio_height\");\n\t\t\t}\n\t\t\telse if (sps->sar_idc < 17) {\n\t\t\t\tsps->sar_width = hevc_sar[sps->sar_idc].w;\n\t\t\t\tsps->sar_height = hevc_sar[sps->sar_idc].h;\n\t\t\t}\n\t\t}",
"\t\tif ((sps->overscan_info_present = gf_bs_read_int_log(bs, 1, \"overscan_info_present\")))\n\t\t\tsps->overscan_appropriate = gf_bs_read_int_log(bs, 1, \"overscan_appropriate\");",
"\t\tsps->video_signal_type_present_flag = gf_bs_read_int_log(bs, 1, \"video_signal_type_present_flag\");\n\t\tif (sps->video_signal_type_present_flag) {\n\t\t\tsps->video_format = gf_bs_read_int_log(bs, 3, \"video_format\");\n\t\t\tsps->video_full_range_flag = gf_bs_read_int_log(bs, 1, \"video_full_range_flag\");\n\t\t\tif ((sps->colour_description_present_flag = gf_bs_read_int_log(bs, 1, \"colour_description_present_flag\"))) {\n\t\t\t\tsps->colour_primaries = gf_bs_read_int_log(bs, 8, \"colour_primaries\");\n\t\t\t\tsps->transfer_characteristic = gf_bs_read_int_log(bs, 8, \"transfer_characteristic\");\n\t\t\t\tsps->matrix_coeffs = gf_bs_read_int_log(bs, 8, \"matrix_coefficients\");\n\t\t\t}\n\t\t}",
"\t\tif ((sps->chroma_loc_info_present_flag = gf_bs_read_int_log(bs, 1, \"chroma_loc_info_present_flag\"))) {\n\t\t\tsps->chroma_sample_loc_type_top_field = gf_bs_read_ue_log(bs, \"chroma_sample_loc_type_top_field\");\n\t\t\tsps->chroma_sample_loc_type_bottom_field = gf_bs_read_ue_log(bs, \"chroma_sample_loc_type_bottom_field\");\n\t\t}",
"\t\tsps->neutra_chroma_indication_flag = gf_bs_read_int_log(bs, 1, \"neutra_chroma_indication_flag\");\n\t\tsps->field_seq_flag = gf_bs_read_int_log(bs, 1, \"field_seq_flag\");\n\t\tsps->frame_field_info_present_flag = gf_bs_read_int_log(bs, 1, \"frame_field_info_present_flag\");",
"\t\tif ((sps->default_display_window_flag = gf_bs_read_int_log(bs, 1, \"default_display_window_flag\"))) {\n\t\t\tsps->left_offset = gf_bs_read_ue_log(bs, \"display_window_left_offset\");\n\t\t\tsps->right_offset = gf_bs_read_ue_log(bs, \"display_window_right_offset\");\n\t\t\tsps->top_offset = gf_bs_read_ue_log(bs, \"display_window_top_offset\");\n\t\t\tsps->bottom_offset = gf_bs_read_ue_log(bs, \"display_window_bottom_offset\");\n\t\t}",
"\t\tsps->has_timing_info = gf_bs_read_int_log(bs, 1, \"has_timing_info\");\n\t\tif (sps->has_timing_info) {\n\t\t\tsps->num_units_in_tick = gf_bs_read_int_log(bs, 32, \"num_units_in_tick\");\n\t\t\tsps->time_scale = gf_bs_read_int_log(bs, 32, \"time_scale\");\n\t\t\tsps->poc_proportional_to_timing_flag = gf_bs_read_int_log(bs, 1, \"poc_proportional_to_timing_flag\");\n\t\t\tif (sps->poc_proportional_to_timing_flag)\n\t\t\t\tsps->num_ticks_poc_diff_one_minus1 = gf_bs_read_ue_log(bs, \"num_ticks_poc_diff_one_minus1\");\n\t\t\tif ((sps->hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, \"hrd_parameters_present_flag\"))) {\n\t\t\t\t//\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CODING, (\"[HEVC] HRD param parsing not implemented\\n\"));\n\t\t\t\treturn sps_id;\n\t\t\t}\n\t\t}",
"\t\tif (gf_bs_read_int_log(bs, 1, \"bitstream_restriction_flag\")) {\n\t\t\tgf_bs_read_int_log(bs, 1, \"tiles_fixed_structure_flag\");\n\t\t\tgf_bs_read_int_log(bs, 1, \"motion_vectors_over_pic_boundaries_flag\");\n\t\t\tgf_bs_read_int_log(bs, 1, \"restricted_ref_pic_lists_flag\");\n\t\t\tgf_bs_read_ue_log(bs, \"min_spatial_segmentation_idc\");\n\t\t\tgf_bs_read_ue_log(bs, \"max_bytes_per_pic_denom\");\n\t\t\tgf_bs_read_ue_log(bs, \"max_bits_per_min_cu_denom\");\n\t\t\tgf_bs_read_ue_log(bs, \"log2_max_mv_length_horizontal\");\n\t\t\tgf_bs_read_ue_log(bs, \"log2_max_mv_length_vertical\");\n\t\t}\n\t}",
"\tif (gf_bs_read_int_log(bs, 1, \"sps_extension_flag\")) {\n#if 0\n\t\twhile (gf_bs_available(bs)) {\n\t\t\t/*sps_extension_data_flag */ gf_bs_read_int(bs, 1);\n\t\t}\n#endif",
"\t}",
"\treturn sps_id;\n}",
"GF_EXPORT\ns32 gf_hevc_read_sps_ex(char *data, u32 size, HEVCState *hevc, u32 *vui_flag_pos)\n{\n\tGF_BitStream *bs;\n\ts32 sps_id = -1;\n\tu8 layer_id;",
"\tif (vui_flag_pos) *vui_flag_pos = 0;",
"\tbs = gf_bs_new(data, size, GF_BITSTREAM_READ);\n\tif (!bs) goto exit;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tif (!hevc_parse_nal_header(bs, NULL, NULL, &layer_id)) goto exit;\n\tsps_id = gf_hevc_read_sps_bs_internal(bs, hevc, layer_id, vui_flag_pos);",
"exit:\n\tif (bs) gf_bs_del(bs);\n\treturn sps_id;\n}",
"GF_EXPORT\ns32 gf_hevc_read_sps(u8 *data, u32 size, HEVCState *hevc)\n{\n\treturn gf_hevc_read_sps_ex(data, size, hevc, NULL);\n}",
"GF_EXPORT\ns32 gf_hevc_read_sps_bs(GF_BitStream *bs, HEVCState *hevc)\n{\n\tu8 layer_id;\n\tif (!bs || !hevc) return -1;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\tif (!hevc_parse_nal_header(bs, NULL, NULL, &layer_id)) return -1;\n\treturn gf_hevc_read_sps_bs_internal(bs, hevc, layer_id, NULL);\n}",
"\nstatic s32 gf_hevc_read_pps_bs_internal(GF_BitStream *bs, HEVCState *hevc)\n{\n\tu32 i;\n\ts32 pps_id;\n\tHEVC_PPS *pps;",
"\t//NAL header already read\n\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");",
"\tif ((pps_id < 0) || (pps_id >= 64)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] wrong PPS ID %d in PPS\\n\", pps_id));\n\t\treturn -1;\n\t}\n\tpps = &hevc->pps[pps_id];",
"\tif (!pps->state) {\n\t\tpps->id = pps_id;\n\t\tpps->state = 1;\n\t}\n\tpps->sps_id = gf_bs_read_ue_log(bs, \"sps_id\");\n\tif (((s32)pps->sps_id<0) || (pps->sps_id >= 16)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] wrong SPS ID %d in PPS\\n\", pps->sps_id));\n\t\tpps->sps_id=0;\n\t\treturn -1;\n\t}\n\thevc->sps_active_idx = pps->sps_id; /*set active sps*/\n\tpps->dependent_slice_segments_enabled_flag = gf_bs_read_int_log(bs, 1, \"dependent_slice_segments_enabled_flag\");",
"\tpps->output_flag_present_flag = gf_bs_read_int_log(bs, 1, \"output_flag_present_flag\");\n\tpps->num_extra_slice_header_bits = gf_bs_read_int_log(bs, 3, \"num_extra_slice_header_bits\");\n\tpps->sign_data_hiding_flag = gf_bs_read_int_log(bs, 1, \"sign_data_hiding_flag\");\n\tpps->cabac_init_present_flag = gf_bs_read_int_log(bs, 1, \"cabac_init_present_flag\");\n\tpps->num_ref_idx_l0_default_active = 1 + gf_bs_read_ue_log(bs, \"num_ref_idx_l0_default_active\");\n\tpps->num_ref_idx_l1_default_active = 1 + gf_bs_read_ue_log(bs, \"num_ref_idx_l1_default_active\");\n\tpps->pic_init_qp_minus26 = gf_bs_read_se_log(bs, \"pic_init_qp_minus26\");\n\tpps->constrained_intra_pred_flag = gf_bs_read_int_log(bs, 1, \"constrained_intra_pred_flag\");\n\tpps->transform_skip_enabled_flag = gf_bs_read_int_log(bs, 1, \"transform_skip_enabled_flag\");\n\tif ((pps->cu_qp_delta_enabled_flag = gf_bs_read_int_log(bs, 1, \"cu_qp_delta_enabled_flag\")))\n\t\tpps->diff_cu_qp_delta_depth = gf_bs_read_ue_log(bs, \"diff_cu_qp_delta_depth\");",
"\tpps->pic_cb_qp_offset = gf_bs_read_se_log(bs, \"pic_cb_qp_offset\");\n\tpps->pic_cr_qp_offset = gf_bs_read_se_log(bs, \"pic_cr_qp_offset\");\n\tpps->slice_chroma_qp_offsets_present_flag = gf_bs_read_int_log(bs, 1, \"slice_chroma_qp_offsets_present_flag\");\n\tpps->weighted_pred_flag = gf_bs_read_int_log(bs, 1, \"weighted_pred_flag\");\n\tpps->weighted_bipred_flag = gf_bs_read_int_log(bs, 1, \"weighted_bipred_flag\");\n\tpps->transquant_bypass_enable_flag = gf_bs_read_int_log(bs, 1, \"transquant_bypass_enable_flag\");\n\tpps->tiles_enabled_flag = gf_bs_read_int_log(bs, 1, \"tiles_enabled_flag\");\n\tpps->entropy_coding_sync_enabled_flag = gf_bs_read_int_log(bs, 1, \"entropy_coding_sync_enabled_flag\");\n\tif (pps->tiles_enabled_flag) {\n\t\tpps->num_tile_columns = 1 + gf_bs_read_ue_log(bs, \"num_tile_columns_minus1\");\n\t\tpps->num_tile_rows = 1 + gf_bs_read_ue_log(bs, \"num_tile_rows_minus1\");\n\t\tpps->uniform_spacing_flag = gf_bs_read_int_log(bs, 1, \"uniform_spacing_flag\");\n\t\tif (!pps->uniform_spacing_flag) {\n\t\t\tfor (i = 0; i < pps->num_tile_columns - 1; i++) {\n\t\t\t\tpps->column_width[i] = 1 + gf_bs_read_ue_log_idx(bs, \"column_width_minus1\", i);\n\t\t\t}\n\t\t\tfor (i = 0; i < pps->num_tile_rows - 1; i++) {\n\t\t\t\tpps->row_height[i] = 1 + gf_bs_read_ue_log_idx(bs, \"row_height_minus1\", i);\n\t\t\t}\n\t\t}\n\t\tpps->loop_filter_across_tiles_enabled_flag = gf_bs_read_int_log(bs, 1, \"loop_filter_across_tiles_enabled_flag\");\n\t}\n\tpps->loop_filter_across_slices_enabled_flag = gf_bs_read_int_log(bs, 1, \"loop_filter_across_slices_enabled_flag\");\n\tif ((pps->deblocking_filter_control_present_flag = gf_bs_read_int_log(bs, 1, \"deblocking_filter_control_present_flag\"))) {\n\t\tpps->deblocking_filter_override_enabled_flag = gf_bs_read_int_log(bs, 1, \"deblocking_filter_override_enabled_flag\");\n\t\tif (! (pps->pic_disable_deblocking_filter_flag = gf_bs_read_int_log(bs, 1, \"pic_disable_deblocking_filter_flag\"))) {\n\t\t\tpps->beta_offset_div2 = gf_bs_read_se_log(bs, \"beta_offset_div2\");\n\t\t\tpps->tc_offset_div2 = gf_bs_read_se_log(bs, \"tc_offset_div2\");\n\t\t}\n\t}\n\tif ((pps->pic_scaling_list_data_present_flag = gf_bs_read_int_log(bs, 1, \"pic_scaling_list_data_present_flag\"))) {\n\t\thevc_scaling_list_data(bs);\n\t}\n\tpps->lists_modification_present_flag = gf_bs_read_int_log(bs, 1, \"lists_modification_present_flag\");\n\tpps->log2_parallel_merge_level_minus2 = gf_bs_read_ue_log(bs, \"log2_parallel_merge_level_minus2\");\n\tpps->slice_segment_header_extension_present_flag = gf_bs_read_int_log(bs, 1, \"slice_segment_header_extension_present_flag\");\n\tif (gf_bs_read_int_log(bs, 1, \"pps_extension_flag\")) {\n#if 0\n\t\twhile (gf_bs_available(bs)) {\n\t\t\t/*pps_extension_data_flag */ gf_bs_read_int(bs, 1);\n\t\t}\n#endif",
"\t}\n\treturn pps_id;\n}",
"\nGF_EXPORT\ns32 gf_hevc_read_pps(u8 *data, u32 size, HEVCState *hevc)\n{\n\tGF_BitStream *bs;\n\ts32 pps_id = -1;",
"\tbs = gf_bs_new(data, size, GF_BITSTREAM_READ);\n\tif (!bs) goto exit;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tif (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) goto exit;",
"\tpps_id = gf_hevc_read_pps_bs_internal(bs, hevc);",
"exit:\n\tif (bs) gf_bs_del(bs);\n\treturn pps_id;\n}",
"GF_EXPORT\ns32 gf_hevc_read_pps_bs(GF_BitStream *bs, HEVCState *hevc)\n{\n\tif (!bs || !hevc) return -1;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);\n\tif (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) return -1;\n\treturn gf_hevc_read_pps_bs_internal(bs, hevc);\n}",
"GF_EXPORT\ns32 gf_hevc_parse_nalu_bs(GF_BitStream *bs, HEVCState *hevc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tBool is_slice = GF_FALSE;\n\ts32 ret = -1;\n\tHEVCSliceInfo n_state;",
"\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tmemcpy(&n_state, &hevc->s_info, sizeof(HEVCSliceInfo));\n\tif (!hevc_parse_nal_header(bs, nal_unit_type, temporal_id, layer_id)) return -1;",
"\tn_state.nal_unit_type = *nal_unit_type;",
"\tswitch (n_state.nal_unit_type) {\n\tcase GF_HEVC_NALU_ACCESS_UNIT:\n\tcase GF_HEVC_NALU_END_OF_SEQ:\n\tcase GF_HEVC_NALU_END_OF_STREAM:\n\t\tret = 1;\n\t\tbreak;",
"\t\t/*slice_segment_layer_rbsp*/\n\tcase GF_HEVC_NALU_SLICE_TRAIL_N:\n\tcase GF_HEVC_NALU_SLICE_TRAIL_R:\n\tcase GF_HEVC_NALU_SLICE_TSA_N:\n\tcase GF_HEVC_NALU_SLICE_TSA_R:\n\tcase GF_HEVC_NALU_SLICE_STSA_N:\n\tcase GF_HEVC_NALU_SLICE_STSA_R:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\tcase GF_HEVC_NALU_SLICE_CRA:\n\tcase GF_HEVC_NALU_SLICE_RADL_N:\n\tcase GF_HEVC_NALU_SLICE_RADL_R:\n\tcase GF_HEVC_NALU_SLICE_RASL_N:\n\tcase GF_HEVC_NALU_SLICE_RASL_R:\n\t\tis_slice = GF_TRUE;\n\t\t/* slice - read the info and compare.*/\n\t\tret = hevc_parse_slice_segment(bs, hevc, &n_state);\n\t\tif (ret < 0) return ret;",
"\t\thevc_compute_poc(&n_state);",
"\t\tret = 0;",
"\t\tif (hevc->s_info.poc != n_state.poc) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (n_state.first_slice_segment_in_pic_flag) {\n\t\t\tif (!(*layer_id) || (n_state.prev_layer_id_plus1 && ((*layer_id) <= n_state.prev_layer_id_plus1 - 1))) {\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase GF_HEVC_NALU_SEQ_PARAM:\n\t\thevc->last_parsed_sps_id = gf_hevc_read_sps_bs_internal(bs, hevc, *layer_id, NULL);\n\t\tret = (hevc->last_parsed_sps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tcase GF_HEVC_NALU_PIC_PARAM:\n\t\thevc->last_parsed_pps_id = gf_hevc_read_pps_bs_internal(bs, hevc);\n\t\tret = (hevc->last_parsed_pps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tcase GF_HEVC_NALU_VID_PARAM:\n\t\thevc->last_parsed_vps_id = gf_hevc_read_vps_bs_internal(bs, hevc, GF_FALSE);\n\t\tret = (hevc->last_parsed_vps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tdefault:\n\t\tret = 0;\n\t\tbreak;\n\t}",
"\t/* save _prev values */\n\tif ((ret>0) && hevc->s_info.sps) {\n\t\tn_state.frame_num_offset_prev = hevc->s_info.frame_num_offset;\n\t\tn_state.frame_num_prev = hevc->s_info.frame_num;",
"\t\tn_state.poc_lsb_prev = hevc->s_info.poc_lsb;\n\t\tn_state.poc_msb_prev = hevc->s_info.poc_msb;\n\t\tif (is_slice)\n\t\t\tn_state.prev_layer_id_plus1 = *layer_id + 1;\n\t}\n\tif (is_slice) hevc_compute_poc(&n_state);\n\tmemcpy(&hevc->s_info, &n_state, sizeof(HEVCSliceInfo));",
"\treturn ret;\n}",
"GF_EXPORT\ns32 gf_hevc_parse_nalu(u8 *data, u32 size, HEVCState *hevc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tGF_BitStream *bs = NULL;\n\ts32 ret = -1;",
"\tif (!hevc) {\n\t\tif (nal_unit_type) (*nal_unit_type) = (data[0] & 0x7E) >> 1;\n\t\tif (layer_id) {\n\t\t\tu8 id = data[0] & 1;\n\t\t\tid <<= 5;\n\t\t\tid |= (data[1] >> 3) & 0x1F;\n\t\t\t(*layer_id) = id;\n\t\t}\n\t\tif (temporal_id) (*temporal_id) = (data[1] & 0x7);\n\t\treturn -1;\n\t}",
"\tbs = gf_bs_new(data, size, GF_BITSTREAM_READ);\n\tif (!bs) return -1;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tret = gf_hevc_parse_nalu_bs(bs, hevc, nal_unit_type, temporal_id, layer_id);",
"\tgf_bs_del(bs);\n\treturn ret;\n}",
"GF_EXPORT\nGF_Err gf_hevc_change_vui(GF_HEVCConfig *hvcc, GF_VUIInfo *vui_info)\n{\n\tGF_BitStream *orig, *mod;\n\tHEVCState hevc;\n\tu32 i, bit_offset, flag;\n\ts32 idx;\n\tGF_NALUFFParamArray *spss;\n\tGF_NALUFFParam *slc;\n\torig = NULL;",
"\tmemset(&hevc, 0, sizeof(HEVCState));\n\thevc.sps_active_idx = -1;",
"\ti = 0;\n\tspss = NULL;\n\twhile ((spss = (GF_NALUFFParamArray *)gf_list_enum(hvcc->param_array, &i))) {\n\t\tif (spss->type == GF_HEVC_NALU_SEQ_PARAM)\n\t\t\tbreak;\n\t\tspss = NULL;\n\t}\n\tif (!spss) return GF_NON_COMPLIANT_BITSTREAM;",
"\ti = 0;\n\twhile ((slc = (GF_NALUFFParam *)gf_list_enum(spss->nalus, &i))) {\n\t\tu8 *no_emulation_buf;\n\t\tu32 no_emulation_buf_size, emulation_bytes;",
"\t\t/*SPS may still contains emulation bytes*/\n\t\tno_emulation_buf = gf_malloc((slc->size) * sizeof(char));\n\t\tno_emulation_buf_size = gf_media_nalu_remove_emulation_bytes(slc->data, no_emulation_buf, slc->size);",
"\t\tidx = gf_hevc_read_sps_ex(no_emulation_buf, no_emulation_buf_size, &hevc, &bit_offset);\n\t\tif (idx < 0) {\n\t\t\tif (orig)\n\t\t\t\tgf_bs_del(orig);\n\t\t\tgf_free(no_emulation_buf);\n\t\t\tcontinue;\n\t\t}",
"\t\torig = gf_bs_new(no_emulation_buf, no_emulation_buf_size, GF_BITSTREAM_READ);\n\t\tmod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);",
"\t\t/*copy over till vui flag*/\n\t\tassert(bit_offset >= 0);\n\t\twhile (bit_offset) {\n\t\t\tflag = gf_bs_read_int(orig, 1);\n\t\t\tgf_bs_write_int(mod, flag, 1);\n\t\t\tbit_offset--;\n\t\t}",
"\t\tavc_hevc_rewrite_vui(vui_info, orig, mod);",
"\t\t/*finally copy over remaining*/\n\t\twhile (gf_bs_bits_available(orig)) {\n\t\t\tflag = gf_bs_read_int(orig, 1);\n\t\t\tgf_bs_write_int(mod, flag, 1);\n\t\t}\n\t\tgf_bs_del(orig);\n\t\torig = NULL;\n\t\tgf_free(no_emulation_buf);",
"\t\t/*set anti-emulation*/\n\t\tgf_bs_get_content(mod, &no_emulation_buf, &no_emulation_buf_size);\n\t\temulation_bytes = gf_media_nalu_emulation_bytes_add_count(no_emulation_buf, no_emulation_buf_size);\n\t\tif (no_emulation_buf_size + emulation_bytes > slc->size)\n\t\t\tslc->data = (char*)gf_realloc(slc->data, no_emulation_buf_size + emulation_bytes);",
"\t\tslc->size = gf_media_nalu_add_emulation_bytes(no_emulation_buf, slc->data, no_emulation_buf_size);",
"\t\tgf_bs_del(mod);\n\t\tgf_free(no_emulation_buf);\n\t}\n\treturn GF_OK;\n}",
"\nGF_EXPORT\nGF_Err gf_hevc_change_par(GF_HEVCConfig *hvcc, s32 ar_n, s32 ar_d)\n{\n\tGF_VUIInfo vuii;\n\tmemset(&vuii, 0, sizeof(GF_VUIInfo));\n\tvuii.ar_num = ar_n;\n\tvuii.ar_den = ar_d;\n\tvuii.fullrange = -1;\n\tvuii.video_format = -1;\n\tvuii.color_prim = -1;\n\tvuii.color_tfc = -1;\n\tvuii.color_matrix = -1;\n\treturn gf_hevc_change_vui(hvcc, &vuii);\n}",
"GF_EXPORT\nGF_Err gf_hevc_change_color(GF_HEVCConfig *hvcc, s32 fullrange, s32 vidformat, s32 colorprim, s32 transfer, s32 colmatrix)\n{\n\tGF_VUIInfo vuii;\n\tmemset(&vuii, 0, sizeof(GF_VUIInfo));\n\tvuii.ar_num = -1;\n\tvuii.ar_den = -1;\n\tvuii.fullrange = fullrange;\n\tvuii.video_format = vidformat;\n\tvuii.color_prim = colorprim;\n\tvuii.color_tfc = transfer;\n\tvuii.color_matrix = colmatrix;\n\treturn gf_hevc_change_vui(hvcc, &vuii);\n}",
"\nGF_EXPORT\nGF_Err gf_hevc_get_sps_info_with_state(HEVCState *hevc, u8 *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)\n{\n\ts32 idx;\n\tidx = gf_hevc_read_sps(sps_data, sps_size, hevc);\n\tif (idx < 0) {\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t}\n\tif (sps_id) *sps_id = idx;",
"\tif (width) *width = hevc->sps[idx].width;\n\tif (height) *height = hevc->sps[idx].height;\n\tif (par_n) *par_n = hevc->sps[idx].aspect_ratio_info_present_flag ? hevc->sps[idx].sar_width : (u32)-1;\n\tif (par_d) *par_d = hevc->sps[idx].aspect_ratio_info_present_flag ? hevc->sps[idx].sar_height : (u32)-1;\n\treturn GF_OK;\n}",
"GF_EXPORT\nGF_Err gf_hevc_get_sps_info(u8 *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)\n{\n\tHEVCState hevc;\n\tmemset(&hevc, 0, sizeof(HEVCState));\n\thevc.sps_active_idx = -1;\n\treturn gf_hevc_get_sps_info_with_state(&hevc, sps_data, sps_size, sps_id, width, height, par_n, par_d);\n}",
"\n#endif //GPAC_DISABLE_HEVC",
"static u32 AC3_FindSyncCode(u8 *buf, u32 buflen)\n{\n\tu32 end = buflen - 6;\n\tu32 offset = 0;\n\twhile (offset <= end) {\n\t\tif (buf[offset] == 0x0b && buf[offset + 1] == 0x77) {\n\t\t\treturn offset;\n\t\t}\n\t\toffset++;\n\t}\n\treturn buflen;\n}",
"\nstatic Bool AC3_FindSyncCodeBS(GF_BitStream *bs)\n{\n\tu8 b1;\n\tu64 pos = gf_bs_get_position(bs);\n\tu64 end = gf_bs_get_size(bs);",
"\tpos += 1;\n\tb1 = gf_bs_read_u8(bs);\n\twhile (pos + 1 <= end) {\n\t\tu8 b2 = gf_bs_read_u8(bs);\n\t\tif ((b1 == 0x0b) && (b2 == 0x77)) {\n\t\t\tgf_bs_seek(bs, pos - 1);\n\t\t\treturn GF_TRUE;\n\t\t}\n\t\tpos++;\n\t\tb1 = b2;\n\t}\n\treturn GF_FALSE;\n}",
"static const u32 ac3_sizecod_to_bitrate[] = {\n\t32000, 40000, 48000, 56000, 64000, 80000, 96000,\n\t112000, 128000, 160000, 192000, 224000, 256000,\n\t320000, 384000, 448000, 512000, 576000, 640000\n};",
"static const u32 ac3_sizecod2_to_framesize[] = {\n\t96, 120, 144, 168, 192, 240, 288, 336, 384, 480, 576, 672,\n\t768, 960, 1152, 1344, 1536, 1728, 1920\n};",
"static const u32 ac3_sizecod1_to_framesize[] = {\n\t69, 87, 104, 121, 139, 174, 208, 243, 278, 348, 417, 487,\n\t557, 696, 835, 975, 1114, 1253, 1393\n};\nstatic const u32 ac3_sizecod0_to_framesize[] = {\n\t64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448,\n\t512, 640, 768, 896, 1024, 1152, 1280\n};",
"static const u32 ac3_mod_to_chans[] = {\n\t2, 1, 2, 3, 3, 4, 4, 5\n};",
"GF_EXPORT\nu32 gf_ac3_get_channels(u32 acmod)\n{\n\tu32 nb_ch;\n\tnb_ch = ac3_mod_to_chans[acmod];\n\treturn nb_ch;\n}",
"GF_EXPORT\nu32 gf_ac3_get_bitrate(u32 brcode)\n{\n\treturn ac3_sizecod_to_bitrate[brcode];\n}",
"Bool gf_ac3_parser(u8 *buf, u32 buflen, u32 *pos, GF_AC3Config *hdr, Bool full_parse)\n{\n\tGF_BitStream *bs;\n\tBool ret;",
"\tif (buflen < 6) return GF_FALSE;\n\t(*pos) = AC3_FindSyncCode(buf, buflen);\n\tif (*pos >= buflen) return GF_FALSE;",
"\tbs = gf_bs_new((const char*)(buf + *pos), buflen, GF_BITSTREAM_READ);\n\tret = gf_ac3_parser_bs(bs, hdr, full_parse);\n\tgf_bs_del(bs);",
"\treturn ret;\n}",
"GF_EXPORT\nBool gf_ac3_parser_bs(GF_BitStream *bs, GF_AC3Config *hdr, Bool full_parse)\n{\n\tu32 fscod, frmsizecod, bsid, ac3_mod, freq, framesize, bsmod, syncword;\n\tu64 pos;\n\tif (!hdr || (gf_bs_available(bs) < 6)) return GF_FALSE;\n\tif (!AC3_FindSyncCodeBS(bs)) return GF_FALSE;",
"\tpos = gf_bs_get_position(bs);",
"\tsyncword = gf_bs_read_u16(bs);\n\tif (syncword != 0x0B77) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[AC3] Wrong sync word detected (0x%X - expecting 0x0B77).\\n\", syncword));\n\t\treturn GF_FALSE;\n\t}\n\tgf_bs_read_int_log(bs, 16, \"crc1\");\n\tfscod = gf_bs_read_int_log(bs, 2, \"fscod\");\n\tfrmsizecod = gf_bs_read_int_log(bs, 6, \"frmsizecod\");\n\tbsid = gf_bs_read_int_log(bs, 5, \"bsid\");\n\tbsmod = gf_bs_read_int_log(bs, 3, \"bsmod\");\n\tac3_mod = gf_bs_read_int_log(bs, 3, \"ac3_mod\");\n\tif (frmsizecod >= 2 * sizeof(ac3_sizecod_to_bitrate) / sizeof(u32))\n\t\treturn GF_FALSE;",
"\thdr->bitrate = ac3_sizecod_to_bitrate[frmsizecod / 2];\n\tif (bsid > 8) hdr->bitrate = hdr->bitrate >> (bsid - 8);",
"\tswitch (fscod) {\n\tcase 0:\n\t\tif (frmsizecod >= 2 * sizeof(ac3_sizecod0_to_framesize) / sizeof(u32))\n\t\t\treturn GF_FALSE;\n\t\tfreq = 48000;\n\t\tframesize = ac3_sizecod0_to_framesize[frmsizecod / 2] * 2;\n\t\tbreak;\n\tcase 1:\n\t\tif (frmsizecod >= 2 * sizeof(ac3_sizecod1_to_framesize) / sizeof(u32))\n\t\t\treturn GF_FALSE;\n\t\tfreq = 44100;\n\t\tframesize = (ac3_sizecod1_to_framesize[frmsizecod / 2] + (frmsizecod & 0x1)) * 2;\n\t\tbreak;\n\tcase 2:\n\t\tif (frmsizecod >= 2 * sizeof(ac3_sizecod2_to_framesize) / sizeof(u32))\n\t\t\treturn GF_FALSE;\n\t\tfreq = 32000;\n\t\tframesize = ac3_sizecod2_to_framesize[frmsizecod / 2] * 2;\n\t\tbreak;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n\thdr->sample_rate = freq;\n\thdr->framesize = framesize;",
"\tif (full_parse) {\n\t\thdr->streams[0].bsid = bsid;\n\t\thdr->streams[0].bsmod = bsmod;\n\t\thdr->streams[0].acmod = ac3_mod;\n\t\thdr->streams[0].lfon = 0;\n\t\thdr->streams[0].fscod = fscod;\n\t\thdr->brcode = frmsizecod / 2;\n\t}\n\tif (ac3_mod >= 2 * sizeof(ac3_mod_to_chans) / sizeof(u32))\n\t\treturn GF_FALSE;",
"\thdr->channels = ac3_mod_to_chans[ac3_mod];\n\tif ((ac3_mod & 0x1) && (ac3_mod != 1)) gf_bs_read_int_log(bs, 2, \"cmixlev\");\n\tif (ac3_mod & 0x4) gf_bs_read_int_log(bs, 2, \"surmixlev\");\n\tif (ac3_mod == 0x2) gf_bs_read_int_log(bs, 2, \"dsurmod\");",
"\tif (gf_bs_read_int_log(bs, 1, \"lfeon\")) {\n\t\thdr->channels += 1;\n\t\thdr->streams[0].lfon = 1;\n\t}",
"\tgf_bs_seek(bs, pos);",
"\treturn GF_TRUE;\n}",
"GF_EXPORT\nBool gf_eac3_parser_bs(GF_BitStream *bs, GF_AC3Config *hdr, Bool full_parse)\n{\n\tu32 fscod, bsid, ac3_mod, freq, framesize, syncword, substreamid, lfon, channels, numblkscod, strmtyp, frmsiz;\n\tu64 pos;\n\tu16 chanmap;\n\tstatic u32 numblks[4] = {1, 2, 3, 6};",
"\tif (!hdr || (gf_bs_available(bs) < 6))\n\t\treturn GF_FALSE;\n\tif (!AC3_FindSyncCodeBS(bs))\n\t\treturn GF_FALSE;",
"\tpos = gf_bs_get_position(bs);\n\tframesize = 0;\n\tnumblkscod = 0;\n\tmemset(hdr, 0, sizeof(GF_AC3Config));",
"block:\n\tsyncword = gf_bs_read_u16(bs);\n\tif (syncword != 0x0B77) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[E-AC3] Wrong sync word detected (0x%X - expecting 0x0B77).\\n\", syncword));\n\t\treturn GF_FALSE;\n\t}",
"\tstrmtyp = gf_bs_read_int_log(bs, 2, \"strmtyp\");\n\tsubstreamid = gf_bs_read_int_log(bs, 3, \"substreamid\");\n\t//next main (independent) AU, done with this frame\n\tif ((strmtyp!=0x1) && ((hdr->substreams >> substreamid) & 0x1)) {\n\t\thdr->framesize = framesize;\n\t\tgf_bs_seek(bs, pos);\n\t\treturn GF_TRUE;\n\t}",
"\tfrmsiz = gf_bs_read_int_log(bs, 11, \"frmsiz\");\n\tframesize += 2 * (1 + frmsiz);\n\tfscod = gf_bs_read_int_log(bs, 2, \"fscod\");\n\tif (fscod == 0x3) {\n\t\tfscod = gf_bs_read_int_log(bs, 2, \"fscod2\");\n\t\tnumblkscod += 6;\n\t}\n\telse {\n\t\tnumblkscod += gf_bs_read_int_log(bs, 2, \"numblkscod\");\n\t}\n\tassert(numblkscod <= 9);",
"\n\tif ((hdr->substreams >> substreamid) & 0x1) {\n\t\t//we still have sync frames following\n\t\tif (substreamid) {\n\t\t\tif (gf_bs_seek(bs, pos + framesize) != GF_OK) {\n\t\t\t\tgf_bs_seek(bs, pos);\n\t\t\t\treturn GF_FALSE;\n\t\t\t}\n\t\t\tif ((gf_bs_available(bs) < 6) || !AC3_FindSyncCodeBS(bs)) {\n\t\t\t\tgf_bs_seek(bs, pos);\n\t\t\t\treturn GF_FALSE;\n\t\t\t}\n\t\t\tgoto block;\n\t\t}\n\t}",
"\thdr->substreams |= (1 << substreamid);",
"\tswitch (fscod) {\n\tcase 0:\n\t\tfreq = 48000;\n\t\tbreak;\n\tcase 1:\n\t\tfreq = 44100;\n\t\tbreak;\n\tcase 2:\n\t\tfreq = 32000;\n\t\tbreak;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}",
"\tac3_mod = gf_bs_read_int_log(bs, 3, \"ac3_mod\");\n\tlfon = gf_bs_read_int_log(bs, 1, \"lfon\");\n\tbsid = gf_bs_read_int_log(bs, 5, \"bsid\");\n\tif (!substreamid && (bsid != 16/*E-AC3*/))\n\t\treturn GF_FALSE;\n\tgf_bs_read_int_log(bs, 5, \"dialnorm\");\n\tif (gf_bs_read_int_log(bs, 1, \"compre\")) {\n\t\tgf_bs_read_int_log(bs, 8, \"compr\");\n\t}\n\tif (ac3_mod==0) {\n\t\tgf_bs_read_int_log(bs, 5, \"dialnorm2\");\n\t\tif (gf_bs_read_int_log(bs, 1, \"compr2e\")) {\n\t\t\tgf_bs_read_int_log(bs, 8, \"compr2\");\n\t\t}\n\t}\n\tchanmap = 0;\n\tif (strmtyp==0x1) {\n\t\tif (gf_bs_read_int_log(bs, 1, \"chanmape\")) {\n\t\t\tchanmap = gf_bs_read_int_log(bs, 16, \"chanmap\");\n\t\t}\n\t}",
"\tchannels = ac3_mod_to_chans[ac3_mod];\n\tif (lfon)\n\t\tchannels += 1;",
"\thdr->bitrate = 0;\n\thdr->sample_rate = freq;\n\thdr->framesize = framesize;\n\tif (strmtyp != 1) {\n\t\thdr->channels = channels;\n\t\thdr->streams[substreamid].lfon = lfon;\n\t\tif (full_parse) {\n\t\t\thdr->streams[substreamid].bsid = bsid;\n\t\t\thdr->streams[substreamid].bsmod = 0;\n\t\t\thdr->streams[substreamid].acmod = ac3_mod;\n\t\t\thdr->streams[substreamid].fscod = fscod;\n\t\t\thdr->brcode = 0;\n\t\t}\n\t\thdr->nb_streams++;\n\t\t//not clear if this is only for the independent streams\n\t\thdr->brcode += ((frmsiz+1) * freq) / (numblks[numblkscod]*16) / 1000;",
"\t\tif (lfon)\n\t\t\thdr->channels += 1;",
"\t} else {\n\t\thdr->streams[substreamid].nb_dep_sub = substreamid;\n\t\thdr->streams[substreamid].chan_loc |= chanmap;\n\t}",
"\tif (numblkscod < 6) { //we need 6 blocks to make a sample\n\t\tif (gf_bs_seek(bs, pos + framesize) != GF_OK) {\n\t\t\tgf_bs_seek(bs, pos);\n\t\t\treturn GF_FALSE;\n\t\t}",
"\t\tif ((gf_bs_available(bs) < 6) || !AC3_FindSyncCodeBS(bs))\n\t\t\treturn GF_FALSE;\n\t\tgoto block;\n\t}",
"\tgf_bs_seek(bs, pos);",
"\treturn GF_TRUE;\n}",
"#endif /*GPAC_DISABLE_AV_PARSERS*/",
"u32 gf_id3_read_size(GF_BitStream *bs)\n{\n\tu32 size = 0;\n\tgf_bs_read_int(bs, 1);\n\tsize |= gf_bs_read_int(bs, 7);\n\tsize<<=7;\n\tgf_bs_read_int(bs, 1);\n\tsize |= gf_bs_read_int(bs, 7);\n\tsize<<=7;\n\tgf_bs_read_int(bs, 1);\n\tsize |= gf_bs_read_int(bs, 7);\n\tsize<<=7;\n\tgf_bs_read_int(bs, 1);\n\tsize |= gf_bs_read_int(bs, 7);\n\treturn size;\n}",
"\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined (GPAC_DISABLE_OGG)",
"/*\n\tVorbis parser\n*/",
"static u32 vorbis_book_maptype1_quantvals(u32 entries, u32 dim)\n{\n\tu32 vals = (u32)floor(pow(entries, 1.0 / dim));\n\twhile (1) {\n\t\tu32 acc = 1;\n\t\tu32 acc1 = 1;\n\t\tu32 i;\n\t\tfor (i = 0; i < dim; i++) {\n\t\t\tacc *= vals;\n\t\t\tacc1 *= vals + 1;\n\t\t}\n\t\tif (acc <= entries && acc1 > entries) return (vals);\n\t\telse {\n\t\t\tif (acc > entries) vals--;\n\t\t\telse vals++;\n\t\t}\n\t}\n}",
"static u32 ilog(u32 v, Bool dec)\n{\n\tu32 ret = 0;\n\tif (dec && v) --v;\n\twhile (v) {\n\t\tret++;\n\t\tv >>= 1;\n\t}\n\treturn (ret);\n}",
"static u32 icount(u32 v)\n{\n\tu32 ret = 0;\n\twhile (v) {\n\t\tret += v & 1;\n\t\tv >>= 1;\n\t}\n\treturn(ret);\n}",
"\nGF_EXPORT\nBool gf_vorbis_parse_header(GF_VorbisParser *vp, u8 *data, u32 data_len)\n{\n\tu32 pack_type, i, j, k, times, nb_part, nb_books, nb_modes;\n\tu32 l;\n\tchar szNAME[8];\n\toggpack_buffer opb;",
"\toggpack_readinit(&opb, (u8*)data, data_len);\n\tpack_type = oggpack_read(&opb, 8);\n\ti = 0;\n\twhile (i < 6) {\n\t\tszNAME[i] = oggpack_read(&opb, 8);\n\t\ti++;\n\t}\n\tszNAME[i] = 0;\n\tif (strcmp(szNAME, \"vorbis\")) {\n\t\treturn GF_FALSE;\n\t}",
"\tswitch (pack_type) {\n\tcase 0x01:\n\t\tvp->version = oggpack_read(&opb, 32);\n\t\tif (vp->version != 0) {\n\t\t\treturn GF_FALSE;\n\t\t}\n\t\tvp->channels = oggpack_read(&opb, 8);\n\t\tvp->sample_rate = oggpack_read(&opb, 32);\n\t\tvp->max_r = oggpack_read(&opb, 32);\n\t\tvp->avg_r = oggpack_read(&opb, 32);\n\t\tvp->low_r = oggpack_read(&opb, 32);",
"\t\tvp->min_block = 1<<oggpack_read(&opb, 4);\n\t\tvp->max_block = 1<<oggpack_read(&opb, 4);\n\t\tif (vp->sample_rate < 1 || vp->channels < 1 || vp->min_block < 8 || vp->max_block < vp->min_block\n\t\t || oggpack_read(&opb, 1) != 1) {\n\t\t\treturn GF_FALSE;\n\t\t}\n\t\tvp->nb_init=1;\n\t\treturn GF_TRUE;",
"\tcase 0x03:\n\t\t/*trash comments*/\n\t\tvp->nb_init++;\n\t\treturn GF_TRUE;\n\tcase 0x05:\n\t\t/*need at least bitstream header to make sure we're parsing the right thing*/\n\t\tif (!vp->nb_init) return GF_FALSE;\n\t\tbreak;\n\tdefault:\n\t\treturn GF_FALSE;\n\t}\n\t/*OK parse codebook*/\n\tnb_books = oggpack_read(&opb, 8) + 1;\n\t/*skip vorbis static books*/\n\tfor (i = 0; i < nb_books; i++) {\n\t\tu32 map_type, qb, qq;\n\t\tu32 entries, dim;\n\t\toggpack_read(&opb, 24);\n\t\tdim = oggpack_read(&opb, 16);\n\t\tentries = oggpack_read(&opb, 24);\n\t\tif ((s32)entries < 0) entries = 0;\n\t\tif (oggpack_read(&opb, 1) == 0) {\n\t\t\tif (oggpack_read(&opb, 1)) {\n\t\t\t\tfor (j = 0; j < entries; j++) {\n\t\t\t\t\tif (oggpack_read(&opb, 1)) {\n\t\t\t\t\t\toggpack_read(&opb, 5);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (j = 0; j < entries; j++)\n\t\t\t\t\toggpack_read(&opb, 5);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\toggpack_read(&opb, 5);\n\t\t\tfor (j = 0; j < entries;) {\n\t\t\t\tu32 num = oggpack_read(&opb, ilog(entries - j, GF_FALSE));\n\t\t\t\tfor (k = 0; k < num && j < entries; k++, j++) {\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tswitch ((map_type = oggpack_read(&opb, 4))) {\n\t\tcase 0:\n\t\t\tbreak;\n\t\tcase 1:\n\t\tcase 2:\n\t\t\toggpack_read(&opb, 32);\n\t\t\toggpack_read(&opb, 32);\n\t\t\tqq = oggpack_read(&opb, 4) + 1;\n\t\t\toggpack_read(&opb, 1);\n\t\t\tif (map_type == 1) qb = vorbis_book_maptype1_quantvals(entries, dim);\n\t\t\telse if (map_type == 2) qb = entries * dim;\n\t\t\telse qb = 0;\n\t\t\tfor (j = 0; j < qb; j++) oggpack_read(&opb, qq);\n\t\t\tbreak;\n\t\t}\n\t}\n\ttimes = oggpack_read(&opb, 6) + 1;\n\tfor (i = 0; i < times; i++) oggpack_read(&opb, 16);\n\ttimes = oggpack_read(&opb, 6) + 1;\n\tfor (i = 0; i < times; i++) {\n\t\tu32 type = oggpack_read(&opb, 16);\n\t\tif (type) {\n\t\t\tu32 *parts, *class_dims, count, rangebits;\n\t\t\tu32 max_class = 0;\n\t\t\tnb_part = oggpack_read(&opb, 5);\n\t\t\tparts = (u32*)gf_malloc(sizeof(u32) * nb_part);\n\t\t\tfor (j = 0; j < nb_part; j++) {\n\t\t\t\tparts[j] = oggpack_read(&opb, 4);\n\t\t\t\tif (max_class < parts[j]) max_class = parts[j];\n\t\t\t}\n\t\t\tclass_dims = (u32*)gf_malloc(sizeof(u32) * (max_class + 1));\n\t\t\tfor (j = 0; j < max_class + 1; j++) {\n\t\t\t\tu32 class_sub;\n\t\t\t\tclass_dims[j] = oggpack_read(&opb, 3) + 1;\n\t\t\t\tclass_sub = oggpack_read(&opb, 2);\n\t\t\t\tif (class_sub) oggpack_read(&opb, 8);\n\t\t\t\tfor (k = 0; k < (u32)(1 << class_sub); k++) oggpack_read(&opb, 8);\n\t\t\t}\n\t\t\toggpack_read(&opb, 2);\n\t\t\trangebits = oggpack_read(&opb, 4);\n\t\t\tcount = 0;\n\t\t\tfor (j = 0, k = 0; j < nb_part; j++) {\n\t\t\t\tcount += class_dims[parts[j]];\n\t\t\t\tfor (; k < count; k++) oggpack_read(&opb, rangebits);\n\t\t\t}\n\t\t\tgf_free(parts);\n\t\t\tgf_free(class_dims);\n\t\t}\n\t\telse {\n\t\t\toggpack_read(&opb, 8 + 16 + 16 + 6 + 8);\n\t\t\tnb_books = oggpack_read(&opb, 4) + 1;\n\t\t\tfor (j = 0; j < nb_books; j++)\n\t\t\t\toggpack_read(&opb, 8);\n\t\t}\n\t}\n\ttimes = oggpack_read(&opb, 6) + 1;\n\tfor (i = 0; i < times; i++) {\n\t\tu32 acc = 0;\n\t\toggpack_read(&opb, 16);/*type*/\n\t\toggpack_read(&opb, 24);\n\t\toggpack_read(&opb, 24);\n\t\toggpack_read(&opb, 24);\n\t\tnb_part = oggpack_read(&opb, 6) + 1;\n\t\toggpack_read(&opb, 8);\n\t\tfor (j = 0; j < nb_part; j++) {\n\t\t\tu32 cascade = oggpack_read(&opb, 3);\n\t\t\tif (oggpack_read(&opb, 1)) cascade |= (oggpack_read(&opb, 5) << 3);\n\t\t\tacc += icount(cascade);\n\t\t}\n\t\tfor (j = 0; j < acc; j++) oggpack_read(&opb, 8);\n\t}\n\ttimes = oggpack_read(&opb, 6) + 1;\n\tfor (i = 0; i < times; i++) {\n\t\tu32 sub_maps = 1;\n\t\toggpack_read(&opb, 16);\n\t\tif (oggpack_read(&opb, 1)) sub_maps = oggpack_read(&opb, 4) + 1;\n\t\tif (oggpack_read(&opb, 1)) {\n\t\t\tu32 nb_steps = oggpack_read(&opb, 8) + 1;\n\t\t\tfor (j = 0; j < nb_steps; j++) {\n\t\t\t\toggpack_read(&opb, ilog(vp->channels, GF_TRUE));\n\t\t\t\toggpack_read(&opb, ilog(vp->channels, GF_TRUE));\n\t\t\t}\n\t\t}\n\t\toggpack_read(&opb, 2);\n\t\tif (sub_maps>1) {\n\t\t\tfor(l=0; l<vp->channels; l++)\n\t\t\t\toggpack_read(&opb, 4);\n\t\t}\n\t\tfor (j = 0; j < sub_maps; j++) {\n\t\t\toggpack_read(&opb, 8);\n\t\t\toggpack_read(&opb, 8);\n\t\t\toggpack_read(&opb, 8);\n\t\t}\n\t}\n\tnb_modes = oggpack_read(&opb, 6) + 1;\n\tfor (i = 0; i < nb_modes; i++) {\n\t\tvp->mode_flag[i] = oggpack_read(&opb, 1);\n\t\toggpack_read(&opb, 16);\n\t\toggpack_read(&opb, 16);\n\t\toggpack_read(&opb, 8);\n\t}",
"\tvp->modebits = 0;\n\tj = nb_modes;\n\twhile (j > 1) {\n\t\tvp->modebits++;\n\t\tj >>= 1;\n\t}",
"\treturn GF_TRUE;\n}",
"GF_EXPORT\nu32 gf_vorbis_check_frame(GF_VorbisParser *vp, u8 *data, u32 data_length)\n{\n\ts32 block_size;\n\toggpack_buffer opb;\n\tif (!vp) return 0;\n\toggpack_readinit(&opb, (unsigned char*)data, data_length);\n\t/*not audio*/\n\tif (oggpack_read(&opb, 1) != 0) return 0;\n\tblock_size = oggpack_read(&opb, vp->modebits);\n\tif (block_size == -1) return 0;\n\treturn ((vp->mode_flag[block_size]) ? vp->max_block : vp->min_block) / (2);\n}",
"/*call with vorbis header packets - initializes the parser on success, leave it to NULL otherwise\nreturns 1 if success, 0 if error.*/\nBool gf_opus_parse_header(GF_OpusParser *opus, u8 *data, u32 data_len)\n{\n\tchar tag[9];\n\tGF_BitStream *bs = gf_bs_new(data, data_len, GF_BITSTREAM_READ);\n\tgf_bs_read_data(bs, tag, 8);\n\ttag[8]=0;",
"\tif (memcmp(data, \"OpusHead\", sizeof(char)*8)) {\n\t\tgf_bs_del(bs);\n\t\treturn GF_FALSE;\n\t}\n\t/*Identification Header*/\n\topus->version = gf_bs_read_u8(bs); /*version*/\n\tif (opus->version != 1) {\n\t\tgf_bs_del(bs);\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[Opus] Unsupported version %d\\n\", opus->version));\n\t\treturn GF_FALSE;\n\t}\n\topus->OutputChannelCount = gf_bs_read_u8(bs);\n\topus->PreSkip = gf_bs_read_u16_le(bs);\n\topus->InputSampleRate = gf_bs_read_u32_le(bs);\n\topus->OutputGain = gf_bs_read_u16_le(bs);\n\topus->ChannelMappingFamily = gf_bs_read_u8(bs);\n\tif (opus->ChannelMappingFamily != 0) {\n\t\topus->StreamCount = gf_bs_read_u8(bs);\n\t\topus->CoupledCount = gf_bs_read_u8(bs);\n\t\tgf_bs_read_data(bs, (char *) opus->ChannelMapping, opus->OutputChannelCount);\n\t}\n\tgf_bs_del(bs);\n\treturn GF_TRUE;\n}",
"/*returns 0 if init error or not a vorbis frame, otherwise returns the number of audio samples\nin this frame*/\nu32 gf_opus_check_frame(GF_OpusParser *op, u8 *data, u32 data_length)\n{\n\tu32 block_size;",
"\tif (!memcmp(data, \"OpusHead\", sizeof(char)*8))\n\t\treturn 0;\n\tif (!memcmp(data, \"OpusTags\", sizeof(char)*8))\n\t\treturn 0;",
"\t/*consider the whole packet as Ogg packets and ISOBMFF samples for Opus are framed similarly*/\n\tstatic const int OpusFrameDurIn48k[] = { 480, 960, 1920, 2880, 480, 960, 1920, 2880, 480, 960, 1920, 2880,\n\t\t480, 960, 480, 960,\n\t\t120, 240, 480, 960, 120, 240, 480, 960, 120, 240, 480, 960, 120, 240, 480, 960,\n\t};\n\tint TOC_config = (data[0] & 0xf8) >> 3;\n\t//int s = (data[0] & 0x04) >> 2;\n\tblock_size = OpusFrameDurIn48k[TOC_config];",
"\tint c = data[0] & 0x03;\n\tif (c == 1 || c == 2) {\n\t\tblock_size *= 2;\n\t} else if (c == 3) {\n\t\t/*unknown number of frames*/\n\t\tint num_frames = data[1] & 0x3f;\n\t\tblock_size *= num_frames;\n\t}\n\treturn block_size;\n}",
"#endif /*!defined(GPAC_DISABLE_AV_PARSERS) && !defined (GPAC_DISABLE_OGG)*/",
"u64 gf_mpegh_escaped_value(GF_BitStream *bs, u32 nBits1, u32 nBits2, u32 nBits3)\n{\n\tu64 value = gf_bs_read_int(bs, nBits1);\n\tif (value == (1<<nBits1)-1) {\n\t\tu32 vadd = gf_bs_read_int(bs, nBits2);\n\t\tvalue += vadd;\n\t\tif (vadd == (1<<nBits2)-1) {\n\t\t\tvadd = gf_bs_read_int(bs, nBits3);\n\t\t\tvalue += vadd;\n\t\t}\n\t}\n\treturn value;\n}",
"GF_EXPORT\ns32 gf_mpegh_get_mhas_pl(u8 *ptr, u32 size, u64 *ch_layout)\n{\n\ts32 PL = -1;\n\tGF_BitStream *bs;\n\tu32 i;\n\ts32 sync_pos=-1;",
"\tif (!ptr || !size) return 0;\n\t\n\tfor (i=0; i<size-3; i++) {\n\t\tif ((ptr[i]==0xC0) && (ptr[i+1]== 0x01) && (ptr[i+2]==0xA5)) {\n\t\t\tsync_pos = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (sync_pos<0) return 0;\n\tif (ch_layout) *ch_layout = 0;\n\tbs = gf_bs_new(ptr, size, GF_BITSTREAM_READ);\n\tgf_bs_skip_bytes(bs, sync_pos);",
"\twhile (gf_bs_available(bs)) {\n\t\tu32 type = (u32) gf_mpegh_escaped_value(bs, 3, 8, 8);\n\t\t/*u64 label = */gf_mpegh_escaped_value(bs, 2, 8, 32);\n\t\tu64 mh_size = gf_mpegh_escaped_value(bs, 11, 24, 24);\n\t\tif (mh_size > gf_bs_available(bs))\n\t\t\tbreak;\n\t\t//MHAS config\n\t\tif (type==1) {\n\t\t\tPL = gf_bs_read_int(bs, 8);\n\t\t\tif (ch_layout) {\n\t\t\t\tu32 idx = gf_bs_read_int(bs, 5);\n\t\t\t\tif (idx==0x1f)\n\t\t\t\t\tgf_bs_read_int(bs, 24);\n\t\t\t\t/*idx = */gf_bs_read_int(bs, 3);\n\t\t\t\tgf_bs_read_int(bs, 1);\n\t\t\t\tgf_bs_read_int(bs, 1);",
"\t\t\t\t//speaker config\n\t\t\t\tidx = gf_bs_read_int(bs, 2);\n\t\t\t\tif (idx == 0) {\n\t\t\t\t\t*ch_layout = gf_audio_fmt_get_layout_from_cicp( gf_bs_read_int(bs, 6) );\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tgf_bs_skip_bytes(bs, mh_size);\n\t}\n\tgf_bs_del(bs);\n\treturn PL;\n}",
"\nGF_EXPORT\nvoid gf_media_vvc_parse_sei(char *buffer, u32 nal_size, VVCState *vvc)\n{\n\tgf_hevc_vvc_parse_sei(buffer, nal_size, NULL, vvc);\n}",
"static Bool vvc_parse_nal_header(GF_BitStream *bs, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tu32 val;\n\tval = gf_bs_read_int_log(bs, 1, \"forbidden_zero\");\n\tif (val) return GF_FALSE;\n\tval = gf_bs_read_int_log(bs, 1, \"resevred0\");\n\tif (val) return GF_FALSE;",
"\tval = gf_bs_read_int_log(bs, 6, \"layerID\");\n\tif (layer_id) *layer_id = val;",
"\tval = gf_bs_read_int_log(bs, 5, \"nuh_type\");\n\tif (nal_unit_type) *nal_unit_type = val;",
"\tval = gf_bs_read_int_log(bs, 3, \"temporalID\");\n\tif (!val) return GF_FALSE;\n\tval -= 1;\n\tif (temporal_id) *temporal_id = val;\n\treturn GF_TRUE;\n}",
"static void vvc_profile_tier_level(GF_BitStream *bs, VVC_ProfileTierLevel *ptl, u32 idx)\n{\n\tu32 i;\n\tif (ptl->pt_present) {\n\t\tptl->general_profile_idc = gf_bs_read_int_log_idx(bs, 7, \"general_profile_idc\", idx);\n\t\tptl->general_tier_flag = gf_bs_read_int_log_idx(bs, 1, \"general_tier_flag\", idx);\n\t}\n\tptl->general_level_idc = gf_bs_read_int_log_idx(bs, 8, \"general_level_idc\", idx);\n\tptl->frame_only_constraint = gf_bs_read_int_log_idx(bs, 1, \"frame_only_constraint\", idx);\n\tptl->multilayer_enabled = gf_bs_read_int_log_idx(bs, 1, \"multilayer_enabled\", idx);\n\t//general constraints info - max size if 1 + 81 + 8 + 255\n\tif (ptl->pt_present) {\n\t\t//\t\tgeneral_constraints_info\n\t\tptl->gci_present = gf_bs_read_int_log_idx(bs, 1, \"gci_present\", idx);\n\t\tif (ptl->gci_present) {\n\t\t\tu8 res;\n\t\t\tptl->gci[0] = 0x80;\n\t\t\tptl->gci[0] |= gf_bs_read_int(bs, 7);\n\t\t\t//81-7 = 74 bits till reserved\n\t\t\tgf_bs_read_data(bs, ptl->gci+1, 9);\n\t\t\tptl->gci[10] = gf_bs_read_int(bs, 2)<<6;\n\t\t\t//skip extensions\n\t\t\tptl->gci[11] = 0;\n\t\t\tres = gf_bs_read_int(bs, 8);\n\t\t\tgf_bs_read_int(bs, res);\n\t\t}\n\t\tgf_bs_align(bs);\n\t}\n\tfor (i=ptl->ptl_max_tid; i>0; i--) {\n\t\tptl->sub_ptl[i-1].level_present_flag = gf_bs_read_int_log_idx2(bs, 1, \"level_present_flag\", idx, i);\n\t}\n\tgf_bs_align(bs);\n\tfor (i=ptl->ptl_max_tid; i>0; i--) {\n\t\tif (ptl->sub_ptl[i-1].level_present_flag)\n\t\t\tptl->sub_ptl[i-1].sublayer_level_idc = gf_bs_read_int_log_idx2(bs, 8, \"sublayer_level_idc\", idx, i);\n\t}\n\tif (ptl->pt_present) {\n\t\tptl->num_sub_profiles = gf_bs_read_int_log_idx(bs, 8, \"num_sub_profiles\", idx);\n\t\tfor (i=0; i<ptl->num_sub_profiles; i++) {\n\t\t\tptl->sub_profile_idc[i] = gf_bs_read_int_log_idx2(bs, 32, \"sub_profile_idc\", idx, i);\n\t\t}\n\t}\n}",
"static s32 gf_media_vvc_read_vps_bs_internal(GF_BitStream *bs, VVCState *vvc, Bool stop_at_vps_ext)\n{\n\tu32 i, j;\n\ts32 vps_id;\n\tVVC_VPS *vps;\n\tBool vps_default_ptl_dpb_hrd_max_tid_flag=0;",
"\t//nalu header already parsed\n\tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n\tif ((vps_id<0) || (vps_id >= 16)) return -1;\n\tif (!vps_id) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] VPS ID 0 is forbidden\\n\"));\n\t\treturn -1;\n\t}\n\tvps = &vvc->vps[vps_id];\n\tif (!vps->state) {\n\t\tvps->id = vps_id;\n\t\tvps->state = 1;\n\t}\n\tvps->max_layers = 1 + gf_bs_read_int_log(bs, 6, \"max_layers\");\n\tif (vps->max_layers > MAX_LHVC_LAYERS) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] sorry, %d layers in VPS but only %d supported\\n\", vps->max_layers, MAX_LHVC_LAYERS));\n\t\treturn -1;\n\t}\n\tvps->max_sub_layers = gf_bs_read_int_log(bs, 3, \"max_sub_layers_minus1\") + 1;",
"\tif ((vps->max_layers>1) && (vps->max_sub_layers>1))\n\t\tvps_default_ptl_dpb_hrd_max_tid_flag = gf_bs_read_int_log(bs, 1, \"vps_default_ptl_dpb_hrd_max_tid_flag\");",
"\tif (vps->max_layers>1)\n\t\tvps->all_layers_independent = gf_bs_read_int_log(bs, 1, \"all_layers_independent\");",
"\tfor (i=0; i<vps->max_layers; i++) {\n\t\tu32 layer_id = gf_bs_read_int_log_idx(bs, 6, \"layer_id\", i);\n\t\tif (layer_id>vps->max_layer_id) vps->max_layer_id = layer_id;\n\t\tif (i && !vps->all_layers_independent) {\n\t\t\tBool layer_indep = gf_bs_read_int_log_idx(bs, 1, \"layer_independent\", i);\n\t\t\tif (!layer_indep) {\n\t\t\t\tBool vps_max_tid_ref_present_flag = gf_bs_read_int_log_idx(bs, 1, \"vps_max_tid_ref_present_flag\", i);\n\t\t\t\tfor (j=0; j<i; j++) {\n\t\t\t\t\tBool vps_direct_ref_layer_flag = gf_bs_read_int_log_idx2(bs, 1, \"vps_direct_ref_layer_flag\", i, j);\n\t\t\t\t\tif (vps_max_tid_ref_present_flag && vps_direct_ref_layer_flag) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx2(bs, 3, \"vps_max_tid_il_ref_pics_plus1\", i, j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tvps->num_ptl = 1;\n\tif (vps->max_layers > 1) {\n\t\tif (vps->all_layers_independent) {\n\t\t\tvps->each_layer_is_ols = gf_bs_read_int_log(bs, 1, \"each_layer_is_ols\");\n\t\t}\n\t\tif (!vps->each_layer_is_ols) {\n\t\t\tu32 vps_ols_mode_idc = 2;\n\t\t\tif (!vps->all_layers_independent) {\n\t\t\t\tvps_ols_mode_idc = gf_bs_read_int_log(bs, 2, \"vps_ols_mode_idc\");\n\t\t\t}\n\t\t\tif (vps_ols_mode_idc==2) {\n\t\t\t\tu8 vps_num_output_layer_sets = 2 + gf_bs_read_int_log(bs, 8, \"vps_num_output_layer_sets_minus2\");\n\t\t\t\tfor (i=0; i<vps_num_output_layer_sets; i++) {\n\t\t\t\t\tfor (j=0; j<vps->max_layers; j++) {\n\t\t\t\t\t\tgf_bs_read_int_log_idx2(bs, 1, \"vps_ols_output_layer_flag\", i, j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvps->num_ptl = 1 + gf_bs_read_int_log(bs, 8, \"num_ptl_minus1\");\n\t}\n\tvps->ptl[0].pt_present = 1;\n\tfor (i=0; i<vps->num_ptl; i++) {\n\t\tif (i)\n\t\t\tvps->ptl[i].pt_present = gf_bs_read_int_log_idx(bs, 1, \"pt_present\", i);\n\t\tif (!vps_default_ptl_dpb_hrd_max_tid_flag)\n\t\t\tvps->ptl[i].ptl_max_tid = gf_bs_read_int_log_idx(bs, 3, \"ptl_max_tid\", i);\n\t\telse\n\t\t\tvps->ptl[i].ptl_max_tid = vps->max_sub_layers - 1;\n\t}\n\t//align\n\tgf_bs_align(bs);",
"\tfor (i=0; i<vps->num_ptl; i++) {\n\t\tvvc_profile_tier_level(bs, &vps->ptl[i], i);\n\t}",
"\t//TODO, parse multilayer stuff\n\treturn vps_id;\n}",
"\nstatic s32 gf_media_vvc_read_sps_bs_internal(GF_BitStream *bs, VVCState *vvc, u8 layer_id, u32 *vui_flag_pos)\n{\n\ts32 vps_id, sps_id;\n\tu32 i, CtbSizeY;\n\tVVC_SPS *sps;\n\tu8 sps_ptl_dpb_hrd_params_present_flag;",
"\tif (vui_flag_pos) *vui_flag_pos = 0;",
"\tsps_id = gf_bs_read_int_log(bs, 4, \"sps_id\");\n\tif ((sps_id<0) || (sps_id >= 16)) {\n\t\treturn -1;\n\t}\n\tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n\tif ((vps_id<0) || (vps_id >= 16)) {\n\t\treturn -1;\n\t}\n\tif (!vps_id && !vvc->vps[0].state) {\n\t\tvvc->vps[0].state = 1;\n\t\tvvc->vps[0].num_ptl = 1;\n\t\tvvc->vps[0].max_layers = 1;\n\t\tvvc->vps[0].all_layers_independent = 1;\n\t}",
"\tsps = &vvc->sps[sps_id];\n\tif (!sps->state) {\n\t\tsps->state = 1;\n\t\tsps->id = sps_id;\n\t\tsps->vps_id = vps_id;\n\t}\n\tsps->max_sublayers = 1 + gf_bs_read_int_log(bs, 3, \"max_sublayers_minus1\");\n\tsps->chroma_format_idc = gf_bs_read_int_log(bs, 2, \"chroma_format_idc\");\n\tsps->log2_ctu_size = 5 + gf_bs_read_int_log(bs, 2, \"log2_ctu_size_minus5\");\n\tCtbSizeY = 1<<sps->log2_ctu_size;",
"\tsps_ptl_dpb_hrd_params_present_flag = gf_bs_read_int_log(bs, 1, \"sps_ptl_dpb_hrd_params_present_flag\");\n\tif (sps_ptl_dpb_hrd_params_present_flag) {\n\t\tVVC_ProfileTierLevel ptl, *p_ptl;\n\t\tif (sps->vps_id) {\n\t\t\tp_ptl = &ptl;\n\t\t} else {\n\t\t\tp_ptl = &vvc->vps[0].ptl[0];\n\t\t}\n\t\tmemset(p_ptl, 0, sizeof(VVC_ProfileTierLevel));\n\t\tp_ptl->pt_present = 1;\n\t\tp_ptl->ptl_max_tid = sps->max_sublayers-1;\n\t\tvvc_profile_tier_level(bs, p_ptl, 0);\n\t}\n\tsps->gdr_enabled = gf_bs_read_int_log(bs, 1, \"gdr_enabled\");\n\tsps->ref_pic_resampling = gf_bs_read_int_log(bs, 1, \"ref_pic_resampling\");\n\tif (sps->ref_pic_resampling)\n\t\tsps->res_change_in_clvs = gf_bs_read_int_log(bs, 1, \"res_change_in_clvs\");\n\tsps->width = gf_bs_read_ue_log(bs, \"width\");\n\tsps->height = gf_bs_read_ue_log(bs, \"height\");\n\tsps->conf_window = gf_bs_read_int_log(bs, 1, \"conformance_window_present_flag\");\n\tif (sps->conf_window) {\n\t\tsps->cw_left = gf_bs_read_ue_log(bs, \"conformance_window_left\");\n\t\tsps->cw_right = gf_bs_read_ue_log(bs, \"conformance_window_right\");\n\t\tsps->cw_top = gf_bs_read_ue_log(bs, \"conformance_window_top\");\n\t\tsps->cw_bottom = gf_bs_read_ue_log(bs, \"conformance_window_bottom\");\n\t}\n\tsps->subpic_info_present = gf_bs_read_int_log(bs, 1, \"subpic_info_present\");\n\tif (sps->subpic_info_present) {\n\t\tsps->nb_subpics = 1 + gf_bs_read_ue_log(bs, \"nb_subpics_minus1\");\n\t\tif (sps->nb_subpics>1) {\n\t\t\tu32 tmpWidthVal, tmpHeightVal;\n\t\t\tsps->independent_subpic_flags = gf_bs_read_int_log(bs, 1, \"independent_subpic_flags\");\n\t\t\tsps->subpic_same_size = gf_bs_read_int_log(bs, 1, \"subpic_same_size\");",
"\t\t\ttmpWidthVal = (sps->width + CtbSizeY-1) / CtbSizeY;\n\t\t\ttmpWidthVal = gf_get_bit_size(tmpWidthVal);\n\t\t\ttmpHeightVal = (sps->height + CtbSizeY-1) / CtbSizeY;\n\t\t\ttmpHeightVal = gf_get_bit_size(tmpHeightVal);",
"\t\t\tfor (i=0; i<sps->nb_subpics; i++) {\n\t\t\t\tif( !sps->subpic_same_size || !i) {\n\t\t\t\t\tif (i && (sps->width > CtbSizeY))\n\t\t\t\t\t\tgf_bs_read_int_log(bs, tmpWidthVal, \"subpic_ctu_top_left_x\");\n\t\t\t\t\tif (i && (sps->height > CtbSizeY))\n\t\t\t\t\t\tgf_bs_read_int_log(bs, tmpHeightVal, \"subpic_ctu_top_left_y\");\n\t\t\t\t\tif ((i+1 < sps->nb_subpics) && (sps->width > CtbSizeY))\n\t\t\t\t\t\tgf_bs_read_int_log(bs, tmpWidthVal, \"subpic_width_minus1\");\n\t\t\t\t\tif ((i+1 < sps->nb_subpics) && (sps->height > CtbSizeY))\n\t\t\t\t\t\tgf_bs_read_int_log(bs, tmpHeightVal, \"subpic_height_minus1\");\n\t\t\t\t}\n\t\t\t\tif (!sps->independent_subpic_flags) {\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"subpic_treated_as_pic_flag\");\n\t\t\t\t\tgf_bs_read_int_log(bs, 1, \"loop_filter_across_subpic_enabled_flag\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tsps->subpicid_len = gf_bs_read_ue_log(bs, \"subpic_id_len_minus1\") + 1;\n\t\t\tsps->subpicid_mapping_explicit = gf_bs_read_int_log(bs, 1, \"subpic_id_mapping_explicitly_signalled_flag\");\n\t\t\tif (sps->subpicid_mapping_explicit) {\n\t\t\t\tsps->subpicid_mapping_present = gf_bs_read_int_log(bs, 1, \"subpic_id_mapping_present_flag\");\n\t\t\t\tif (sps->subpicid_mapping_present) {\n\t\t\t\t\tfor (i=0; i<sps->nb_subpics; i++) {\n\t\t\t\t\t\tgf_bs_read_ue_log(bs, \"subpic_id\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tsps->bitdepth = gf_bs_read_ue_log(bs, \"bitdepth_minus8\") + 8;\n\tgf_bs_read_int_log(bs, 1, \"entropy_coding_sync_enabled_flag\");\n\tgf_bs_read_int_log(bs, 1, \"entry_point_offsets_present_flag\");\n\tsps->log2_max_poc_lsb = 4 + gf_bs_read_int_log(bs, 4, \"log2_max_poc_lsb_minus4\");\n\tif ((sps->poc_msb_cycle_flag = gf_bs_read_int_log(bs, 1, \"poc_msb_cycle_flag\")))\n\t\tsps->poc_msb_cycle_len = 1 + gf_bs_read_ue_log(bs, \"poc_msb_cycle_len_minus1\");",
"\tu8 sps_num_extra_ph_bits = 8 * gf_bs_read_int_log(bs, 2, \"sps_num_extra_ph_bytes\");\n\tfor (i=0; i<sps_num_extra_ph_bits; i++) {\n\t\tif (gf_bs_read_int_log_idx(bs, 1, \"extra_ph_bit_present_flag\", 1))\n\t\t\tsps->ph_num_extra_bits++;\n\t}\n\tu8 sps_num_extra_sh_bits = 8 * gf_bs_read_int_log(bs, 2, \"num_extra_sh_bytes\");\n\tfor (i=0; i<sps_num_extra_sh_bits; i++) {\n\t\tif (gf_bs_read_int_log_idx(bs, 1, \"extra_sh_bit_present_flag\", i))\n\t\t\tsps->sh_num_extra_bits++;\n\t}",
"\tif (sps_ptl_dpb_hrd_params_present_flag) {\n\t\tu8 sps_sublayer_dpb_params_flag = 0;\n\t\tif (sps->max_sublayers>1) {\n\t\t\tsps_sublayer_dpb_params_flag = gf_bs_read_int_log(bs, 1, \"sps_sublayer_dpb_params_flag\");\n\t\t}\n\t\tfor (i=(sps_sublayer_dpb_params_flag ? 0 : sps->max_sublayers-1); i < sps->max_sublayers; i++ ) {\n\t\t\tgf_bs_read_ue_log_idx(bs, \"dpb_max_dec_pic_buffering_minus1\", i);\n\t\t\tgf_bs_read_ue_log_idx(bs, \"dpb_max_num_reorder_pics\", i);\n\t\t\tgf_bs_read_ue_log_idx(bs, \"dpb_max_latency_increase_plus1\", i);\n\t\t}\n\t}\n\tgf_bs_read_ue_log(bs, \"sps_log2_min_luma_coding_block_size_minus2\");\n\tgf_bs_read_int_log(bs, 1, \"sps_partition_constraints_override_enabled_flag\");\n\tgf_bs_read_ue_log(bs, \"sps_log2_min_luma_coding_block_size_minus2\");\n\tu8 sps_max_mtt_hierarchy_depth_intra_slice_luma = gf_bs_read_ue_log(bs, \"sps_max_mtt_hierarchy_depth_intra_slice_luma\");\n\tif (sps_max_mtt_hierarchy_depth_intra_slice_luma != 0) {\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_bt_min_qt_intra_slice_luma\");\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_tt_min_qt_intra_slice_luma\");\n\t}\n\tu8 sps_qtbtt_dual_tree_intra_flag = 0;\n\tif (sps->chroma_format_idc) {\n\t\tsps_qtbtt_dual_tree_intra_flag = gf_bs_read_int_log(bs, 1, \"sps_qtbtt_dual_tree_intra_flag\");\n\t}\n\tif (sps_qtbtt_dual_tree_intra_flag) {\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_min_qt_min_cb_intra_slice_chroma\");\n\t\tu8 sps_max_mtt_hierarchy_depth_intra_slice_chroma = gf_bs_read_ue_log(bs, \"sps_max_mtt_hierarchy_depth_intra_slice_chroma\");\n\t\tif( sps_max_mtt_hierarchy_depth_intra_slice_chroma != 0) {\n\t\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_bt_min_qt_intra_slice_chroma\");\n\t\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_tt_min_qt_intra_slice_chroma\");\n\t\t}\n\t}",
"\tgf_bs_read_ue_log(bs, \"sps_log2_diff_min_qt_min_cb_inter_slice\");\n\tu8 sps_max_mtt_hierarchy_depth_inter_slice = gf_bs_read_ue_log(bs, \"sps_max_mtt_hierarchy_depth_inter_slice\");\n\tif (sps_max_mtt_hierarchy_depth_inter_slice != 0) {\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_bt_min_qt_inter_slice\");\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_diff_max_tt_min_qt_inter_slice\");\n\t}\n\t//u8 sps_max_luma_transform_size_64_flag = 0;\n\tif (CtbSizeY > 32) {\n\t\t/*sps_max_luma_transform_size_64_flag = */gf_bs_read_int_log(bs, 1, \"sps_max_luma_transform_size_64_flag\");\n\t}\n\tu8 sps_transform_skip_enabled_flag = gf_bs_read_int_log(bs, 1, \"sps_transform_skip_enabled_flag\");",
"\tif (sps_transform_skip_enabled_flag) {\n\t\tgf_bs_read_ue_log(bs, \"sps_log2_transform_skip_max_size_minus2\");\n\t\tgf_bs_read_int_log(bs, 1, \"sps_bdpcm_enabled_flag\");\n\t}\n\tif (gf_bs_read_int_log(bs, 1, \"sps_mts_enabled_flag\")) {\n\t\tgf_bs_read_int_log(bs, 1, \"sps_explicit_mts_intra_enabled_flag\");\n\t\tgf_bs_read_int_log(bs, 1, \"sps_explicit_mts_inter_enabled_flag\");\n\t}\n\tgf_bs_read_int_log(bs, 1, \"sps_lfnst_enabled_flag\");\n\tif (sps->chroma_format_idc) {\n\t\tu8 sps_joint_cbcr_enabled_flag = gf_bs_read_int_log(bs, 1, \"sps_joint_cbcr_enabled_flag\");\n\t\tu8 sps_same_qp_table_for_chroma_flag = gf_bs_read_int_log(bs, 1, \"sps_same_qp_table_for_chroma_flag\");\n\t\tu32 numQpTables = sps_same_qp_table_for_chroma_flag ? 1 : (sps_joint_cbcr_enabled_flag ? 3 : 2);\n\t\tfor (i=0; i<numQpTables; i++) {\n\t\t\tgf_bs_read_se_log_idx(bs, \"sps_qp_table_start_minus26\", i);\n\t\t\tu32 j, sps_num_points_in_qp_table = 1 + gf_bs_read_ue_log_idx(bs, \"sps_num_points_in_qp_table_minus1\", i);\n\t\t\tfor (j=0; j<sps_num_points_in_qp_table; j++) {\n\t\t\t\tgf_bs_read_ue_log_idx2(bs, \"sps_delta_qp_in_val_minus1\", i, j);\n\t\t\t\tgf_bs_read_ue_log_idx2(bs, \"sps_delta_qp_diff_val\", i, j);\n\t\t\t}\n\t\t}\n\t}\n\tgf_bs_read_int_log(bs, 1, \"sps_sao_enabled_flag\");\n\tsps->alf_enabled_flag = gf_bs_read_int_log(bs, 1, \"sps_alf_enabled_flag\");\n\tif (sps->alf_enabled_flag && sps->chroma_format_idc) {\n\t\tgf_bs_read_int_log(bs, 1, \"sps_ccalf_enabled_flag\");\n\t}\n\t/*! TODO parse the rest !*/",
"\treturn sps_id;\n}",
"static s32 gf_media_vvc_read_pps_bs_internal(GF_BitStream *bs, VVCState *vvc)\n{\n\tu32 i;\n\ts32 pps_id;\n\tVVC_PPS *pps;",
"\t//NAL header already read\n\tpps_id = gf_bs_read_int_log(bs, 6, \"pps_id\");",
"\tif ((pps_id < 0) || (pps_id >= 64)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] wrong PPS ID %d in PPS\\n\", pps_id));\n\t\treturn -1;\n\t}\n\tpps = &vvc->pps[pps_id];",
"\tif (!pps->state) {\n\t\tpps->id = pps_id;\n\t\tpps->state = 1;\n\t}\n\tpps->sps_id = gf_bs_read_int_log(bs, 4, \"sps_id\");\n\tif (((s32)pps->sps_id<0) || (pps->sps_id >= 16)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] wrong SPS ID %d in PPS\\n\", pps->sps_id));\n\t\tpps->sps_id=0;\n\t\treturn -1;\n\t}\n\tvvc->sps_active_idx = pps->sps_id; /*set active sps*/\n\tpps->mixed_nal_types = gf_bs_read_int_log(bs, 1, \"mixed_nal_types\");\n\tpps->width = gf_bs_read_ue_log(bs, \"width\");\n\tpps->height = gf_bs_read_ue_log(bs, \"height\");\n\tpps->conf_window = gf_bs_read_int_log(bs, 1, \"conformance_window_flag\");\n\tif (pps->conf_window) {\n\t\tpps->cw_left = gf_bs_read_ue_log(bs, \"conf_win_left_offset\");\n\t\tpps->cw_right = gf_bs_read_ue_log(bs, \"conf_win_right_offset\");\n\t\tpps->cw_top = gf_bs_read_ue_log(bs, \"conf_win_top_offset\");\n\t\tpps->cw_bottom = gf_bs_read_ue_log(bs, \"conf_win_bottom_offset\");\n\t}\n\t//scaling window\n\tif (gf_bs_read_int_log(bs, 1, \"scaling_window_explicit_signaling_flag\")) {\n\t\tgf_bs_read_se_log(bs, \"scaling_win_left_offset\");\n\t\tgf_bs_read_se_log(bs, \"scaling_win_right_offset\");\n\t\tgf_bs_read_se_log(bs, \"scaling_win_top_offset\");\n\t\tgf_bs_read_se_log(bs, \"scaling_win_bottom_offset\");\n\t}\n\tpps->output_flag_present_flag = gf_bs_read_int_log(bs, 1, \"output_flag_present_flag\");\n\tpps->no_pic_partition_flag = gf_bs_read_int_log(bs, 1, \"no_pic_partition_flag\");\n\tpps->subpic_id_mapping_present_flag = gf_bs_read_int_log(bs, 1, \"subpic_id_mapping_present_flag\");\n\tif (pps->subpic_id_mapping_present_flag) {\n\t\tu32 pps_subpic_id_len, pps_num_subpics=0;\n\t\tif (!pps->no_pic_partition_flag) {\n\t\t\tpps_num_subpics = 1+gf_bs_read_ue_log(bs, \"pps_num_subpics_minus1\");\n\t\t}\n\t\tpps_subpic_id_len = 1 + gf_bs_read_ue(bs);\n\t\tfor (i=0; i<pps_num_subpics; i++) {\n\t\t\tgf_bs_read_int_log_idx(bs, pps_subpic_id_len, \"subpic_id\", i);\n\t\t}\n\t}\n\tif (!pps->no_pic_partition_flag) {\n\t\tgf_bs_read_int_log(bs, 2, \"pps_log2_ctu_size_minus5\");\n\t\tu32 num_exp_tile_columns = 1 + gf_bs_read_ue_log(bs, \"num_exp_tile_columns_minus1\");\n\t\tu32 num_exp_tile_rows = 1 + gf_bs_read_ue_log(bs, \"num_exp_tile_rows_minus1\");\n\t\tfor (i=0; i<num_exp_tile_columns; i++)\n\t\t\tgf_bs_read_ue_log_idx(bs, \"tile_column_width_minus1\", i);\n\t\tfor (i=0; i<num_exp_tile_rows; i++)\n\t\t\tgf_bs_read_ue_log_idx(bs, \"tile_row_height_minus1\", i);",
"\t\t//todo parse the rest\n\t\treturn pps_id;\n\t}",
"\n\t//todo parse the rest",
"\treturn pps_id;\n}",
"static\ns32 vvc_parse_picture_header(GF_BitStream *bs, VVCState *vvc, VVCSliceInfo *si)\n{\n\ts32 pps_id;",
"\tsi->irap_or_gdr_pic = gf_bs_read_int_log(bs, 1, \"irap_or_gdr_pic\");\n\tsi->non_ref_pic = gf_bs_read_int_log(bs, 1, \"non_ref_pic\");\n\tif (si->irap_or_gdr_pic)\n\t\tsi->gdr_pic = gf_bs_read_int_log(bs, 1, \"gdr_pic\");\n\tif ((si->inter_slice_allowed_flag = gf_bs_read_int_log(bs, 1, \"inter_slice_allowed_flag\")))\n\t\tsi->intra_slice_allowed_flag = gf_bs_read_int_log(bs, 1, \"intra_slice_allowed_flag\");",
"\tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n\tif ((pps_id<0) || (pps_id >= 64))\n\t\treturn -1;\n\tsi->pps = &vvc->pps[pps_id];\n\tsi->sps = &vvc->sps[si->pps->sps_id];\n\tsi->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, \"poc_lsb\");",
"\tsi->recovery_point_valid = 0;\n\tsi->gdr_recovery_count = 0;\n\tif (si->gdr_pic) {\n\t\tsi->recovery_point_valid = 1;\n\t\tsi->gdr_recovery_count = gf_bs_read_ue_log(bs, \"gdr_recovery_count\");\n\t}\n\tgf_bs_read_int_log(bs, si->sps->ph_num_extra_bits, \"ph_extra_bits\");",
"\tif (si->sps->poc_msb_cycle_flag) {\n\t\tif ( (si->poc_msb_cycle_present_flag = gf_bs_read_int_log(bs, 1, \"poc_msb_cycle_present_flag\"))) {\n\t\t\tsi->poc_msb_cycle = gf_bs_read_int_log(bs, si->sps->poc_msb_cycle_len, \"poc_msb_cycle\");\n\t\t}\n\t}",
"\treturn 0;\n}",
"static s32 vvc_parse_slice(GF_BitStream *bs, VVCState *vvc, VVCSliceInfo *si)\n{\n//\tu32 CurrSubpicIdx = 0;",
"\tsi->picture_header_in_slice_header_flag = gf_bs_read_int_log(bs, 1, \"picture_header_in_slice_header_flag\");\n\tif (si->picture_header_in_slice_header_flag) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CODING, (\"[VVC] Picture header in slice header incomplete support, cannot guess slice type\\n\"));\n\t\tsi->slice_type = GF_VVC_SLICE_TYPE_UNKNOWN;\n\t\treturn vvc_parse_picture_header(bs, vvc, si);\n\t}\n\tif (!si->sps) return -1;\n\tsi->slice_type = GF_VVC_SLICE_TYPE_I;\n\tif (gf_bs_read_int_log(bs, 1, \"sps_subpic_info_present_flag\")) {\n\t\tgf_bs_read_int_log(bs, si->sps->subpicid_len, \"subpic_id\");\n\t\t//todo update CurrSubpicIdx\n\t}",
"\tif (si->pps->rect_slice_flag ) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[VVC] tiling parsing not supported - patch welcome\\n\"));\n\t\treturn 0;\n\t}\n\tgf_bs_read_int_log(bs, si->sps->sh_num_extra_bits, \"num_extra_bits\");\n\t/*\n\t\tif( !pps_rect_slice_flag && NumTilesInPic − sh_slice_address > 1 )\n\t\tsh_num_tiles_in_slice_minus1",
"\t */",
"\tif (si->inter_slice_allowed_flag )\n\t\tsi->slice_type = gf_bs_read_int_log(bs, 2, \"slice_type\");",
"\treturn 0;\n}",
"static void vvc_compute_poc(VVCSliceInfo *si)\n{\n\tu32 max_poc_lsb = 1 << (si->sps->log2_max_poc_lsb);",
"\tif (si->poc_msb_cycle_present_flag) {\n\t\tsi->poc_msb = si->poc_msb_cycle;\n\t} else {\n\t\tif ((si->poc_lsb < si->poc_lsb_prev) && (si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2))\n\t\t\tsi->poc_msb = si->poc_msb_prev + max_poc_lsb;\n\t\telse if ((si->poc_lsb > si->poc_lsb_prev) && (si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))\n\t\t\tsi->poc_msb = si->poc_msb_prev - max_poc_lsb;\n\t\telse\n\t\t\tsi->poc_msb = si->poc_msb_prev;\n\t}",
"\tsi->poc = si->poc_msb + si->poc_lsb;\n}",
"\nGF_EXPORT\ns32 gf_media_vvc_parse_nalu_bs(GF_BitStream *bs, VVCState *vvc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tBool is_slice = GF_FALSE;\n\ts32 ret = -1;\n\tBool poc_reset = GF_FALSE;\n\tVVCSliceInfo n_state;",
"\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tmemcpy(&n_state, &vvc->s_info, sizeof(VVCSliceInfo));\n\tif (!vvc_parse_nal_header(bs, nal_unit_type, temporal_id, layer_id)) return -1;",
"\tn_state.nal_unit_type = *nal_unit_type;",
"\tswitch (n_state.nal_unit_type) {\n\tcase GF_VVC_NALU_ACCESS_UNIT:\n\tcase GF_VVC_NALU_END_OF_SEQ:\n\tcase GF_VVC_NALU_END_OF_STREAM:\n\t\tret = 1;\n\t\tbreak;",
"\tcase GF_VVC_NALU_SLICE_IDR_W_RADL:\n\tcase GF_VVC_NALU_SLICE_IDR_N_LP:\n\t\tpoc_reset = GF_TRUE;\n\tcase GF_VVC_NALU_SLICE_TRAIL:\n\tcase GF_VVC_NALU_SLICE_STSA:\n\tcase GF_VVC_NALU_SLICE_RADL:\n\tcase GF_VVC_NALU_SLICE_RASL:\n\tcase GF_VVC_NALU_SLICE_CRA:\n\tcase GF_VVC_NALU_SLICE_GDR:\n\t\t/* slice - read the info and compare.*/\n\t\tret = vvc_parse_slice(bs, vvc, &n_state);\n\t\tif (ret < 0) return ret;",
"\t\tret = 0;\n\t\tif (n_state.compute_poc_defer || n_state.picture_header_in_slice_header_flag) {\n\t\t\tis_slice = GF_TRUE;\n\t\t\tn_state.compute_poc_defer = 0;\n\t\t\tif (poc_reset) {\n\t\t\t\tn_state.poc_lsb_prev = 0;\n\t\t\t\tn_state.poc_msb_prev = 0;\n\t\t\t}",
"\t\t\tvvc_compute_poc(&n_state);\n\t\t\tif (vvc->s_info.poc != n_state.poc) {\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!(*layer_id) || (n_state.prev_layer_id_plus1 && ((*layer_id) <= n_state.prev_layer_id_plus1 - 1))) {\n\t\t\t\tret = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;",
"\tcase GF_VVC_NALU_PIC_HEADER:\n\t\tif (vvc_parse_picture_header(bs, vvc, &n_state)<0) {\n\t\t\tret = -1;\n\t\t\tbreak;\n\t\t}\n\t\tis_slice = GF_TRUE;",
"\t\t/*POC reset for IDR frames, NOT for CRA*/\n\t\tif (n_state.irap_or_gdr_pic && !n_state.gdr_pic) {\n\t\t\tn_state.poc_lsb_prev = 0;\n\t\t\tn_state.poc_msb_prev = 0;\n\t\t\tvvc_compute_poc(&n_state);\n\t\t} else {\n\t\t\t//we cannot compute poc until we know the first picture unit type, since IDR will reset poc count\n\t\t\t//and irap_or_gdr_pic=0 does not prevent IDR from following\n\t\t\tn_state.compute_poc_defer = 1;\n\t\t}",
"\t\tif (!(*layer_id) || (n_state.prev_layer_id_plus1 && ((*layer_id) <= n_state.prev_layer_id_plus1 - 1))) {\n\t\t\tret = 1;\n\t\t}\n\t\tbreak;\n\tcase GF_VVC_NALU_SEQ_PARAM:\n\t\tvvc->last_parsed_sps_id = gf_media_vvc_read_sps_bs_internal(bs, vvc, *layer_id, NULL);\n\t\tret = (vvc->last_parsed_sps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tcase GF_VVC_NALU_PIC_PARAM:\n\t\tvvc->last_parsed_pps_id = gf_media_vvc_read_pps_bs_internal(bs, vvc);\n\t\tret = (vvc->last_parsed_pps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tcase GF_VVC_NALU_VID_PARAM:\n\t\tvvc->last_parsed_vps_id = gf_media_vvc_read_vps_bs_internal(bs, vvc, GF_FALSE);\n\t\tret = (vvc->last_parsed_vps_id>=0) ? 0 : -1;\n\t\tbreak;\n\tcase GF_VVC_NALU_DEC_PARAM:\n\t\tret = 0;\n\t\tbreak;\n\tcase GF_VVC_NALU_APS_PREFIX:\n\t\t//we use the mix aps type + aps id (first 8 bits) as unique identifier\n\t\tvvc->last_parsed_aps_id = gf_bs_read_int_log(bs, 8, \"aps_id\");\n\t\tret = 0;\n\t\tbreak;\n\tdefault:\n\t\tret = 0;\n\t\tbreak;\n\t}",
"\t/* save _prev values */\n\tif ((ret>0) && vvc->s_info.sps) {\n//\t\tn_state.frame_num_offset_prev = vvc->s_info.frame_num_offset;\n//\t\tn_state.frame_num_prev = vvc->s_info.frame_num;",
"\t\tn_state.poc_lsb_prev = vvc->s_info.poc_lsb;\n\t\tn_state.poc_msb_prev = vvc->s_info.poc_msb;\n\t\tif (is_slice)\n\t\t\tn_state.prev_layer_id_plus1 = *layer_id + 1;\n\t}",
"\tmemcpy(&vvc->s_info, &n_state, sizeof(VVCSliceInfo));",
"\treturn ret;\n}",
"GF_EXPORT\ns32 gf_media_vvc_parse_nalu(u8 *data, u32 size, VVCState *vvc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)\n{\n\tGF_BitStream *bs = NULL;\n\ts32 ret;",
"\tif (!vvc) {\n\t\tif (nal_unit_type) (*nal_unit_type) = data[1] >> 3;\n\t\tif (layer_id) (*layer_id) = data[0] & 0x3f;\n\t\tif (temporal_id) (*temporal_id) = (data[1] & 0x7);\n\t\treturn -1;\n\t}\n\tbs = gf_bs_new(data, size, GF_BITSTREAM_READ);\n\tif (!bs) return -1;\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);",
"\tret = gf_media_vvc_parse_nalu_bs(bs, vvc, nal_unit_type, temporal_id, layer_id);\n\tgf_bs_del(bs);\n\treturn ret;\n}",
"Bool gf_media_vvc_slice_is_ref(VVCState *vvc)\n{\n\tif (!vvc->s_info.irap_or_gdr_pic) {\n\t\treturn GF_FALSE;\n\t}\n\tif (vvc->s_info.gdr_pic) {\n\t\tif (vvc->s_info.recovery_point_valid) {\n\t\t\tvvc->s_info.recovery_point_valid = 0;\n\t\t\treturn GF_TRUE;\n\t\t}\n\t\treturn GF_FALSE;\n\t}\n\treturn GF_TRUE;\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [5789], "buggy_code_start_loc": [4693], "filenames": ["src/media_tools/av_parsers.c"], "fixing_code_end_loc": [5792], "fixing_code_start_loc": [4693], "message": "A buffer overflow vulnerability exists in Gpac through 1.0.1 via a malformed MP4 file in the svc_parse_slice function in av_parsers.c, which allows attackers to cause a denial of service, even code execution and escalation of privileges.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gpac:gpac:*:*:*:*:*:*:*:*", "matchCriteriaId": "72EEF01B-F945-4AEF-B5C2-6F84A51311C9", "versionEndExcluding": null, "versionEndIncluding": "1.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A buffer overflow vulnerability exists in Gpac through 1.0.1 via a malformed MP4 file in the svc_parse_slice function in av_parsers.c, which allows attackers to cause a denial of service, even code execution and escalation of privileges."}, {"lang": "es", "value": "es presentado una vulnerabilidad de desbordamiento de b\u00fafer en Gpac versiones hasta 1.0.1 por medio de un archivo MP4 malformado en la funci\u00f3n svc_parse_slice en el archivo av_parsers.c, que permite a atacantes causar una denegaci\u00f3n de servicio, incluso ejecuci\u00f3n de c\u00f3digo y escalada de privilegios"}], "evaluatorComment": null, "id": "CVE-2021-40568", "lastModified": "2023-05-27T04:15:16.660", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-01-13T18:15:07.977", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/commit/f1ae01d745200a258cdf62622f71754c37cb6c30"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/issues/1900"}, {"source": "cve@mitre.org", "tags": null, "url": "https://www.debian.org/security/2023/dsa-5411"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-120"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gpac/gpac/commit/f1ae01d745200a258cdf62622f71754c37cb6c30"}, "type": "CWE-120"}
| 246
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"# -*- coding: utf-8 -*-\n# (c) 2009-2022 Martin Wendt and contributors; see WsgiDAV https://github.com/mar10/wsgidav\n# Licensed under the MIT license:\n# http://www.opensource.org/licenses/mit-license.php\n\"\"\"\nWSGI middleware that handles GET requests on collections to display directories.\n\"\"\"\nimport os\nimport sys\nfrom fnmatch import fnmatch\nfrom urllib.parse import unquote\n",
"from jinja2 import Environment, FileSystemLoader",
"\nfrom wsgidav import __version__, util\nfrom wsgidav.dav_error import HTTP_MEDIATYPE_NOT_SUPPORTED, HTTP_OK, DAVError\nfrom wsgidav.mw.base_mw import BaseMiddleware\nfrom wsgidav.util import get_uri_name, safe_re_encode, send_redirect_response",
"__docformat__ = \"reStructuredText\"",
"_logger = util.get_module_logger(__name__)",
"ASSET_SHARE = \"/:dir_browser\"",
"DAVMOUNT_TEMPLATE = \"\"\"\n<dm:mount xmlns:dm=\"http://purl.org/NET/webdav/mount\">\n <dm:url>{}</dm:url>\n</dm:mount>\n\"\"\".strip()",
"MS_OFFICE_TYPE_TO_EXT_MAP = {\n \"excel\": (\"xls\", \"xlt\", \"xlm\", \"xlsm\", \"xlsx\", \"xltm\", \"xltx\"),\n \"powerpoint\": (\"pps\", \"ppt\", \"pptm\", \"pptx\", \"potm\", \"potx\", \"ppsm\", \"ppsx\"),\n \"word\": (\"doc\", \"dot\", \"docm\", \"docx\", \"dotm\", \"dotx\"),\n \"visio\": (\"vsd\", \"vsdm\", \"vsdx\", \"vstm\", \"vstx\"),\n}\nMS_OFFICE_EXT_TO_TYPE_MAP = {}\nfor t, el in MS_OFFICE_TYPE_TO_EXT_MAP.items():\n for e in el:\n MS_OFFICE_EXT_TO_TYPE_MAP[e] = t\nOPEN_OFFICE_EXTENSIONS = {\"odt\", \"odp\", \"odx\"}",
"\nclass WsgiDavDirBrowser(BaseMiddleware):\n \"\"\"WSGI middleware that handles GET requests on collections to display directories.\"\"\"",
" def __init__(self, wsgidav_app, next_app, config):\n super().__init__(wsgidav_app, next_app, config)",
" self.dir_config = util.get_dict_value(config, \"dir_browser\", as_dict=True)",
" # mount path must be \"\" or start (but not end) with '/'\n self.mount_path = config.get(\"mount_path\") or \"\"",
" htdocs_path = self.dir_config.get(\"htdocs_path\")\n if htdocs_path:\n self.htdocs_path = os.path.realpath(htdocs_path)\n else:\n self.htdocs_path = os.path.join(os.path.dirname(__file__), \"htdocs\")",
" if not os.path.isdir(self.htdocs_path):\n raise ValueError(\n \"Invalid dir_browser htdocs_path {!r}\".format(self.htdocs_path)\n )",
" # Add an additional read-only FS provider that serves the dir_browser assets\n self.wsgidav_app.add_provider(ASSET_SHARE, self.htdocs_path, readonly=True)\n # and make sure we have anonymous access there\n config.get(\"simple_dc\", {}).get(\"user_mapping\", {}).setdefault(\n ASSET_SHARE, True\n )",
" # Prepare a Jinja2 template\n templateLoader = FileSystemLoader(searchpath=self.htdocs_path)",
" templateEnv = Environment(loader=templateLoader)",
" self.template = templateEnv.get_template(\"template.html\")",
" def is_disabled(self):\n return self.dir_config.get(\"enable\") is False",
" def __call__(self, environ, start_response):\n path = environ[\"PATH_INFO\"]",
" dav_res = None\n if environ[\"wsgidav.provider\"]:\n dav_res = environ[\"wsgidav.provider\"].get_resource_inst(path, environ)",
" if (\n environ[\"REQUEST_METHOD\"] in (\"GET\", \"HEAD\")\n and dav_res\n and dav_res.is_collection\n ):",
" if util.get_content_length(environ) != 0:\n self._fail(\n HTTP_MEDIATYPE_NOT_SUPPORTED,\n \"The server does not handle any body content.\",\n )",
" if environ[\"REQUEST_METHOD\"] == \"HEAD\":\n return util.send_status_response(\n environ, start_response, HTTP_OK, is_head=True\n )",
" # Support DAV mount (http://www.ietf.org/rfc/rfc4709.txt)\n if self.dir_config.get(\"davmount\") and \"davmount\" in environ.get(\n \"QUERY_STRING\", \"\"\n ):\n collectionUrl = util.make_complete_url(environ)\n collectionUrl = collectionUrl.split(\"?\", 1)[0]\n res = util.to_bytes(DAVMOUNT_TEMPLATE.format(collectionUrl))\n # TODO: support <dm:open>%s</dm:open>",
" start_response(\n \"200 OK\",\n [\n (\"Content-Type\", \"application/davmount+xml\"),\n (\"Content-Length\", str(len(res))),\n (\"Cache-Control\", \"private\"),\n (\"Date\", util.get_rfc1123_time()),\n ],\n )\n return [res]",
" directory_slash = self.dir_config.get(\"directory_slash\")\n requrest_uri = environ.get(\"REQUEST_URI\")\n if directory_slash and requrest_uri and not requrest_uri.endswith(\"/\"):\n _logger.info(f\"Redirect {requrest_uri} to {requrest_uri}/\")\n return send_redirect_response(\n environ, start_response, location=requrest_uri + \"/\"\n )",
" context = self._get_context(environ, dav_res)",
" res = self.template.render(**context)\n res = util.to_bytes(res)\n start_response(\n \"200 OK\",\n [\n (\"Content-Type\", \"text/html; charset=utf-8\"),\n (\"Content-Length\", str(len(res))),\n (\"Cache-Control\", \"private\"),\n (\"Date\", util.get_rfc1123_time()),\n ],\n )\n return [res]",
" return self.next_app(environ, start_response)",
" def _fail(self, value, context_info=None, src_exception=None, err_condition=None):\n \"\"\"Wrapper to raise (and log) DAVError.\"\"\"\n e = DAVError(value, context_info, src_exception, err_condition)\n if self.verbose >= 4:\n _logger.warning(\n \"Raising DAVError {}\".format(\n safe_re_encode(e.get_user_info(), sys.stdout.encoding)\n )\n )\n raise e",
" def _get_context(self, environ, dav_res):\n \"\"\"\n @see: http://www.webdav.org/specs/rfc4918.html#rfc.section.9.4\n \"\"\"\n assert dav_res.is_collection",
" is_readonly = environ[\"wsgidav.provider\"].is_readonly()\n ms_sharepoint_support = self.dir_config.get(\"ms_sharepoint_support\")\n libre_office_support = self.dir_config.get(\"libre_office_support\")\n is_top_dir = dav_res.path in (\"\", \"/\")",
" # TODO: WebDAV URLs only on Windows?\n # TODO: WebDAV URLs only on HTTPS?\n # is_windows = \"Windows NT \" in environ.get(\"HTTP_USER_AGENT\", \"\")",
" context = {\n \"htdocs\": self.mount_path + ASSET_SHARE,\n \"rows\": [],\n \"version\": __version__,\n \"display_path\": unquote(dav_res.get_href()),\n \"url\": dav_res.get_href(), # util.make_complete_url(environ),\n # \"parent_url\": util.get_uri_parent(dav_res.get_href()),\n \"is_top_dir\": is_top_dir,\n \"config\": self.dir_config,\n \"is_readonly\": is_readonly,\n \"access\": \"read-only\" if is_readonly else \"read-write\",\n \"is_authenticated\": False,\n }",
" trailer = self.dir_config.get(\"response_trailer\")\n if trailer is True:\n trailer = \"${version} - ${time}\"",
" if trailer:\n trailer = trailer.replace(\n \"${version}\",\n f\"<a href='https://github.com/mar10/wsgidav/'>WsgiDAV/{__version__}</a>\",\n )\n trailer = trailer.replace(\"${time}\", util.get_rfc1123_time())",
" context[\"trailer\"] = trailer",
" rows = context[\"rows\"]",
" # Ask collection for member info list\n dirInfoList = dav_res.get_directory_info()",
" if dirInfoList is None:\n # No pre-build info: traverse members\n dirInfoList = []\n childList = dav_res.get_descendants(depth=\"1\", add_self=False)\n for res in childList:\n di = res.get_display_info()\n href = res.get_href()\n ofe_prefix = None\n tr_classes = []\n a_classes = []",
" # #268 Use relative paths to support reverse proxies:\n rel_href = get_uri_name(href)\n if res.is_collection:\n tr_classes.append(\"directory\")\n rel_href = f\"./{rel_href}/\" # 274",
" add_link_html = []",
" if not is_readonly and not res.is_collection:\n ext = os.path.splitext(href)[1].lstrip(\".\").lower()\n ms_office_type = MS_OFFICE_EXT_TO_TYPE_MAP.get(ext)\n if ms_office_type:\n if ms_sharepoint_support:\n ofe_prefix = f\"ms-{ms_office_type}:ofe|u|\"\n a_classes.append(\"msoffice\")\n if libre_office_support:\n add_link_html.append(\n f\"<a class='edit2' title='Edit with Libre Office' href='vnd.libreoffice.command:ofv|u|{rel_href}'>Edit</a>\"\n )\n # ofe_prefix_2 = \"vnd.libreoffice.command:ofv|u|\"\n # a_classes.append(\"msoffice\")\n elif libre_office_support:\n ofe_prefix = \"vnd.libreoffice.command:ofv|u|\"\n # a_classes.append(\"msoffice\")",
" elif ext in OPEN_OFFICE_EXTENSIONS:\n if libre_office_support:\n ofe_prefix = \"vnd.libreoffice.command:ofv|u|\"\n a_classes.append(\"msoffice\")",
" entry = {\n \"href\": rel_href,\n \"ofe_prefix\": ofe_prefix,\n \"a_class\": \" \".join(a_classes),\n \"add_link_html\": \"\".join(add_link_html),\n \"tr_class\": \" \".join(tr_classes),\n \"display_name\": res.get_display_name(),\n \"last_modified\": res.get_last_modified(),\n \"is_collection\": res.is_collection,\n \"content_length\": res.get_content_length(),\n \"display_type\": di.get(\"type\"),\n \"display_type_comment\": di.get(\"typeComment\"),\n }",
" dirInfoList.append(entry)\n #\n ignore_patterns = self.dir_config.get(\"ignore\", [])\n if util.is_basestring(ignore_patterns):\n ignore_patterns = ignore_patterns.split(\",\")",
" ignored_list = []\n for entry in dirInfoList:\n # Skip ignore patterns\n ignore = False\n for pat in ignore_patterns:\n if fnmatch(entry[\"display_name\"], pat):\n ignored_list.append(entry[\"display_name\"])\n # _logger.debug(\"Ignore {}\".format(entry[\"display_name\"]))\n ignore = True\n break\n if ignore:\n continue\n #\n last_modified = entry.get(\"last_modified\")\n if last_modified is None:\n entry[\"str_modified\"] = \"\"\n else:\n entry[\"str_modified\"] = util.get_rfc1123_time(last_modified)",
" entry[\"str_size\"] = \"-\"\n if not entry.get(\"is_collection\"):\n content_length = entry.get(\"content_length\")\n if content_length is not None:\n entry[\"str_size\"] = util.byte_number_string(content_length)",
" rows.append(entry)\n if ignored_list:\n _logger.debug(\n \"Dir browser ignored {} entries: {}\".format(\n len(ignored_list), ignored_list\n )\n )",
" # sort\n sort = \"name\"\n if sort == \"name\":\n rows.sort(\n key=lambda v: \"{}{}\".format(\n not v[\"is_collection\"], v[\"display_name\"].lower()\n )\n )",
" if \"wsgidav.auth.user_name\" in environ:\n context.update(\n {\n \"is_authenticated\": bool(environ.get(\"wsgidav.auth.user_name\")),\n \"user_name\": (environ.get(\"wsgidav.auth.user_name\") or \"anonymous\"),\n \"realm\": environ.get(\"wsgidav.auth.realm\"),\n \"user_roles\": \", \".join(environ.get(\"wsgidav.auth.roles\") or []),\n \"user_permissions\": \", \".join(\n environ.get(\"wsgidav.auth.permissions\") or []\n ),\n }\n )",
" return context"
] |
[
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [77, 99], "buggy_code_start_loc": [13, 84], "filenames": ["wsgidav/dir_browser/_dir_browser.py", "wsgidav/dir_browser/htdocs/template.html"], "fixing_code_end_loc": [77, 99], "fixing_code_start_loc": [13, 84], "message": "WsgiDAV is a generic and extendable WebDAV server based on WSGI. Implementations using this library with directory browsing enabled may be susceptible to Cross Site Scripting (XSS) attacks. This issue has been patched, users can upgrade to version 4.1.0. As a workaround, set `dir_browser.enable = False` in the configuration.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wsgidav_project:wsgidav:*:*:*:*:*:*:*:*", "matchCriteriaId": "A13F7E6A-3839-4247-ACA6-4544D45534CA", "versionEndExcluding": "4.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WsgiDAV is a generic and extendable WebDAV server based on WSGI. Implementations using this library with directory browsing enabled may be susceptible to Cross Site Scripting (XSS) attacks. This issue has been patched, users can upgrade to version 4.1.0. As a workaround, set `dir_browser.enable = False` in the configuration."}], "evaluatorComment": null, "id": "CVE-2022-41905", "lastModified": "2022-11-16T18:10:41.607", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 8.2, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-11-11T21:15:09.743", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mar10/wsgidav/commit/e9606ab0f42f4c1a6611bc3c52de299b0aba7726"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/mar10/wsgidav/security/advisories/GHSA-xx6g-jj35-pxjv"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mar10/wsgidav/commit/e9606ab0f42f4c1a6611bc3c52de299b0aba7726"}, "type": "CWE-79"}
| 247
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"# -*- coding: utf-8 -*-\n# (c) 2009-2022 Martin Wendt and contributors; see WsgiDAV https://github.com/mar10/wsgidav\n# Licensed under the MIT license:\n# http://www.opensource.org/licenses/mit-license.php\n\"\"\"\nWSGI middleware that handles GET requests on collections to display directories.\n\"\"\"\nimport os\nimport sys\nfrom fnmatch import fnmatch\nfrom urllib.parse import unquote\n",
"from jinja2 import Environment, FileSystemLoader, select_autoescape",
"\nfrom wsgidav import __version__, util\nfrom wsgidav.dav_error import HTTP_MEDIATYPE_NOT_SUPPORTED, HTTP_OK, DAVError\nfrom wsgidav.mw.base_mw import BaseMiddleware\nfrom wsgidav.util import get_uri_name, safe_re_encode, send_redirect_response",
"__docformat__ = \"reStructuredText\"",
"_logger = util.get_module_logger(__name__)",
"ASSET_SHARE = \"/:dir_browser\"",
"DAVMOUNT_TEMPLATE = \"\"\"\n<dm:mount xmlns:dm=\"http://purl.org/NET/webdav/mount\">\n <dm:url>{}</dm:url>\n</dm:mount>\n\"\"\".strip()",
"MS_OFFICE_TYPE_TO_EXT_MAP = {\n \"excel\": (\"xls\", \"xlt\", \"xlm\", \"xlsm\", \"xlsx\", \"xltm\", \"xltx\"),\n \"powerpoint\": (\"pps\", \"ppt\", \"pptm\", \"pptx\", \"potm\", \"potx\", \"ppsm\", \"ppsx\"),\n \"word\": (\"doc\", \"dot\", \"docm\", \"docx\", \"dotm\", \"dotx\"),\n \"visio\": (\"vsd\", \"vsdm\", \"vsdx\", \"vstm\", \"vstx\"),\n}\nMS_OFFICE_EXT_TO_TYPE_MAP = {}\nfor t, el in MS_OFFICE_TYPE_TO_EXT_MAP.items():\n for e in el:\n MS_OFFICE_EXT_TO_TYPE_MAP[e] = t\nOPEN_OFFICE_EXTENSIONS = {\"odt\", \"odp\", \"odx\"}",
"\nclass WsgiDavDirBrowser(BaseMiddleware):\n \"\"\"WSGI middleware that handles GET requests on collections to display directories.\"\"\"",
" def __init__(self, wsgidav_app, next_app, config):\n super().__init__(wsgidav_app, next_app, config)",
" self.dir_config = util.get_dict_value(config, \"dir_browser\", as_dict=True)",
" # mount path must be \"\" or start (but not end) with '/'\n self.mount_path = config.get(\"mount_path\") or \"\"",
" htdocs_path = self.dir_config.get(\"htdocs_path\")\n if htdocs_path:\n self.htdocs_path = os.path.realpath(htdocs_path)\n else:\n self.htdocs_path = os.path.join(os.path.dirname(__file__), \"htdocs\")",
" if not os.path.isdir(self.htdocs_path):\n raise ValueError(\n \"Invalid dir_browser htdocs_path {!r}\".format(self.htdocs_path)\n )",
" # Add an additional read-only FS provider that serves the dir_browser assets\n self.wsgidav_app.add_provider(ASSET_SHARE, self.htdocs_path, readonly=True)\n # and make sure we have anonymous access there\n config.get(\"simple_dc\", {}).get(\"user_mapping\", {}).setdefault(\n ASSET_SHARE, True\n )",
" # Prepare a Jinja2 template\n templateLoader = FileSystemLoader(searchpath=self.htdocs_path)",
" templateEnv = Environment(loader=templateLoader, autoescape=select_autoescape())",
" self.template = templateEnv.get_template(\"template.html\")",
" def is_disabled(self):\n return self.dir_config.get(\"enable\") is False",
" def __call__(self, environ, start_response):\n path = environ[\"PATH_INFO\"]",
" dav_res = None\n if environ[\"wsgidav.provider\"]:\n dav_res = environ[\"wsgidav.provider\"].get_resource_inst(path, environ)",
" if (\n environ[\"REQUEST_METHOD\"] in (\"GET\", \"HEAD\")\n and dav_res\n and dav_res.is_collection\n ):",
" if util.get_content_length(environ) != 0:\n self._fail(\n HTTP_MEDIATYPE_NOT_SUPPORTED,\n \"The server does not handle any body content.\",\n )",
" if environ[\"REQUEST_METHOD\"] == \"HEAD\":\n return util.send_status_response(\n environ, start_response, HTTP_OK, is_head=True\n )",
" # Support DAV mount (http://www.ietf.org/rfc/rfc4709.txt)\n if self.dir_config.get(\"davmount\") and \"davmount\" in environ.get(\n \"QUERY_STRING\", \"\"\n ):\n collectionUrl = util.make_complete_url(environ)\n collectionUrl = collectionUrl.split(\"?\", 1)[0]\n res = util.to_bytes(DAVMOUNT_TEMPLATE.format(collectionUrl))\n # TODO: support <dm:open>%s</dm:open>",
" start_response(\n \"200 OK\",\n [\n (\"Content-Type\", \"application/davmount+xml\"),\n (\"Content-Length\", str(len(res))),\n (\"Cache-Control\", \"private\"),\n (\"Date\", util.get_rfc1123_time()),\n ],\n )\n return [res]",
" directory_slash = self.dir_config.get(\"directory_slash\")\n requrest_uri = environ.get(\"REQUEST_URI\")\n if directory_slash and requrest_uri and not requrest_uri.endswith(\"/\"):\n _logger.info(f\"Redirect {requrest_uri} to {requrest_uri}/\")\n return send_redirect_response(\n environ, start_response, location=requrest_uri + \"/\"\n )",
" context = self._get_context(environ, dav_res)",
" res = self.template.render(**context)\n res = util.to_bytes(res)\n start_response(\n \"200 OK\",\n [\n (\"Content-Type\", \"text/html; charset=utf-8\"),\n (\"Content-Length\", str(len(res))),\n (\"Cache-Control\", \"private\"),\n (\"Date\", util.get_rfc1123_time()),\n ],\n )\n return [res]",
" return self.next_app(environ, start_response)",
" def _fail(self, value, context_info=None, src_exception=None, err_condition=None):\n \"\"\"Wrapper to raise (and log) DAVError.\"\"\"\n e = DAVError(value, context_info, src_exception, err_condition)\n if self.verbose >= 4:\n _logger.warning(\n \"Raising DAVError {}\".format(\n safe_re_encode(e.get_user_info(), sys.stdout.encoding)\n )\n )\n raise e",
" def _get_context(self, environ, dav_res):\n \"\"\"\n @see: http://www.webdav.org/specs/rfc4918.html#rfc.section.9.4\n \"\"\"\n assert dav_res.is_collection",
" is_readonly = environ[\"wsgidav.provider\"].is_readonly()\n ms_sharepoint_support = self.dir_config.get(\"ms_sharepoint_support\")\n libre_office_support = self.dir_config.get(\"libre_office_support\")\n is_top_dir = dav_res.path in (\"\", \"/\")",
" # TODO: WebDAV URLs only on Windows?\n # TODO: WebDAV URLs only on HTTPS?\n # is_windows = \"Windows NT \" in environ.get(\"HTTP_USER_AGENT\", \"\")",
" context = {\n \"htdocs\": self.mount_path + ASSET_SHARE,\n \"rows\": [],\n \"version\": __version__,\n \"display_path\": unquote(dav_res.get_href()),\n \"url\": dav_res.get_href(), # util.make_complete_url(environ),\n # \"parent_url\": util.get_uri_parent(dav_res.get_href()),\n \"is_top_dir\": is_top_dir,\n \"config\": self.dir_config,\n \"is_readonly\": is_readonly,\n \"access\": \"read-only\" if is_readonly else \"read-write\",\n \"is_authenticated\": False,\n }",
" trailer = self.dir_config.get(\"response_trailer\")\n if trailer is True:\n trailer = \"${version} - ${time}\"",
" if trailer:\n trailer = trailer.replace(\n \"${version}\",\n f\"<a href='https://github.com/mar10/wsgidav/'>WsgiDAV/{__version__}</a>\",\n )\n trailer = trailer.replace(\"${time}\", util.get_rfc1123_time())",
" context[\"trailer\"] = trailer",
" rows = context[\"rows\"]",
" # Ask collection for member info list\n dirInfoList = dav_res.get_directory_info()",
" if dirInfoList is None:\n # No pre-build info: traverse members\n dirInfoList = []\n childList = dav_res.get_descendants(depth=\"1\", add_self=False)\n for res in childList:\n di = res.get_display_info()\n href = res.get_href()\n ofe_prefix = None\n tr_classes = []\n a_classes = []",
" # #268 Use relative paths to support reverse proxies:\n rel_href = get_uri_name(href)\n if res.is_collection:\n tr_classes.append(\"directory\")\n rel_href = f\"./{rel_href}/\" # 274",
" add_link_html = []",
" if not is_readonly and not res.is_collection:\n ext = os.path.splitext(href)[1].lstrip(\".\").lower()\n ms_office_type = MS_OFFICE_EXT_TO_TYPE_MAP.get(ext)\n if ms_office_type:\n if ms_sharepoint_support:\n ofe_prefix = f\"ms-{ms_office_type}:ofe|u|\"\n a_classes.append(\"msoffice\")\n if libre_office_support:\n add_link_html.append(\n f\"<a class='edit2' title='Edit with Libre Office' href='vnd.libreoffice.command:ofv|u|{rel_href}'>Edit</a>\"\n )\n # ofe_prefix_2 = \"vnd.libreoffice.command:ofv|u|\"\n # a_classes.append(\"msoffice\")\n elif libre_office_support:\n ofe_prefix = \"vnd.libreoffice.command:ofv|u|\"\n # a_classes.append(\"msoffice\")",
" elif ext in OPEN_OFFICE_EXTENSIONS:\n if libre_office_support:\n ofe_prefix = \"vnd.libreoffice.command:ofv|u|\"\n a_classes.append(\"msoffice\")",
" entry = {\n \"href\": rel_href,\n \"ofe_prefix\": ofe_prefix,\n \"a_class\": \" \".join(a_classes),\n \"add_link_html\": \"\".join(add_link_html),\n \"tr_class\": \" \".join(tr_classes),\n \"display_name\": res.get_display_name(),\n \"last_modified\": res.get_last_modified(),\n \"is_collection\": res.is_collection,\n \"content_length\": res.get_content_length(),\n \"display_type\": di.get(\"type\"),\n \"display_type_comment\": di.get(\"typeComment\"),\n }",
" dirInfoList.append(entry)\n #\n ignore_patterns = self.dir_config.get(\"ignore\", [])\n if util.is_basestring(ignore_patterns):\n ignore_patterns = ignore_patterns.split(\",\")",
" ignored_list = []\n for entry in dirInfoList:\n # Skip ignore patterns\n ignore = False\n for pat in ignore_patterns:\n if fnmatch(entry[\"display_name\"], pat):\n ignored_list.append(entry[\"display_name\"])\n # _logger.debug(\"Ignore {}\".format(entry[\"display_name\"]))\n ignore = True\n break\n if ignore:\n continue\n #\n last_modified = entry.get(\"last_modified\")\n if last_modified is None:\n entry[\"str_modified\"] = \"\"\n else:\n entry[\"str_modified\"] = util.get_rfc1123_time(last_modified)",
" entry[\"str_size\"] = \"-\"\n if not entry.get(\"is_collection\"):\n content_length = entry.get(\"content_length\")\n if content_length is not None:\n entry[\"str_size\"] = util.byte_number_string(content_length)",
" rows.append(entry)\n if ignored_list:\n _logger.debug(\n \"Dir browser ignored {} entries: {}\".format(\n len(ignored_list), ignored_list\n )\n )",
" # sort\n sort = \"name\"\n if sort == \"name\":\n rows.sort(\n key=lambda v: \"{}{}\".format(\n not v[\"is_collection\"], v[\"display_name\"].lower()\n )\n )",
" if \"wsgidav.auth.user_name\" in environ:\n context.update(\n {\n \"is_authenticated\": bool(environ.get(\"wsgidav.auth.user_name\")),\n \"user_name\": (environ.get(\"wsgidav.auth.user_name\") or \"anonymous\"),\n \"realm\": environ.get(\"wsgidav.auth.realm\"),\n \"user_roles\": \", \".join(environ.get(\"wsgidav.auth.roles\") or []),\n \"user_permissions\": \", \".join(\n environ.get(\"wsgidav.auth.permissions\") or []\n ),\n }\n )",
" return context"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [77, 99], "buggy_code_start_loc": [13, 84], "filenames": ["wsgidav/dir_browser/_dir_browser.py", "wsgidav/dir_browser/htdocs/template.html"], "fixing_code_end_loc": [77, 99], "fixing_code_start_loc": [13, 84], "message": "WsgiDAV is a generic and extendable WebDAV server based on WSGI. Implementations using this library with directory browsing enabled may be susceptible to Cross Site Scripting (XSS) attacks. This issue has been patched, users can upgrade to version 4.1.0. As a workaround, set `dir_browser.enable = False` in the configuration.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wsgidav_project:wsgidav:*:*:*:*:*:*:*:*", "matchCriteriaId": "A13F7E6A-3839-4247-ACA6-4544D45534CA", "versionEndExcluding": "4.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WsgiDAV is a generic and extendable WebDAV server based on WSGI. Implementations using this library with directory browsing enabled may be susceptible to Cross Site Scripting (XSS) attacks. This issue has been patched, users can upgrade to version 4.1.0. As a workaround, set `dir_browser.enable = False` in the configuration."}], "evaluatorComment": null, "id": "CVE-2022-41905", "lastModified": "2022-11-16T18:10:41.607", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 8.2, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-11-11T21:15:09.743", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mar10/wsgidav/commit/e9606ab0f42f4c1a6611bc3c52de299b0aba7726"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/mar10/wsgidav/security/advisories/GHSA-xx6g-jj35-pxjv"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mar10/wsgidav/commit/e9606ab0f42f4c1a6611bc3c52de299b0aba7726"}, "type": "CWE-79"}
| 247
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<!DOCTYPE html>\n<html>\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n <meta name=\"generator\" content=\"WsgiDAV/{{ version }}\">\n <title>WsgiDAV - Index of {{ display_path }} </title>\n <link rel=\"shortcut icon\" href=\"{{ htdocs }}/favicon.ico\">\n <link rel=\"stylesheet\" href=\"{{ htdocs }}/style.css\" />\n <script defer src=\"{{ htdocs }}/script.js\"></script>\n <style type=\"text/css\"> A {behavior: url(#default#AnchorClick);} </style>\n</head>",
"<body onload=\"onLoad()\">",
" <h1>\n {%- if config.icon %}\n <img class=\"logo\" alt=\"WsgiDAV\" title=\"WsgiDAV\" src=\"{{ htdocs }}/logo.png\">\n {% endif -%}\n Index of {{ display_path }}\n </h1>",
" {% if config.davmount_links %}\n <p class=\"links\">\n <a title=\"Open this folder in a registered WebDAV client.\" href=\"{{ url }}?davmount\">Mount</a>\n </p>\n {% endif %}",
" {%- if user_name and config.show_user %}\n <p class=\"auth-user\">\n Authenticated user: \"{{user_name}}\", realm: \"{{realm}}\", access: {{access}}.\n {%- if is_authenticated and config.show_logout %}\n <a title=\"Logout current user\" href=\"{{ url }}?logout\" target=\"_blank\">Logout</a>\n {% endif -%}\n {%- if user_roles %}\n , roles: {{ user_roles }}\n {% endif -%}\n </p>\n {% endif -%}",
" <hr>",
" <table class=\"dir-listing\" onclick=\"return onClickTable(event)\">",
" <colgroup>\n <col>\n <col>\n <col class=\"right\">\n <col class=\"right\">\n </colgroup>",
" <thead>\n <tr>\n <th>Name</th>\n <th>Type</th>\n <th>Size</th>\n <th>Last modified</th>\n </tr>\n </thead>",
" <tbody>\n {%- if not is_top_dir %}\n <tr class=\"directory\">\n <td>\n <a href=\"..\">..</a>\n </td>\n <td>Directory</td>\n <td>-</td>\n <td></td>\n </tr>\n {% endif -%}",
" {% for row in rows %}\n <tr class=\"{{ row.tr_class }}\">\n <td>\n <a class=\"{{ row.a_class }}\" href=\"{{row.href}}\" {% if row.ofe_prefix %} data-ofe=\"{{row.ofe_prefix}}\" {% endif %} >\n {{row.display_name}}\n </a>\n {%- if row.href_2 %}\n <a class=\"{{ row.a_class_2 }}\" href=\"{{row.href_2}}\" {% if row.ofe_prefix_2%} data-ofe=\"{{row.ofe_prefix_2}}\" {% endif %} >\n {{row.display_name_2}}\n </a>\n {% endif -%}\n {%- if row.add_link_html %}",
" {{row.add_link_html}}",
" {% endif -%}\n </td>\n <td>{{ row.display_type }}</td>\n <td>{{ row.str_size }}</td>\n <td>{{ row.str_modified }}</td>\n </tr>\n {% endfor %}\n </tbody>\n </table>",
" <hr>",
" {% if trailer %}",
" <p class=\"trailer\">{{ trailer }}</p>",
" {% endif %}",
" <object id=\"winFirefoxPlugin\" type=\"application/x-sharepoint\"\n width=\"0\" height=\"0\" style=\"visibility: hidden;\"></object>",
"</body>\n</html>"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
0,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [77, 99], "buggy_code_start_loc": [13, 84], "filenames": ["wsgidav/dir_browser/_dir_browser.py", "wsgidav/dir_browser/htdocs/template.html"], "fixing_code_end_loc": [77, 99], "fixing_code_start_loc": [13, 84], "message": "WsgiDAV is a generic and extendable WebDAV server based on WSGI. Implementations using this library with directory browsing enabled may be susceptible to Cross Site Scripting (XSS) attacks. This issue has been patched, users can upgrade to version 4.1.0. As a workaround, set `dir_browser.enable = False` in the configuration.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wsgidav_project:wsgidav:*:*:*:*:*:*:*:*", "matchCriteriaId": "A13F7E6A-3839-4247-ACA6-4544D45534CA", "versionEndExcluding": "4.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WsgiDAV is a generic and extendable WebDAV server based on WSGI. Implementations using this library with directory browsing enabled may be susceptible to Cross Site Scripting (XSS) attacks. This issue has been patched, users can upgrade to version 4.1.0. As a workaround, set `dir_browser.enable = False` in the configuration."}], "evaluatorComment": null, "id": "CVE-2022-41905", "lastModified": "2022-11-16T18:10:41.607", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 8.2, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-11-11T21:15:09.743", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mar10/wsgidav/commit/e9606ab0f42f4c1a6611bc3c52de299b0aba7726"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/mar10/wsgidav/security/advisories/GHSA-xx6g-jj35-pxjv"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mar10/wsgidav/commit/e9606ab0f42f4c1a6611bc3c52de299b0aba7726"}, "type": "CWE-79"}
| 247
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<!DOCTYPE html>\n<html>\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n <meta name=\"generator\" content=\"WsgiDAV/{{ version }}\">\n <title>WsgiDAV - Index of {{ display_path }} </title>\n <link rel=\"shortcut icon\" href=\"{{ htdocs }}/favicon.ico\">\n <link rel=\"stylesheet\" href=\"{{ htdocs }}/style.css\" />\n <script defer src=\"{{ htdocs }}/script.js\"></script>\n <style type=\"text/css\"> A {behavior: url(#default#AnchorClick);} </style>\n</head>",
"<body onload=\"onLoad()\">",
" <h1>\n {%- if config.icon %}\n <img class=\"logo\" alt=\"WsgiDAV\" title=\"WsgiDAV\" src=\"{{ htdocs }}/logo.png\">\n {% endif -%}\n Index of {{ display_path }}\n </h1>",
" {% if config.davmount_links %}\n <p class=\"links\">\n <a title=\"Open this folder in a registered WebDAV client.\" href=\"{{ url }}?davmount\">Mount</a>\n </p>\n {% endif %}",
" {%- if user_name and config.show_user %}\n <p class=\"auth-user\">\n Authenticated user: \"{{user_name}}\", realm: \"{{realm}}\", access: {{access}}.\n {%- if is_authenticated and config.show_logout %}\n <a title=\"Logout current user\" href=\"{{ url }}?logout\" target=\"_blank\">Logout</a>\n {% endif -%}\n {%- if user_roles %}\n , roles: {{ user_roles }}\n {% endif -%}\n </p>\n {% endif -%}",
" <hr>",
" <table class=\"dir-listing\" onclick=\"return onClickTable(event)\">",
" <colgroup>\n <col>\n <col>\n <col class=\"right\">\n <col class=\"right\">\n </colgroup>",
" <thead>\n <tr>\n <th>Name</th>\n <th>Type</th>\n <th>Size</th>\n <th>Last modified</th>\n </tr>\n </thead>",
" <tbody>\n {%- if not is_top_dir %}\n <tr class=\"directory\">\n <td>\n <a href=\"..\">..</a>\n </td>\n <td>Directory</td>\n <td>-</td>\n <td></td>\n </tr>\n {% endif -%}",
" {% for row in rows %}\n <tr class=\"{{ row.tr_class }}\">\n <td>\n <a class=\"{{ row.a_class }}\" href=\"{{row.href}}\" {% if row.ofe_prefix %} data-ofe=\"{{row.ofe_prefix}}\" {% endif %} >\n {{row.display_name}}\n </a>\n {%- if row.href_2 %}\n <a class=\"{{ row.a_class_2 }}\" href=\"{{row.href_2}}\" {% if row.ofe_prefix_2%} data-ofe=\"{{row.ofe_prefix_2}}\" {% endif %} >\n {{row.display_name_2}}\n </a>\n {% endif -%}\n {%- if row.add_link_html %}",
" {{row.add_link_html | safe}}",
" {% endif -%}\n </td>\n <td>{{ row.display_type }}</td>\n <td>{{ row.str_size }}</td>\n <td>{{ row.str_modified }}</td>\n </tr>\n {% endfor %}\n </tbody>\n </table>",
" <hr>",
" {% if trailer %}",
" <p class=\"trailer\">{{ trailer | safe }}</p>",
" {% endif %}",
" <object id=\"winFirefoxPlugin\" type=\"application/x-sharepoint\"\n width=\"0\" height=\"0\" style=\"visibility: hidden;\"></object>",
"</body>\n</html>"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [77, 99], "buggy_code_start_loc": [13, 84], "filenames": ["wsgidav/dir_browser/_dir_browser.py", "wsgidav/dir_browser/htdocs/template.html"], "fixing_code_end_loc": [77, 99], "fixing_code_start_loc": [13, 84], "message": "WsgiDAV is a generic and extendable WebDAV server based on WSGI. Implementations using this library with directory browsing enabled may be susceptible to Cross Site Scripting (XSS) attacks. This issue has been patched, users can upgrade to version 4.1.0. As a workaround, set `dir_browser.enable = False` in the configuration.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wsgidav_project:wsgidav:*:*:*:*:*:*:*:*", "matchCriteriaId": "A13F7E6A-3839-4247-ACA6-4544D45534CA", "versionEndExcluding": "4.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WsgiDAV is a generic and extendable WebDAV server based on WSGI. Implementations using this library with directory browsing enabled may be susceptible to Cross Site Scripting (XSS) attacks. This issue has been patched, users can upgrade to version 4.1.0. As a workaround, set `dir_browser.enable = False` in the configuration."}], "evaluatorComment": null, "id": "CVE-2022-41905", "lastModified": "2022-11-16T18:10:41.607", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 8.2, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-11-11T21:15:09.743", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mar10/wsgidav/commit/e9606ab0f42f4c1a6611bc3c52de299b0aba7726"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/mar10/wsgidav/security/advisories/GHSA-xx6g-jj35-pxjv"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mar10/wsgidav/commit/e9606ab0f42f4c1a6611bc3c52de299b0aba7726"}, "type": "CWE-79"}
| 247
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"#include \"helper.h\"",
"#include <QCoreApplication>\n#include <QtDBus>\n#include <QFile>\n#include <PolkitQt1/Authority>\n#include <PolkitQt1/Subject>",
"#include <signal.h>",
"HelperAdaptor::HelperAdaptor(Helper *parent) :\n QDBusAbstractAdaptor(parent)\n{\n m_parentHelper = parent;\n}",
"QVariantMap HelperAdaptor::listStorages()\n{\n return m_parentHelper->listStorages();\n}",
"void HelperAdaptor::prepareBenchmarkFile(const QString &benchmarkFile, int fileSize, bool fillZeros)\n{\n return m_parentHelper->prepareBenchmarkFile(benchmarkFile, fileSize, fillZeros);\n}",
"void HelperAdaptor::startBenchmarkTest(int measuringTime, int fileSize, int randomReadPercentage, bool fillZeros, bool cacheBypass,\n int blockSize, int queueDepth, int threads, const QString &rw)\n{\n m_parentHelper->startBenchmarkTest(measuringTime, fileSize, randomReadPercentage, fillZeros, cacheBypass, blockSize, queueDepth, threads, rw);\n}",
"QVariantMap HelperAdaptor::flushPageCache()\n{\n return m_parentHelper->flushPageCache();\n}",
"bool HelperAdaptor::removeBenchmarkFile()\n{\n return m_parentHelper->removeBenchmarkFile();\n}",
"void HelperAdaptor::stopCurrentTask()\n{\n m_parentHelper->stopCurrentTask();\n}",
"Helper::Helper() : m_helperAdaptor(new HelperAdaptor(this))\n{\n if (!QDBusConnection::systemBus().isConnected() || !QDBusConnection::systemBus().registerService(QStringLiteral(\"dev.jonmagon.kdiskmark.helperinterface\")) ||\n !QDBusConnection::systemBus().registerObject(QStringLiteral(\"/Helper\"), this)) {\n qWarning() << QDBusConnection::systemBus().lastError().message();\n qApp->quit();\n }",
" m_serviceWatcher = new QDBusServiceWatcher(this);\n m_serviceWatcher->setConnection(QDBusConnection ::systemBus());\n m_serviceWatcher->setWatchMode(QDBusServiceWatcher::WatchForUnregistration);",
" connect(m_serviceWatcher, &QDBusServiceWatcher::serviceUnregistered, qApp, [this](const QString &service) {\n m_serviceWatcher->removeWatchedService(service);\n if (m_serviceWatcher->watchedServices().isEmpty()) {\n qApp->quit();\n }\n });",
" QObject::connect(this, &Helper::taskFinished, m_helperAdaptor, &HelperAdaptor::taskFinished);\n}",
"bool Helper::testFilePath(const QString &benchmarkFile)\n{\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))\n if (QFileInfo(benchmarkFile).isSymbolicLink()) {\n#else\n // detects *.lnk on Windows, but there's not Windows version, whatever\n if (QFileInfo(benchmarkFile).isSymLink()) {\n#endif\n qWarning(\"The path should not be symbolic link.\");\n return false;\n }",
" if (!benchmarkFile.endsWith(\"/.kdiskmark.tmp\")) {\n qWarning(\"The path must end with /.kdiskmark.tmp\");\n return false;\n }",
" // Actually superfluous because of above, makes the check more obvious\n // Just in case something changes in the backend\n if (benchmarkFile.startsWith(\"/dev\")) {\n qWarning(\"Cannot specify a raw device.\");\n return false;\n }",
" return true;\n}",
"QVariantMap Helper::listStorages()\n{\n if (!isCallerAuthorized()) {\n return {};\n }",
" QVariantMap reply;\n foreach (const QStorageInfo &storage, QStorageInfo::mountedVolumes()) {\n if (storage.isValid() && storage.isReady() && !storage.isReadOnly()) {\n if (storage.device().indexOf(\"/dev\") != -1) {\n reply[storage.rootPath()] =\n QVariant::fromValue(QDBusVariant(QVariant::fromValue(QVector<qlonglong> { storage.bytesTotal(), storage.bytesAvailable() })));\n }\n }\n }",
" return reply;\n}",
"void Helper::prepareBenchmarkFile(const QString &benchmarkFile, int fileSize, bool fillZeros)\n{\n if (!isCallerAuthorized()) {\n return;\n }",
" // If benchmarking has been done, but removeBenchmarkFile has not been called,\n // and benchmarking on a new file is called, then reject the request. The *previous* file must be removed first.\n if (!m_benchmarkFile.isEmpty()) {\n qWarning() << \"The previous benchmarking was not completed correctly.\";\n return;\n }",
" if (!testFilePath(benchmarkFile)) {\n return;\n }",
" m_benchmarkFile = benchmarkFile;",
" m_process = new QProcess();\n m_process->start(\"fio\", QStringList()\n << QStringLiteral(\"--output-format=json\")\n << QStringLiteral(\"--create_only=1\")\n << QStringLiteral(\"--filename=%1\").arg(m_benchmarkFile)\n << QStringLiteral(\"--size=%1m\").arg(fileSize)\n << QStringLiteral(\"--zero_buffers=%1\").arg(fillZeros)\n << QStringLiteral(\"--name=prepare\"));",
" connect(m_process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),\n [=] (int exitCode, QProcess::ExitStatus exitStatus) {\n emit taskFinished(exitStatus == QProcess::NormalExit, QString(m_process->readAllStandardOutput()), QString(m_process->readAllStandardError()));\n });\n}",
"void Helper::startBenchmarkTest(int measuringTime, int fileSize, int randomReadPercentage, bool fillZeros, bool cacheBypass,\n int blockSize, int queueDepth, int threads, const QString &rw)\n{\n if (!isCallerAuthorized()) {\n return;\n }",
" if (m_benchmarkFile.isEmpty()) {\n return;\n }",
" if (!QFile(m_benchmarkFile).exists()) {\n qWarning() << \"The benchmark file was not pre-created.\";\n return;\n }",
" m_process = new QProcess();\n m_process->start(\"fio\", QStringList()\n << QStringLiteral(\"--output-format=json\")\n << QStringLiteral(\"--ioengine=libaio\")\n << QStringLiteral(\"--randrepeat=0\")\n << QStringLiteral(\"--refill_buffers\")\n << QStringLiteral(\"--end_fsync=1\")\n << QStringLiteral(\"--direct=%1\").arg(cacheBypass)\n << QStringLiteral(\"--rwmixread=%1\").arg(randomReadPercentage)\n << QStringLiteral(\"--filename=%1\").arg(m_benchmarkFile)\n << QStringLiteral(\"--name=%1\").arg(rw)\n << QStringLiteral(\"--size=%1m\").arg(fileSize)\n << QStringLiteral(\"--zero_buffers=%1\").arg(fillZeros)\n << QStringLiteral(\"--bs=%1k\").arg(blockSize)\n << QStringLiteral(\"--runtime=%1\").arg(measuringTime)\n << QStringLiteral(\"--rw=%1\").arg(rw)\n << QStringLiteral(\"--iodepth=%1\").arg(queueDepth)\n << QStringLiteral(\"--numjobs=%1\").arg(threads));",
" connect(m_process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),\n [=] (int exitCode, QProcess::ExitStatus exitStatus) {\n emit taskFinished(exitStatus == QProcess::NormalExit, QString(m_process->readAllStandardOutput()), QString(m_process->readAllStandardError()));\n });\n}",
"QVariantMap Helper::flushPageCache()\n{",
"",
" QVariantMap reply;\n reply[QStringLiteral(\"success\")] = true;",
" if (!isCallerAuthorized()) {\n reply[QStringLiteral(\"success\")] = false;\n return reply;\n }",
" QFile file(\"/proc/sys/vm/drop_caches\");",
" if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n file.write(\"1\");\n file.close();\n }\n else {\n reply[QStringLiteral(\"success\")] = false;\n reply[QStringLiteral(\"error\")] = file.errorString();\n }",
" return reply;\n}",
"bool Helper::removeBenchmarkFile()\n{\n if (!isCallerAuthorized()) {\n return false;\n }",
" if (m_benchmarkFile.isEmpty()) {\n return false;\n }",
" bool deletionState = QFile(m_benchmarkFile).remove();\n m_benchmarkFile.clear();",
" return deletionState;\n}",
"void Helper::stopCurrentTask()\n{\n if (!isCallerAuthorized()) {\n return;\n }",
" if (!m_process) return;",
" if (m_process->state() == QProcess::Running || m_process->state() == QProcess::Starting) {\n m_process->terminate();\n m_process->waitForFinished(-1);\n }",
" delete m_process;\n}",
"bool Helper::isCallerAuthorized()\n{\n if (!calledFromDBus()) {\n return false;\n }",
" if (m_serviceWatcher->watchedServices().contains(message().service())) {\n return true;\n }",
" if (!m_serviceWatcher->watchedServices().isEmpty()) {\n qDebug() << \"There are already registered DBus connections.\";\n return false;\n }",
" PolkitQt1::SystemBusNameSubject subject(message().service());\n PolkitQt1::Authority *authority = PolkitQt1::Authority::instance();",
" PolkitQt1::Authority::Result result;\n QEventLoop e;\n connect(authority, &PolkitQt1::Authority::checkAuthorizationFinished, &e, [&e, &result](PolkitQt1::Authority::Result _result) {\n result = _result;\n e.quit();\n });",
" authority->checkAuthorization(QStringLiteral(\"dev.jonmagon.kdiskmark.helper.init\"), subject, PolkitQt1::Authority::AllowUserInteraction);\n e.exec();",
" if (authority->hasError()) {\n qDebug() << \"Encountered error while checking authorization, error code: \" << authority->lastError() << authority->errorDetails();\n authority->clearError();\n }",
" switch (result) {\n case PolkitQt1::Authority::Yes:\n // track who called into us so we can close when all callers have gone away\n m_serviceWatcher->addWatchedService(message().service());\n return true;\n default:\n sendErrorReply(QDBusError::AccessDenied);\n if (m_serviceWatcher->watchedServices().isEmpty())\n qApp->quit();\n return false;\n }\n}",
"int main(int argc, char *argv[])\n{\n QCoreApplication a(argc, argv);\n Helper helper;\n a.exec();\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [192], "buggy_code_start_loc": [192], "filenames": ["src/helper.cpp"], "fixing_code_end_loc": [197], "fixing_code_start_loc": [193], "message": "KDiskMark before 3.1.0 lacks authorization checking for D-Bus methods such as Helper::flushPageCache.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kdiskmark_project:kdiskmark:*:*:*:*:*:*:*:*", "matchCriteriaId": "39BAECF8-9240-451F-A20B-5DB8FBA3B003", "versionEndExcluding": "3.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "KDiskMark before 3.1.0 lacks authorization checking for D-Bus methods such as Helper::flushPageCache."}, {"lang": "es", "value": "KDiskMark versiones anteriores a 3.1.0, carece de comprobaci\u00f3n de autorizaci\u00f3n para los m\u00e9todos D-Bus como Helper::flushPageCache"}], "evaluatorComment": null, "id": "CVE-2022-40673", "lastModified": "2022-10-01T02:32:48.573", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-09-14T11:15:53.837", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2022/09/14/1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/JonMagon/KDiskMark/commit/3c90083a4f5ba3f240a797e509d818221542bbdc"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/JonMagon/KDiskMark/compare/3.0.0...3.1.0"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/JonMagon/KDiskMark/releases/tag/3.1.0"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/YYO3GWTNPHNCLHSI562Q3KX43PW7FQ4Q/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-862"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/JonMagon/KDiskMark/commit/3c90083a4f5ba3f240a797e509d818221542bbdc"}, "type": "CWE-862"}
| 248
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"#include \"helper.h\"",
"#include <QCoreApplication>\n#include <QtDBus>\n#include <QFile>\n#include <PolkitQt1/Authority>\n#include <PolkitQt1/Subject>",
"#include <signal.h>",
"HelperAdaptor::HelperAdaptor(Helper *parent) :\n QDBusAbstractAdaptor(parent)\n{\n m_parentHelper = parent;\n}",
"QVariantMap HelperAdaptor::listStorages()\n{\n return m_parentHelper->listStorages();\n}",
"void HelperAdaptor::prepareBenchmarkFile(const QString &benchmarkFile, int fileSize, bool fillZeros)\n{\n return m_parentHelper->prepareBenchmarkFile(benchmarkFile, fileSize, fillZeros);\n}",
"void HelperAdaptor::startBenchmarkTest(int measuringTime, int fileSize, int randomReadPercentage, bool fillZeros, bool cacheBypass,\n int blockSize, int queueDepth, int threads, const QString &rw)\n{\n m_parentHelper->startBenchmarkTest(measuringTime, fileSize, randomReadPercentage, fillZeros, cacheBypass, blockSize, queueDepth, threads, rw);\n}",
"QVariantMap HelperAdaptor::flushPageCache()\n{\n return m_parentHelper->flushPageCache();\n}",
"bool HelperAdaptor::removeBenchmarkFile()\n{\n return m_parentHelper->removeBenchmarkFile();\n}",
"void HelperAdaptor::stopCurrentTask()\n{\n m_parentHelper->stopCurrentTask();\n}",
"Helper::Helper() : m_helperAdaptor(new HelperAdaptor(this))\n{\n if (!QDBusConnection::systemBus().isConnected() || !QDBusConnection::systemBus().registerService(QStringLiteral(\"dev.jonmagon.kdiskmark.helperinterface\")) ||\n !QDBusConnection::systemBus().registerObject(QStringLiteral(\"/Helper\"), this)) {\n qWarning() << QDBusConnection::systemBus().lastError().message();\n qApp->quit();\n }",
" m_serviceWatcher = new QDBusServiceWatcher(this);\n m_serviceWatcher->setConnection(QDBusConnection ::systemBus());\n m_serviceWatcher->setWatchMode(QDBusServiceWatcher::WatchForUnregistration);",
" connect(m_serviceWatcher, &QDBusServiceWatcher::serviceUnregistered, qApp, [this](const QString &service) {\n m_serviceWatcher->removeWatchedService(service);\n if (m_serviceWatcher->watchedServices().isEmpty()) {\n qApp->quit();\n }\n });",
" QObject::connect(this, &Helper::taskFinished, m_helperAdaptor, &HelperAdaptor::taskFinished);\n}",
"bool Helper::testFilePath(const QString &benchmarkFile)\n{\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))\n if (QFileInfo(benchmarkFile).isSymbolicLink()) {\n#else\n // detects *.lnk on Windows, but there's not Windows version, whatever\n if (QFileInfo(benchmarkFile).isSymLink()) {\n#endif\n qWarning(\"The path should not be symbolic link.\");\n return false;\n }",
" if (!benchmarkFile.endsWith(\"/.kdiskmark.tmp\")) {\n qWarning(\"The path must end with /.kdiskmark.tmp\");\n return false;\n }",
" // Actually superfluous because of above, makes the check more obvious\n // Just in case something changes in the backend\n if (benchmarkFile.startsWith(\"/dev\")) {\n qWarning(\"Cannot specify a raw device.\");\n return false;\n }",
" return true;\n}",
"QVariantMap Helper::listStorages()\n{\n if (!isCallerAuthorized()) {\n return {};\n }",
" QVariantMap reply;\n foreach (const QStorageInfo &storage, QStorageInfo::mountedVolumes()) {\n if (storage.isValid() && storage.isReady() && !storage.isReadOnly()) {\n if (storage.device().indexOf(\"/dev\") != -1) {\n reply[storage.rootPath()] =\n QVariant::fromValue(QDBusVariant(QVariant::fromValue(QVector<qlonglong> { storage.bytesTotal(), storage.bytesAvailable() })));\n }\n }\n }",
" return reply;\n}",
"void Helper::prepareBenchmarkFile(const QString &benchmarkFile, int fileSize, bool fillZeros)\n{\n if (!isCallerAuthorized()) {\n return;\n }",
" // If benchmarking has been done, but removeBenchmarkFile has not been called,\n // and benchmarking on a new file is called, then reject the request. The *previous* file must be removed first.\n if (!m_benchmarkFile.isEmpty()) {\n qWarning() << \"The previous benchmarking was not completed correctly.\";\n return;\n }",
" if (!testFilePath(benchmarkFile)) {\n return;\n }",
" m_benchmarkFile = benchmarkFile;",
" m_process = new QProcess();\n m_process->start(\"fio\", QStringList()\n << QStringLiteral(\"--output-format=json\")\n << QStringLiteral(\"--create_only=1\")\n << QStringLiteral(\"--filename=%1\").arg(m_benchmarkFile)\n << QStringLiteral(\"--size=%1m\").arg(fileSize)\n << QStringLiteral(\"--zero_buffers=%1\").arg(fillZeros)\n << QStringLiteral(\"--name=prepare\"));",
" connect(m_process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),\n [=] (int exitCode, QProcess::ExitStatus exitStatus) {\n emit taskFinished(exitStatus == QProcess::NormalExit, QString(m_process->readAllStandardOutput()), QString(m_process->readAllStandardError()));\n });\n}",
"void Helper::startBenchmarkTest(int measuringTime, int fileSize, int randomReadPercentage, bool fillZeros, bool cacheBypass,\n int blockSize, int queueDepth, int threads, const QString &rw)\n{\n if (!isCallerAuthorized()) {\n return;\n }",
" if (m_benchmarkFile.isEmpty()) {\n return;\n }",
" if (!QFile(m_benchmarkFile).exists()) {\n qWarning() << \"The benchmark file was not pre-created.\";\n return;\n }",
" m_process = new QProcess();\n m_process->start(\"fio\", QStringList()\n << QStringLiteral(\"--output-format=json\")\n << QStringLiteral(\"--ioengine=libaio\")\n << QStringLiteral(\"--randrepeat=0\")\n << QStringLiteral(\"--refill_buffers\")\n << QStringLiteral(\"--end_fsync=1\")\n << QStringLiteral(\"--direct=%1\").arg(cacheBypass)\n << QStringLiteral(\"--rwmixread=%1\").arg(randomReadPercentage)\n << QStringLiteral(\"--filename=%1\").arg(m_benchmarkFile)\n << QStringLiteral(\"--name=%1\").arg(rw)\n << QStringLiteral(\"--size=%1m\").arg(fileSize)\n << QStringLiteral(\"--zero_buffers=%1\").arg(fillZeros)\n << QStringLiteral(\"--bs=%1k\").arg(blockSize)\n << QStringLiteral(\"--runtime=%1\").arg(measuringTime)\n << QStringLiteral(\"--rw=%1\").arg(rw)\n << QStringLiteral(\"--iodepth=%1\").arg(queueDepth)\n << QStringLiteral(\"--numjobs=%1\").arg(threads));",
" connect(m_process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),\n [=] (int exitCode, QProcess::ExitStatus exitStatus) {\n emit taskFinished(exitStatus == QProcess::NormalExit, QString(m_process->readAllStandardOutput()), QString(m_process->readAllStandardError()));\n });\n}",
"QVariantMap Helper::flushPageCache()\n{",
" if (!isCallerAuthorized()) {\n return {};\n }\n",
" QVariantMap reply;\n reply[QStringLiteral(\"success\")] = true;",
" if (!isCallerAuthorized()) {\n reply[QStringLiteral(\"success\")] = false;\n return reply;\n }",
" QFile file(\"/proc/sys/vm/drop_caches\");",
" if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n file.write(\"1\");\n file.close();\n }\n else {\n reply[QStringLiteral(\"success\")] = false;\n reply[QStringLiteral(\"error\")] = file.errorString();\n }",
" return reply;\n}",
"bool Helper::removeBenchmarkFile()\n{\n if (!isCallerAuthorized()) {\n return false;\n }",
" if (m_benchmarkFile.isEmpty()) {\n return false;\n }",
" bool deletionState = QFile(m_benchmarkFile).remove();\n m_benchmarkFile.clear();",
" return deletionState;\n}",
"void Helper::stopCurrentTask()\n{\n if (!isCallerAuthorized()) {\n return;\n }",
" if (!m_process) return;",
" if (m_process->state() == QProcess::Running || m_process->state() == QProcess::Starting) {\n m_process->terminate();\n m_process->waitForFinished(-1);\n }",
" delete m_process;\n}",
"bool Helper::isCallerAuthorized()\n{\n if (!calledFromDBus()) {\n return false;\n }",
" if (m_serviceWatcher->watchedServices().contains(message().service())) {\n return true;\n }",
" if (!m_serviceWatcher->watchedServices().isEmpty()) {\n qDebug() << \"There are already registered DBus connections.\";\n return false;\n }",
" PolkitQt1::SystemBusNameSubject subject(message().service());\n PolkitQt1::Authority *authority = PolkitQt1::Authority::instance();",
" PolkitQt1::Authority::Result result;\n QEventLoop e;\n connect(authority, &PolkitQt1::Authority::checkAuthorizationFinished, &e, [&e, &result](PolkitQt1::Authority::Result _result) {\n result = _result;\n e.quit();\n });",
" authority->checkAuthorization(QStringLiteral(\"dev.jonmagon.kdiskmark.helper.init\"), subject, PolkitQt1::Authority::AllowUserInteraction);\n e.exec();",
" if (authority->hasError()) {\n qDebug() << \"Encountered error while checking authorization, error code: \" << authority->lastError() << authority->errorDetails();\n authority->clearError();\n }",
" switch (result) {\n case PolkitQt1::Authority::Yes:\n // track who called into us so we can close when all callers have gone away\n m_serviceWatcher->addWatchedService(message().service());\n return true;\n default:\n sendErrorReply(QDBusError::AccessDenied);\n if (m_serviceWatcher->watchedServices().isEmpty())\n qApp->quit();\n return false;\n }\n}",
"int main(int argc, char *argv[])\n{\n QCoreApplication a(argc, argv);\n Helper helper;\n a.exec();\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [192], "buggy_code_start_loc": [192], "filenames": ["src/helper.cpp"], "fixing_code_end_loc": [197], "fixing_code_start_loc": [193], "message": "KDiskMark before 3.1.0 lacks authorization checking for D-Bus methods such as Helper::flushPageCache.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kdiskmark_project:kdiskmark:*:*:*:*:*:*:*:*", "matchCriteriaId": "39BAECF8-9240-451F-A20B-5DB8FBA3B003", "versionEndExcluding": "3.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "KDiskMark before 3.1.0 lacks authorization checking for D-Bus methods such as Helper::flushPageCache."}, {"lang": "es", "value": "KDiskMark versiones anteriores a 3.1.0, carece de comprobaci\u00f3n de autorizaci\u00f3n para los m\u00e9todos D-Bus como Helper::flushPageCache"}], "evaluatorComment": null, "id": "CVE-2022-40673", "lastModified": "2022-10-01T02:32:48.573", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-09-14T11:15:53.837", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2022/09/14/1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/JonMagon/KDiskMark/commit/3c90083a4f5ba3f240a797e509d818221542bbdc"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/JonMagon/KDiskMark/compare/3.0.0...3.1.0"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/JonMagon/KDiskMark/releases/tag/3.1.0"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/YYO3GWTNPHNCLHSI562Q3KX43PW7FQ4Q/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-862"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/JonMagon/KDiskMark/commit/3c90083a4f5ba3f240a797e509d818221542bbdc"}, "type": "CWE-862"}
| 248
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package org.dynmap.servlet;",
"import org.dynmap.DynmapCore;\nimport org.dynmap.DynmapWorld;\nimport org.dynmap.MapType.ImageEncoding;\nimport org.dynmap.PlayerFaces;\nimport org.dynmap.storage.MapStorage;\nimport org.dynmap.storage.MapStorageTile;\nimport org.dynmap.storage.MapStorageTile.TileRead;\nimport org.dynmap.utils.BufferInputStream;\nimport org.eclipse.jetty.http.HttpStatus;\nimport org.eclipse.jetty.server.Request;\nimport org.eclipse.jetty.server.handler.AbstractHandler;",
"import javax.imageio.ImageIO;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletOutputStream;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;",
"import java.awt.image.BufferedImage;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.io.OutputStream;",
"public class MapStorageResourceHandler extends AbstractHandler {",
" private DynmapCore core;\n private byte[] blankpng;\n private long blankpnghash = 0x12345678;\n \n public MapStorageResourceHandler() {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n BufferedImage blank = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB);\n try {\n ImageIO.write(blank, \"png\", baos);\n blankpng = baos.toByteArray();\n } catch (IOException e) {\n }\n \n }\n @Override\n public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {\n String path = baseRequest.getPathInfo();\n int soff = 0, eoff;\n // We're handling this request\n baseRequest.setHandled(true);",
"",
" if (path.charAt(0) == '/') soff = 1;\n eoff = path.indexOf('/', soff);\n if (soff < 0) {\n response.sendError(HttpStatus.NOT_FOUND_404);\n return;\n }\n String world = path.substring(soff, eoff);\n String uri = path.substring(eoff+1);\n // If faces directory, handle faces\n if (world.equals(\"faces\")) {\n handleFace(response, uri);\n return;\n }\n // If markers directory, handle markers\n if (world.equals(\"_markers_\")) {\n handleMarkers(response, uri);\n return;\n }",
" DynmapWorld w = null;\n if (core.mapManager != null) {\n w = core.mapManager.getWorld(world);\n }\n // If world not found quit\n if (w == null) {\n response.setContentType(\"image/png\");\n OutputStream os = response.getOutputStream();\n os.write(blankpng);\n return;\n }\n MapStorage store = w.getMapStorage(); // Get storage handler\n // Get tile reference, based on URI and world\n MapStorageTile tile = store.getTile(w, uri);\n if (tile == null) {\n response.setContentType(\"image/png\");\n OutputStream os = response.getOutputStream();\n os.write(blankpng);\n return;\n }\n // Read tile\n TileRead tr = null;\n if (tile.getReadLock(5000)) {\n tr = tile.read();\n tile.releaseReadLock();\n }\n response.setHeader(\"Cache-Control\", \"max-age=0,must-revalidate\");\n String etag;\n if (tr == null) {\n \tetag = \"\\\"\" + blankpnghash + \"\\\"\";\n }\n else {\n \tetag = \"\\\"\" + tr.hashCode + \"\\\"\";\n }\n response.setHeader(\"ETag\", etag);\n String ifnullmatch = request.getHeader(\"If-None-Match\");\n if ((ifnullmatch != null) && ifnullmatch.equals(etag)) {\n response.sendError(HttpStatus.NOT_MODIFIED_304);\n \treturn;\n }\n if (tr == null) {\n response.setContentType(\"image/png\");\n response.setIntHeader(\"Content-Length\", blankpng.length);\n OutputStream os = response.getOutputStream();\n os.write(blankpng);\n return;\n }\n // Got tile, package up for response\n response.setDateHeader(\"Last-Modified\", tr.lastModified);\n response.setIntHeader(\"Content-Length\", tr.image.length());\n if (tr.format == ImageEncoding.PNG) {\n response.setContentType(\"image/png\");\n }\n else {\n response.setContentType(\"image/jpeg\");\n }\n ServletOutputStream out = response.getOutputStream();\n out.write(tr.image.buffer(), 0, tr.image.length());\n out.flush();",
" }",
" private void handleFace(HttpServletResponse response, String uri) throws IOException, ServletException {\n String[] suri = uri.split(\"[/\\\\.]\");\n if (suri.length < 3) { // 3 parts : face ID, player name, png\n response.sendError(HttpStatus.NOT_FOUND_404);\n return;\n }\n // Find type\n PlayerFaces.FaceType ft = PlayerFaces.FaceType.byID(suri[0]);\n if (ft == null) {\n response.sendError(HttpStatus.NOT_FOUND_404);\n return;\n }\n BufferInputStream bis = null;\n if (core.playerfacemgr != null) {\n bis = core.playerfacemgr.storage.getPlayerFaceImage(suri[1], ft);\n }\n if (bis == null) {\n response.sendError(HttpStatus.NOT_FOUND_404);\n return;\n }\n // Got image, package up for response\n response.setIntHeader(\"Content-Length\", bis.length());\n response.setContentType(\"image/png\");\n ServletOutputStream out = response.getOutputStream();\n out.write(bis.buffer(), 0, bis.length());\n out.flush();\n }",
" private void handleMarkers(HttpServletResponse response, String uri) throws IOException, ServletException {\n String[] suri = uri.split(\"/\");\n // If json file in last part\n if ((suri.length == 1) && suri[0].startsWith(\"marker_\") && suri[0].endsWith(\".json\")) {\n String content = core.getDefaultMapStorage().getMarkerFile(suri[0].substring(7, suri[0].length() - 5));\n response.setContentType(\"application/json\");\n PrintWriter pw = response.getWriter();\n pw.print(content);\n pw.flush();\n return;\n }\n // If png, make marker ID\n if (suri[suri.length-1].endsWith(\".png\")) {\n BufferInputStream bis = core.getDefaultMapStorage().getMarkerImage(uri.substring(0, uri.length()-4));\n // Got image, package up for response\n response.setIntHeader(\"Content-Length\", bis.length());\n response.setContentType(\"image/png\");\n ServletOutputStream out = response.getOutputStream();\n out.write(bis.buffer(), 0, bis.length());\n out.flush();\n return;\n }\n response.sendError(HttpStatus.NOT_FOUND_404);\n }",
" public void setCore(DynmapCore core) {\n this.core = core;\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [50], "buggy_code_start_loc": [49], "filenames": ["DynmapCore/src/main/java/org/dynmap/servlet/MapStorageResourceHandler.java"], "fixing_code_end_loc": [54], "fixing_code_start_loc": [49], "message": "In Webbukkit Dynmap 3.0-beta-3 or below, due to a missing login check in servlet/MapStorageHandler.java, an attacker can see a map image without login even if victim enables login-required in setting.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dynmap_project:dynmap:*:*:*:*:*:*:*:*", "matchCriteriaId": "10C67B48-312F-4A2C-9FC8-174028401A86", "versionEndExcluding": "3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:dynmap_project:dynmap:3.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "BB14CD41-5A40-46F5-B458-797C0724501B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:dynmap_project:dynmap:3.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "856831C2-772A-4472-92A7-99AB91154735", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:dynmap_project:dynmap:3.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "257ADFCF-9444-402D-97F6-AEB3379B04BB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:dynmap_project:dynmap:3.0:rc3:*:*:*:*:*:*", "matchCriteriaId": "19BA4C5F-1600-46E2-9BE1-0DB74F729657", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Webbukkit Dynmap 3.0-beta-3 or below, due to a missing login check in servlet/MapStorageHandler.java, an attacker can see a map image without login even if victim enables login-required in setting."}, {"lang": "es", "value": "En Webbukkit Dynmap 3.0-beta-3 o inferior, debido a una falta de comprobaci\u00f3n de inicio de sesi\u00f3n en servlet / MapStorageHandler.java, un atacante puede ver una imagen del mapa sin iniciar sesi\u00f3n, incluso si la v\u00edctima habilita el inicio de sesi\u00f3n requerido en la configuraci\u00f3n."}], "evaluatorComment": null, "id": "CVE-2019-12395", "lastModified": "2021-11-08T19:47:10.193", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-05-28T13:29:00.490", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://jvn.jp/en/jp/JVN89046645/index.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/webbukkit/dynmap/commit/641f142cd3ccdcbfb04eda3059be22dd9ed93783"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/webbukkit/dynmap/issues/2474"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/webbukkit/dynmap/pull/2475"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/webbukkit/dynmap/commit/641f142cd3ccdcbfb04eda3059be22dd9ed93783"}, "type": "CWE-287"}
| 249
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package org.dynmap.servlet;",
"import org.dynmap.DynmapCore;\nimport org.dynmap.DynmapWorld;\nimport org.dynmap.MapType.ImageEncoding;\nimport org.dynmap.PlayerFaces;\nimport org.dynmap.storage.MapStorage;\nimport org.dynmap.storage.MapStorageTile;\nimport org.dynmap.storage.MapStorageTile.TileRead;\nimport org.dynmap.utils.BufferInputStream;\nimport org.eclipse.jetty.http.HttpStatus;\nimport org.eclipse.jetty.server.Request;\nimport org.eclipse.jetty.server.handler.AbstractHandler;",
"import javax.imageio.ImageIO;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletOutputStream;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;",
"import java.awt.image.BufferedImage;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.io.OutputStream;",
"public class MapStorageResourceHandler extends AbstractHandler {",
" private DynmapCore core;\n private byte[] blankpng;\n private long blankpnghash = 0x12345678;\n \n public MapStorageResourceHandler() {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n BufferedImage blank = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB);\n try {\n ImageIO.write(blank, \"png\", baos);\n blankpng = baos.toByteArray();\n } catch (IOException e) {\n }\n \n }\n @Override\n public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {\n String path = baseRequest.getPathInfo();\n int soff = 0, eoff;\n // We're handling this request\n baseRequest.setHandled(true);",
" if(core.getLoginRequired()\n && request.getSession(true).getAttribute(LoginServlet.USERID_ATTRIB) == null){\n response.sendError(HttpStatus.UNAUTHORIZED_401);\n return;\n }",
" if (path.charAt(0) == '/') soff = 1;\n eoff = path.indexOf('/', soff);\n if (soff < 0) {\n response.sendError(HttpStatus.NOT_FOUND_404);\n return;\n }\n String world = path.substring(soff, eoff);\n String uri = path.substring(eoff+1);\n // If faces directory, handle faces\n if (world.equals(\"faces\")) {\n handleFace(response, uri);\n return;\n }\n // If markers directory, handle markers\n if (world.equals(\"_markers_\")) {\n handleMarkers(response, uri);\n return;\n }",
" DynmapWorld w = null;\n if (core.mapManager != null) {\n w = core.mapManager.getWorld(world);\n }\n // If world not found quit\n if (w == null) {\n response.setContentType(\"image/png\");\n OutputStream os = response.getOutputStream();\n os.write(blankpng);\n return;\n }\n MapStorage store = w.getMapStorage(); // Get storage handler\n // Get tile reference, based on URI and world\n MapStorageTile tile = store.getTile(w, uri);\n if (tile == null) {\n response.setContentType(\"image/png\");\n OutputStream os = response.getOutputStream();\n os.write(blankpng);\n return;\n }\n // Read tile\n TileRead tr = null;\n if (tile.getReadLock(5000)) {\n tr = tile.read();\n tile.releaseReadLock();\n }\n response.setHeader(\"Cache-Control\", \"max-age=0,must-revalidate\");\n String etag;\n if (tr == null) {\n \tetag = \"\\\"\" + blankpnghash + \"\\\"\";\n }\n else {\n \tetag = \"\\\"\" + tr.hashCode + \"\\\"\";\n }\n response.setHeader(\"ETag\", etag);\n String ifnullmatch = request.getHeader(\"If-None-Match\");\n if ((ifnullmatch != null) && ifnullmatch.equals(etag)) {\n response.sendError(HttpStatus.NOT_MODIFIED_304);\n \treturn;\n }\n if (tr == null) {\n response.setContentType(\"image/png\");\n response.setIntHeader(\"Content-Length\", blankpng.length);\n OutputStream os = response.getOutputStream();\n os.write(blankpng);\n return;\n }\n // Got tile, package up for response\n response.setDateHeader(\"Last-Modified\", tr.lastModified);\n response.setIntHeader(\"Content-Length\", tr.image.length());\n if (tr.format == ImageEncoding.PNG) {\n response.setContentType(\"image/png\");\n }\n else {\n response.setContentType(\"image/jpeg\");\n }\n ServletOutputStream out = response.getOutputStream();\n out.write(tr.image.buffer(), 0, tr.image.length());\n out.flush();",
" }",
" private void handleFace(HttpServletResponse response, String uri) throws IOException, ServletException {\n String[] suri = uri.split(\"[/\\\\.]\");\n if (suri.length < 3) { // 3 parts : face ID, player name, png\n response.sendError(HttpStatus.NOT_FOUND_404);\n return;\n }\n // Find type\n PlayerFaces.FaceType ft = PlayerFaces.FaceType.byID(suri[0]);\n if (ft == null) {\n response.sendError(HttpStatus.NOT_FOUND_404);\n return;\n }\n BufferInputStream bis = null;\n if (core.playerfacemgr != null) {\n bis = core.playerfacemgr.storage.getPlayerFaceImage(suri[1], ft);\n }\n if (bis == null) {\n response.sendError(HttpStatus.NOT_FOUND_404);\n return;\n }\n // Got image, package up for response\n response.setIntHeader(\"Content-Length\", bis.length());\n response.setContentType(\"image/png\");\n ServletOutputStream out = response.getOutputStream();\n out.write(bis.buffer(), 0, bis.length());\n out.flush();\n }",
" private void handleMarkers(HttpServletResponse response, String uri) throws IOException, ServletException {\n String[] suri = uri.split(\"/\");\n // If json file in last part\n if ((suri.length == 1) && suri[0].startsWith(\"marker_\") && suri[0].endsWith(\".json\")) {\n String content = core.getDefaultMapStorage().getMarkerFile(suri[0].substring(7, suri[0].length() - 5));\n response.setContentType(\"application/json\");\n PrintWriter pw = response.getWriter();\n pw.print(content);\n pw.flush();\n return;\n }\n // If png, make marker ID\n if (suri[suri.length-1].endsWith(\".png\")) {\n BufferInputStream bis = core.getDefaultMapStorage().getMarkerImage(uri.substring(0, uri.length()-4));\n // Got image, package up for response\n response.setIntHeader(\"Content-Length\", bis.length());\n response.setContentType(\"image/png\");\n ServletOutputStream out = response.getOutputStream();\n out.write(bis.buffer(), 0, bis.length());\n out.flush();\n return;\n }\n response.sendError(HttpStatus.NOT_FOUND_404);\n }",
" public void setCore(DynmapCore core) {\n this.core = core;\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [50], "buggy_code_start_loc": [49], "filenames": ["DynmapCore/src/main/java/org/dynmap/servlet/MapStorageResourceHandler.java"], "fixing_code_end_loc": [54], "fixing_code_start_loc": [49], "message": "In Webbukkit Dynmap 3.0-beta-3 or below, due to a missing login check in servlet/MapStorageHandler.java, an attacker can see a map image without login even if victim enables login-required in setting.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dynmap_project:dynmap:*:*:*:*:*:*:*:*", "matchCriteriaId": "10C67B48-312F-4A2C-9FC8-174028401A86", "versionEndExcluding": "3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:dynmap_project:dynmap:3.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "BB14CD41-5A40-46F5-B458-797C0724501B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:dynmap_project:dynmap:3.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "856831C2-772A-4472-92A7-99AB91154735", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:dynmap_project:dynmap:3.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "257ADFCF-9444-402D-97F6-AEB3379B04BB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:dynmap_project:dynmap:3.0:rc3:*:*:*:*:*:*", "matchCriteriaId": "19BA4C5F-1600-46E2-9BE1-0DB74F729657", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Webbukkit Dynmap 3.0-beta-3 or below, due to a missing login check in servlet/MapStorageHandler.java, an attacker can see a map image without login even if victim enables login-required in setting."}, {"lang": "es", "value": "En Webbukkit Dynmap 3.0-beta-3 o inferior, debido a una falta de comprobaci\u00f3n de inicio de sesi\u00f3n en servlet / MapStorageHandler.java, un atacante puede ver una imagen del mapa sin iniciar sesi\u00f3n, incluso si la v\u00edctima habilita el inicio de sesi\u00f3n requerido en la configuraci\u00f3n."}], "evaluatorComment": null, "id": "CVE-2019-12395", "lastModified": "2021-11-08T19:47:10.193", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-05-28T13:29:00.490", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://jvn.jp/en/jp/JVN89046645/index.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/webbukkit/dynmap/commit/641f142cd3ccdcbfb04eda3059be22dd9ed93783"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/webbukkit/dynmap/issues/2474"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/webbukkit/dynmap/pull/2475"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/webbukkit/dynmap/commit/641f142cd3ccdcbfb04eda3059be22dd9ed93783"}, "type": "CWE-287"}
| 249
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Copyright 2015 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n * Authors: AMD\n *\n */",
"#include <linux/irqdomain.h>\n#include <linux/pci.h>\n#include <linux/pm_domain.h>\n#include <linux/platform_device.h>\n#include <sound/designware_i2s.h>\n#include <sound/pcm.h>",
"#include \"amdgpu.h\"\n#include \"atom.h\"\n#include \"amdgpu_acp.h\"",
"#include \"acp_gfx_if.h\"",
"#define ACP_TILE_ON_MASK \t0x03\n#define ACP_TILE_OFF_MASK \t0x02\n#define ACP_TILE_ON_RETAIN_REG_MASK \t0x1f\n#define ACP_TILE_OFF_RETAIN_REG_MASK \t0x20",
"#define ACP_TILE_P1_MASK \t0x3e\n#define ACP_TILE_P2_MASK \t0x3d\n#define ACP_TILE_DSP0_MASK \t0x3b\n#define ACP_TILE_DSP1_MASK \t0x37",
"#define ACP_TILE_DSP2_MASK \t0x2f",
"#define ACP_DMA_REGS_END\t\t\t0x146c0\n#define ACP_I2S_PLAY_REGS_START\t\t\t0x14840\n#define ACP_I2S_PLAY_REGS_END\t\t\t0x148b4\n#define ACP_I2S_CAP_REGS_START\t\t\t0x148b8\n#define ACP_I2S_CAP_REGS_END\t\t\t0x1496c",
"#define ACP_I2S_COMP1_CAP_REG_OFFSET\t\t0xac\n#define ACP_I2S_COMP2_CAP_REG_OFFSET\t\t0xa8\n#define ACP_I2S_COMP1_PLAY_REG_OFFSET\t\t0x6c\n#define ACP_I2S_COMP2_PLAY_REG_OFFSET\t\t0x68\n#define ACP_BT_PLAY_REGS_START\t\t\t0x14970\n#define ACP_BT_PLAY_REGS_END\t\t\t0x14a24\n#define ACP_BT_COMP1_REG_OFFSET\t\t\t0xac\n#define ACP_BT_COMP2_REG_OFFSET\t\t\t0xa8",
"#define mmACP_PGFSM_RETAIN_REG\t\t\t0x51c9\n#define mmACP_PGFSM_CONFIG_REG\t\t\t0x51ca\n#define mmACP_PGFSM_READ_REG_0\t\t\t0x51cc",
"#define mmACP_MEM_SHUT_DOWN_REQ_LO\t\t0x51f8\n#define mmACP_MEM_SHUT_DOWN_REQ_HI\t\t0x51f9\n#define mmACP_MEM_SHUT_DOWN_STS_LO\t\t0x51fa\n#define mmACP_MEM_SHUT_DOWN_STS_HI\t\t0x51fb",
"#define mmACP_CONTROL\t\t\t\t0x5131\n#define mmACP_STATUS\t\t\t\t0x5133\n#define mmACP_SOFT_RESET\t\t\t0x5134\n#define ACP_CONTROL__ClkEn_MASK \t\t0x1\n#define ACP_SOFT_RESET__SoftResetAud_MASK \t0x100\n#define ACP_SOFT_RESET__SoftResetAudDone_MASK\t0x1000000\n#define ACP_CLOCK_EN_TIME_OUT_VALUE\t\t0x000000FF\n#define ACP_SOFT_RESET_DONE_TIME_OUT_VALUE\t0x000000FF",
"#define ACP_TIMEOUT_LOOP\t\t\t0x000000FF\n#define ACP_DEVS\t\t\t\t4\n#define ACP_SRC_ID\t\t\t\t162",
"enum {\n\tACP_TILE_P1 = 0,\n\tACP_TILE_P2,\n\tACP_TILE_DSP0,\n\tACP_TILE_DSP1,\n\tACP_TILE_DSP2,\n};",
"static int acp_sw_init(void *handle)\n{\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\tadev->acp.parent = adev->dev;",
"\tadev->acp.cgs_device =\n\t\tamdgpu_cgs_create_device(adev);\n\tif (!adev->acp.cgs_device)\n\t\treturn -EINVAL;",
"\treturn 0;\n}",
"static int acp_sw_fini(void *handle)\n{\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\tif (adev->acp.cgs_device)\n\t\tamdgpu_cgs_destroy_device(adev->acp.cgs_device);",
"\treturn 0;\n}",
"struct acp_pm_domain {\n\tvoid *adev;\n\tstruct generic_pm_domain gpd;\n};",
"static int acp_poweroff(struct generic_pm_domain *genpd)\n{\n\tstruct acp_pm_domain *apd;\n\tstruct amdgpu_device *adev;",
"\tapd = container_of(genpd, struct acp_pm_domain, gpd);\n\tif (apd != NULL) {\n\t\tadev = apd->adev;\n\t/* call smu to POWER GATE ACP block\n\t * smu will\n\t * 1. turn off the acp clock\n\t * 2. power off the acp tiles\n\t * 3. check and enter ulv state\n\t */\n\t\tif (adev->powerplay.pp_funcs &&\n\t\t\tadev->powerplay.pp_funcs->set_powergating_by_smu)\n\t\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, true);\n\t}\n\treturn 0;\n}",
"static int acp_poweron(struct generic_pm_domain *genpd)\n{\n\tstruct acp_pm_domain *apd;\n\tstruct amdgpu_device *adev;",
"\tapd = container_of(genpd, struct acp_pm_domain, gpd);\n\tif (apd != NULL) {\n\t\tadev = apd->adev;\n\t/* call smu to UNGATE ACP block\n\t * smu will\n\t * 1. exit ulv\n\t * 2. turn on acp clock\n\t * 3. power on acp tiles\n\t */\n\t\tif (adev->powerplay.pp_funcs->set_powergating_by_smu)\n\t\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, false);\n\t}\n\treturn 0;\n}",
"static struct device *get_mfd_cell_dev(const char *device_name, int r)\n{\n\tchar auto_dev_name[25];\n\tstruct device *dev;",
"\tsnprintf(auto_dev_name, sizeof(auto_dev_name),\n\t\t \"%s.%d.auto\", device_name, r);\n\tdev = bus_find_device_by_name(&platform_bus_type, NULL, auto_dev_name);\n\tdev_info(dev, \"device %s added to pm domain\\n\", auto_dev_name);",
"\treturn dev;\n}",
"/**\n * acp_hw_init - start and test ACP block\n *\n * @adev: amdgpu_device pointer\n *\n */\nstatic int acp_hw_init(void *handle)\n{\n\tint r, i;\n\tuint64_t acp_base;\n\tu32 val = 0;\n\tu32 count = 0;\n\tstruct device *dev;",
"\tstruct i2s_platform_data *i2s_pdata;",
"\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\tconst struct amdgpu_ip_block *ip_block =\n\t\tamdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_ACP);",
"\tif (!ip_block)\n\t\treturn -EINVAL;",
"\tr = amd_acp_hw_init(adev->acp.cgs_device,\n\t\t\t ip_block->version->major, ip_block->version->minor);\n\t/* -ENODEV means board uses AZ rather than ACP */\n\tif (r == -ENODEV) {\n\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, true);\n\t\treturn 0;\n\t} else if (r) {\n\t\treturn r;\n\t}",
"\tif (adev->rmmio_size == 0 || adev->rmmio_size < 0x5289)\n\t\treturn -EINVAL;",
"\tacp_base = adev->rmmio_base;",
"\n\tadev->acp.acp_genpd = kzalloc(sizeof(struct acp_pm_domain), GFP_KERNEL);\n\tif (adev->acp.acp_genpd == NULL)\n\t\treturn -ENOMEM;",
"\tadev->acp.acp_genpd->gpd.name = \"ACP_AUDIO\";\n\tadev->acp.acp_genpd->gpd.power_off = acp_poweroff;\n\tadev->acp.acp_genpd->gpd.power_on = acp_poweron;",
"\n\tadev->acp.acp_genpd->adev = adev;",
"\tpm_genpd_init(&adev->acp.acp_genpd->gpd, NULL, false);",
"\tadev->acp.acp_cell = kcalloc(ACP_DEVS, sizeof(struct mfd_cell),\n\t\t\t\t\t\t\tGFP_KERNEL);\n",
"\tif (adev->acp.acp_cell == NULL)\n\t\treturn -ENOMEM;",
"\n\tadev->acp.acp_res = kcalloc(5, sizeof(struct resource), GFP_KERNEL);\n\tif (adev->acp.acp_res == NULL) {",
"\t\tkfree(adev->acp.acp_cell);\n\t\treturn -ENOMEM;",
"\t}",
"\ti2s_pdata = kcalloc(3, sizeof(struct i2s_platform_data), GFP_KERNEL);\n\tif (i2s_pdata == NULL) {",
"\t\tkfree(adev->acp.acp_res);\n\t\tkfree(adev->acp.acp_cell);\n\t\treturn -ENOMEM;",
"\t}",
"\tswitch (adev->asic_type) {\n\tcase CHIP_STONEY:\n\t\ti2s_pdata[0].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET |\n\t\t\tDW_I2S_QUIRK_16BIT_IDX_OVERRIDE;\n\t\tbreak;\n\tdefault:\n\t\ti2s_pdata[0].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET;\n\t}\n\ti2s_pdata[0].cap = DWC_I2S_PLAY;\n\ti2s_pdata[0].snd_rates = SNDRV_PCM_RATE_8000_96000;\n\ti2s_pdata[0].i2s_reg_comp1 = ACP_I2S_COMP1_PLAY_REG_OFFSET;\n\ti2s_pdata[0].i2s_reg_comp2 = ACP_I2S_COMP2_PLAY_REG_OFFSET;\n\tswitch (adev->asic_type) {\n\tcase CHIP_STONEY:\n\t\ti2s_pdata[1].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET |\n\t\t\tDW_I2S_QUIRK_COMP_PARAM1 |\n\t\t\tDW_I2S_QUIRK_16BIT_IDX_OVERRIDE;\n\t\tbreak;\n\tdefault:\n\t\ti2s_pdata[1].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET |\n\t\t\tDW_I2S_QUIRK_COMP_PARAM1;\n\t}",
"\ti2s_pdata[1].cap = DWC_I2S_RECORD;\n\ti2s_pdata[1].snd_rates = SNDRV_PCM_RATE_8000_96000;\n\ti2s_pdata[1].i2s_reg_comp1 = ACP_I2S_COMP1_CAP_REG_OFFSET;\n\ti2s_pdata[1].i2s_reg_comp2 = ACP_I2S_COMP2_CAP_REG_OFFSET;",
"\ti2s_pdata[2].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET;\n\tswitch (adev->asic_type) {\n\tcase CHIP_STONEY:\n\t\ti2s_pdata[2].quirks |= DW_I2S_QUIRK_16BIT_IDX_OVERRIDE;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}",
"\ti2s_pdata[2].cap = DWC_I2S_PLAY | DWC_I2S_RECORD;\n\ti2s_pdata[2].snd_rates = SNDRV_PCM_RATE_8000_96000;\n\ti2s_pdata[2].i2s_reg_comp1 = ACP_BT_COMP1_REG_OFFSET;\n\ti2s_pdata[2].i2s_reg_comp2 = ACP_BT_COMP2_REG_OFFSET;",
"\tadev->acp.acp_res[0].name = \"acp2x_dma\";\n\tadev->acp.acp_res[0].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[0].start = acp_base;\n\tadev->acp.acp_res[0].end = acp_base + ACP_DMA_REGS_END;",
"\tadev->acp.acp_res[1].name = \"acp2x_dw_i2s_play\";\n\tadev->acp.acp_res[1].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[1].start = acp_base + ACP_I2S_PLAY_REGS_START;\n\tadev->acp.acp_res[1].end = acp_base + ACP_I2S_PLAY_REGS_END;",
"\tadev->acp.acp_res[2].name = \"acp2x_dw_i2s_cap\";\n\tadev->acp.acp_res[2].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[2].start = acp_base + ACP_I2S_CAP_REGS_START;\n\tadev->acp.acp_res[2].end = acp_base + ACP_I2S_CAP_REGS_END;",
"\tadev->acp.acp_res[3].name = \"acp2x_dw_bt_i2s_play_cap\";\n\tadev->acp.acp_res[3].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[3].start = acp_base + ACP_BT_PLAY_REGS_START;\n\tadev->acp.acp_res[3].end = acp_base + ACP_BT_PLAY_REGS_END;",
"\tadev->acp.acp_res[4].name = \"acp2x_dma_irq\";\n\tadev->acp.acp_res[4].flags = IORESOURCE_IRQ;\n\tadev->acp.acp_res[4].start = amdgpu_irq_create_mapping(adev, 162);\n\tadev->acp.acp_res[4].end = adev->acp.acp_res[4].start;",
"\tadev->acp.acp_cell[0].name = \"acp_audio_dma\";\n\tadev->acp.acp_cell[0].num_resources = 5;\n\tadev->acp.acp_cell[0].resources = &adev->acp.acp_res[0];\n\tadev->acp.acp_cell[0].platform_data = &adev->asic_type;\n\tadev->acp.acp_cell[0].pdata_size = sizeof(adev->asic_type);",
"\tadev->acp.acp_cell[1].name = \"designware-i2s\";\n\tadev->acp.acp_cell[1].num_resources = 1;\n\tadev->acp.acp_cell[1].resources = &adev->acp.acp_res[1];\n\tadev->acp.acp_cell[1].platform_data = &i2s_pdata[0];\n\tadev->acp.acp_cell[1].pdata_size = sizeof(struct i2s_platform_data);",
"\tadev->acp.acp_cell[2].name = \"designware-i2s\";\n\tadev->acp.acp_cell[2].num_resources = 1;\n\tadev->acp.acp_cell[2].resources = &adev->acp.acp_res[2];\n\tadev->acp.acp_cell[2].platform_data = &i2s_pdata[1];\n\tadev->acp.acp_cell[2].pdata_size = sizeof(struct i2s_platform_data);",
"\tadev->acp.acp_cell[3].name = \"designware-i2s\";\n\tadev->acp.acp_cell[3].num_resources = 1;\n\tadev->acp.acp_cell[3].resources = &adev->acp.acp_res[3];\n\tadev->acp.acp_cell[3].platform_data = &i2s_pdata[2];\n\tadev->acp.acp_cell[3].pdata_size = sizeof(struct i2s_platform_data);",
"\tr = mfd_add_hotplug_devices(adev->acp.parent, adev->acp.acp_cell,\n\t\t\t\t\t\t\t\tACP_DEVS);\n\tif (r)",
"\t\treturn r;",
"\n\tfor (i = 0; i < ACP_DEVS ; i++) {\n\t\tdev = get_mfd_cell_dev(adev->acp.acp_cell[i].name, i);\n\t\tr = pm_genpd_add_device(&adev->acp.acp_genpd->gpd, dev);\n\t\tif (r) {\n\t\t\tdev_err(dev, \"Failed to add dev to genpd\\n\");",
"\t\t\treturn r;",
"\t\t}\n\t}",
"\n\t/* Assert Soft reset of ACP */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);",
"\tval |= ACP_SOFT_RESET__SoftResetAud_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val);",
"\tcount = ACP_SOFT_RESET_DONE_TIME_OUT_VALUE;\n\twhile (true) {\n\t\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);\n\t\tif (ACP_SOFT_RESET__SoftResetAudDone_MASK ==\n\t\t (val & ACP_SOFT_RESET__SoftResetAudDone_MASK))\n\t\t\tbreak;\n\t\tif (--count == 0) {\n\t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");",
"\t\t\treturn -ETIMEDOUT;",
"\t\t}\n\t\tudelay(100);\n\t}\n\t/* Enable clock to ACP and wait until the clock is enabled */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_CONTROL);\n\tval = val | ACP_CONTROL__ClkEn_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_CONTROL, val);",
"\tcount = ACP_CLOCK_EN_TIME_OUT_VALUE;",
"\twhile (true) {\n\t\tval = cgs_read_register(adev->acp.cgs_device, mmACP_STATUS);\n\t\tif (val & (u32) 0x1)\n\t\t\tbreak;\n\t\tif (--count == 0) {\n\t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");",
"\t\t\treturn -ETIMEDOUT;",
"\t\t}\n\t\tudelay(100);\n\t}\n\t/* Deassert the SOFT RESET flags */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);\n\tval &= ~ACP_SOFT_RESET__SoftResetAud_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val);\n\treturn 0;",
"",
"}",
"/**\n * acp_hw_fini - stop the hardware block\n *\n * @adev: amdgpu_device pointer\n *\n */\nstatic int acp_hw_fini(void *handle)\n{\n\tint i, ret;\n\tu32 val = 0;\n\tu32 count = 0;\n\tstruct device *dev;\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\t/* return early if no ACP */\n\tif (!adev->acp.acp_genpd) {\n\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, false);\n\t\treturn 0;\n\t}",
"\t/* Assert Soft reset of ACP */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);",
"\tval |= ACP_SOFT_RESET__SoftResetAud_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val);",
"\tcount = ACP_SOFT_RESET_DONE_TIME_OUT_VALUE;\n\twhile (true) {\n\t\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);\n\t\tif (ACP_SOFT_RESET__SoftResetAudDone_MASK ==\n\t\t (val & ACP_SOFT_RESET__SoftResetAudDone_MASK))\n\t\t\tbreak;\n\t\tif (--count == 0) {\n\t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");\n\t\t\treturn -ETIMEDOUT;\n\t\t}\n\t\tudelay(100);\n\t}\n\t/* Disable ACP clock */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_CONTROL);\n\tval &= ~ACP_CONTROL__ClkEn_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_CONTROL, val);",
"\tcount = ACP_CLOCK_EN_TIME_OUT_VALUE;",
"\twhile (true) {\n\t\tval = cgs_read_register(adev->acp.cgs_device, mmACP_STATUS);\n\t\tif (val & (u32) 0x1)\n\t\t\tbreak;\n\t\tif (--count == 0) {\n\t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");\n\t\t\treturn -ETIMEDOUT;\n\t\t}\n\t\tudelay(100);\n\t}",
"\tfor (i = 0; i < ACP_DEVS ; i++) {\n\t\tdev = get_mfd_cell_dev(adev->acp.acp_cell[i].name, i);\n\t\tret = pm_genpd_remove_device(dev);\n\t\t/* If removal fails, dont giveup and try rest */\n\t\tif (ret)\n\t\t\tdev_err(dev, \"remove dev from genpd failed\\n\");\n\t}",
"\tmfd_remove_devices(adev->acp.parent);\n\tkfree(adev->acp.acp_res);\n\tkfree(adev->acp.acp_genpd);\n\tkfree(adev->acp.acp_cell);",
"\treturn 0;\n}",
"static int acp_suspend(void *handle)\n{\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\t/* power up on suspend */\n\tif (!adev->acp.acp_cell)\n\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, false);\n\treturn 0;\n}",
"static int acp_resume(void *handle)\n{\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\t/* power down again on resume */\n\tif (!adev->acp.acp_cell)\n\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, true);\n\treturn 0;\n}",
"static int acp_early_init(void *handle)\n{\n\treturn 0;\n}",
"static bool acp_is_idle(void *handle)\n{\n\treturn true;\n}",
"static int acp_wait_for_idle(void *handle)\n{\n\treturn 0;\n}",
"static int acp_soft_reset(void *handle)\n{\n\treturn 0;\n}",
"static int acp_set_clockgating_state(void *handle,\n\t\t\t\t enum amd_clockgating_state state)\n{\n\treturn 0;\n}",
"static int acp_set_powergating_state(void *handle,\n\t\t\t\t enum amd_powergating_state state)\n{\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;\n\tbool enable = state == AMD_PG_STATE_GATE ? true : false;",
"\tif (adev->powerplay.pp_funcs &&\n\t\tadev->powerplay.pp_funcs->set_powergating_by_smu)\n\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, enable);",
"\treturn 0;\n}",
"static const struct amd_ip_funcs acp_ip_funcs = {\n\t.name = \"acp_ip\",\n\t.early_init = acp_early_init,\n\t.late_init = NULL,\n\t.sw_init = acp_sw_init,\n\t.sw_fini = acp_sw_fini,\n\t.hw_init = acp_hw_init,\n\t.hw_fini = acp_hw_fini,\n\t.suspend = acp_suspend,\n\t.resume = acp_resume,\n\t.is_idle = acp_is_idle,\n\t.wait_for_idle = acp_wait_for_idle,\n\t.soft_reset = acp_soft_reset,\n\t.set_clockgating_state = acp_set_clockgating_state,\n\t.set_powergating_state = acp_set_powergating_state,\n};",
"const struct amdgpu_ip_block_version acp_ip_block =\n{\n\t.type = AMD_IP_BLOCK_TYPE_ACP,\n\t.major = 2,\n\t.minor = 2,\n\t.rev = 0,\n\t.funcs = &acp_ip_funcs,\n};"
] |
[
1,
1,
1,
1,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
1,
1,
1,
0,
1,
1,
1,
0,
1,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [395], "buggy_code_start_loc": [192], "filenames": ["drivers/gpu/drm/amd/amdgpu/amdgpu_acp.c"], "fixing_code_end_loc": [406], "fixing_code_start_loc": [192], "message": "** DISPUTED ** Four memory leaks in the acp_hw_init() function in drivers/gpu/drm/amd/amdgpu/amdgpu_acp.c in the Linux kernel before 5.3.8 allow attackers to cause a denial of service (memory consumption) by triggering mfd_add_hotplug_devices() or pm_genpd_add_device() failures, aka CID-57be09c6e874. NOTE: third parties dispute the relevance of this because the attacker must already have privileges for module loading.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "AEC4B6C4-7934-4B29-A754-F6B88C80CF6E", "versionEndExcluding": "5.3.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:19.04:*:*:*:*:*:*:*", "matchCriteriaId": "CD783B0C-9246-47D9-A937-6144FE8BFF0F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:19.10:*:*:*:*:*:*:*", "matchCriteriaId": "A31C8344-3E02-4EB8-8BD8-4C84B7959624", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "** DISPUTED ** Four memory leaks in the acp_hw_init() function in drivers/gpu/drm/amd/amdgpu/amdgpu_acp.c in the Linux kernel before 5.3.8 allow attackers to cause a denial of service (memory consumption) by triggering mfd_add_hotplug_devices() or pm_genpd_add_device() failures, aka CID-57be09c6e874. NOTE: third parties dispute the relevance of this because the attacker must already have privileges for module loading."}, {"lang": "es", "value": "** EN DISPUTA ** Cuatro p\u00e9rdidas de memoria en la funci\u00f3n acp_hw_init() en el archivo drivers/gpu/drm/amd/amdgpu/amdgpu_acp.c en el kernel de Linux versiones anteriores a la versi\u00f3n 5.3.8, permiten a atacantes causar una denegaci\u00f3n de servicio (consumo de memoria) al desencadenar fallos de la funci\u00f3n mfd_add_hotplug_devices() o pm_genpd_add_device(), tambi\u00e9n se conoce como CID-57be09c6e874. NOTA: terceros discuten la relevancia de esto porque el atacante ya debe tener privilegios para cargar el m\u00f3dulo."}], "evaluatorComment": null, "id": "CVE-2019-19067", "lastModified": "2020-09-25T18:15:14.050", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.9, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 4.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:H/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 0.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-11-18T06:15:12.797", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-12/msg00029.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.suse.com/show_bug.cgi?id=1157180"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v5.x/ChangeLog-5.3.8"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/57be09c6e8747bf48704136d9e3f92bfb93f5725"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/4208-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/4226-1/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://usn.ubuntu.com/4526-1/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-401"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/57be09c6e8747bf48704136d9e3f92bfb93f5725"}, "type": "CWE-401"}
| 250
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Copyright 2015 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n * Authors: AMD\n *\n */",
"#include <linux/irqdomain.h>\n#include <linux/pci.h>\n#include <linux/pm_domain.h>\n#include <linux/platform_device.h>\n#include <sound/designware_i2s.h>\n#include <sound/pcm.h>",
"#include \"amdgpu.h\"\n#include \"atom.h\"\n#include \"amdgpu_acp.h\"",
"#include \"acp_gfx_if.h\"",
"#define ACP_TILE_ON_MASK \t0x03\n#define ACP_TILE_OFF_MASK \t0x02\n#define ACP_TILE_ON_RETAIN_REG_MASK \t0x1f\n#define ACP_TILE_OFF_RETAIN_REG_MASK \t0x20",
"#define ACP_TILE_P1_MASK \t0x3e\n#define ACP_TILE_P2_MASK \t0x3d\n#define ACP_TILE_DSP0_MASK \t0x3b\n#define ACP_TILE_DSP1_MASK \t0x37",
"#define ACP_TILE_DSP2_MASK \t0x2f",
"#define ACP_DMA_REGS_END\t\t\t0x146c0\n#define ACP_I2S_PLAY_REGS_START\t\t\t0x14840\n#define ACP_I2S_PLAY_REGS_END\t\t\t0x148b4\n#define ACP_I2S_CAP_REGS_START\t\t\t0x148b8\n#define ACP_I2S_CAP_REGS_END\t\t\t0x1496c",
"#define ACP_I2S_COMP1_CAP_REG_OFFSET\t\t0xac\n#define ACP_I2S_COMP2_CAP_REG_OFFSET\t\t0xa8\n#define ACP_I2S_COMP1_PLAY_REG_OFFSET\t\t0x6c\n#define ACP_I2S_COMP2_PLAY_REG_OFFSET\t\t0x68\n#define ACP_BT_PLAY_REGS_START\t\t\t0x14970\n#define ACP_BT_PLAY_REGS_END\t\t\t0x14a24\n#define ACP_BT_COMP1_REG_OFFSET\t\t\t0xac\n#define ACP_BT_COMP2_REG_OFFSET\t\t\t0xa8",
"#define mmACP_PGFSM_RETAIN_REG\t\t\t0x51c9\n#define mmACP_PGFSM_CONFIG_REG\t\t\t0x51ca\n#define mmACP_PGFSM_READ_REG_0\t\t\t0x51cc",
"#define mmACP_MEM_SHUT_DOWN_REQ_LO\t\t0x51f8\n#define mmACP_MEM_SHUT_DOWN_REQ_HI\t\t0x51f9\n#define mmACP_MEM_SHUT_DOWN_STS_LO\t\t0x51fa\n#define mmACP_MEM_SHUT_DOWN_STS_HI\t\t0x51fb",
"#define mmACP_CONTROL\t\t\t\t0x5131\n#define mmACP_STATUS\t\t\t\t0x5133\n#define mmACP_SOFT_RESET\t\t\t0x5134\n#define ACP_CONTROL__ClkEn_MASK \t\t0x1\n#define ACP_SOFT_RESET__SoftResetAud_MASK \t0x100\n#define ACP_SOFT_RESET__SoftResetAudDone_MASK\t0x1000000\n#define ACP_CLOCK_EN_TIME_OUT_VALUE\t\t0x000000FF\n#define ACP_SOFT_RESET_DONE_TIME_OUT_VALUE\t0x000000FF",
"#define ACP_TIMEOUT_LOOP\t\t\t0x000000FF\n#define ACP_DEVS\t\t\t\t4\n#define ACP_SRC_ID\t\t\t\t162",
"enum {\n\tACP_TILE_P1 = 0,\n\tACP_TILE_P2,\n\tACP_TILE_DSP0,\n\tACP_TILE_DSP1,\n\tACP_TILE_DSP2,\n};",
"static int acp_sw_init(void *handle)\n{\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\tadev->acp.parent = adev->dev;",
"\tadev->acp.cgs_device =\n\t\tamdgpu_cgs_create_device(adev);\n\tif (!adev->acp.cgs_device)\n\t\treturn -EINVAL;",
"\treturn 0;\n}",
"static int acp_sw_fini(void *handle)\n{\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\tif (adev->acp.cgs_device)\n\t\tamdgpu_cgs_destroy_device(adev->acp.cgs_device);",
"\treturn 0;\n}",
"struct acp_pm_domain {\n\tvoid *adev;\n\tstruct generic_pm_domain gpd;\n};",
"static int acp_poweroff(struct generic_pm_domain *genpd)\n{\n\tstruct acp_pm_domain *apd;\n\tstruct amdgpu_device *adev;",
"\tapd = container_of(genpd, struct acp_pm_domain, gpd);\n\tif (apd != NULL) {\n\t\tadev = apd->adev;\n\t/* call smu to POWER GATE ACP block\n\t * smu will\n\t * 1. turn off the acp clock\n\t * 2. power off the acp tiles\n\t * 3. check and enter ulv state\n\t */\n\t\tif (adev->powerplay.pp_funcs &&\n\t\t\tadev->powerplay.pp_funcs->set_powergating_by_smu)\n\t\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, true);\n\t}\n\treturn 0;\n}",
"static int acp_poweron(struct generic_pm_domain *genpd)\n{\n\tstruct acp_pm_domain *apd;\n\tstruct amdgpu_device *adev;",
"\tapd = container_of(genpd, struct acp_pm_domain, gpd);\n\tif (apd != NULL) {\n\t\tadev = apd->adev;\n\t/* call smu to UNGATE ACP block\n\t * smu will\n\t * 1. exit ulv\n\t * 2. turn on acp clock\n\t * 3. power on acp tiles\n\t */\n\t\tif (adev->powerplay.pp_funcs->set_powergating_by_smu)\n\t\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, false);\n\t}\n\treturn 0;\n}",
"static struct device *get_mfd_cell_dev(const char *device_name, int r)\n{\n\tchar auto_dev_name[25];\n\tstruct device *dev;",
"\tsnprintf(auto_dev_name, sizeof(auto_dev_name),\n\t\t \"%s.%d.auto\", device_name, r);\n\tdev = bus_find_device_by_name(&platform_bus_type, NULL, auto_dev_name);\n\tdev_info(dev, \"device %s added to pm domain\\n\", auto_dev_name);",
"\treturn dev;\n}",
"/**\n * acp_hw_init - start and test ACP block\n *\n * @adev: amdgpu_device pointer\n *\n */\nstatic int acp_hw_init(void *handle)\n{\n\tint r, i;\n\tuint64_t acp_base;\n\tu32 val = 0;\n\tu32 count = 0;\n\tstruct device *dev;",
"\tstruct i2s_platform_data *i2s_pdata = NULL;",
"\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\tconst struct amdgpu_ip_block *ip_block =\n\t\tamdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_ACP);",
"\tif (!ip_block)\n\t\treturn -EINVAL;",
"\tr = amd_acp_hw_init(adev->acp.cgs_device,\n\t\t\t ip_block->version->major, ip_block->version->minor);\n\t/* -ENODEV means board uses AZ rather than ACP */\n\tif (r == -ENODEV) {\n\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, true);\n\t\treturn 0;\n\t} else if (r) {\n\t\treturn r;\n\t}",
"\tif (adev->rmmio_size == 0 || adev->rmmio_size < 0x5289)\n\t\treturn -EINVAL;",
"\tacp_base = adev->rmmio_base;",
"\n\tadev->acp.acp_genpd = kzalloc(sizeof(struct acp_pm_domain), GFP_KERNEL);\n\tif (adev->acp.acp_genpd == NULL)\n\t\treturn -ENOMEM;",
"\tadev->acp.acp_genpd->gpd.name = \"ACP_AUDIO\";\n\tadev->acp.acp_genpd->gpd.power_off = acp_poweroff;\n\tadev->acp.acp_genpd->gpd.power_on = acp_poweron;",
"\n\tadev->acp.acp_genpd->adev = adev;",
"\tpm_genpd_init(&adev->acp.acp_genpd->gpd, NULL, false);",
"\tadev->acp.acp_cell = kcalloc(ACP_DEVS, sizeof(struct mfd_cell),\n\t\t\t\t\t\t\tGFP_KERNEL);\n",
"\tif (adev->acp.acp_cell == NULL) {\n\t\tr = -ENOMEM;\n\t\tgoto failure;\n\t}",
"\n\tadev->acp.acp_res = kcalloc(5, sizeof(struct resource), GFP_KERNEL);\n\tif (adev->acp.acp_res == NULL) {",
"\t\tr = -ENOMEM;\n\t\tgoto failure;",
"\t}",
"\ti2s_pdata = kcalloc(3, sizeof(struct i2s_platform_data), GFP_KERNEL);\n\tif (i2s_pdata == NULL) {",
"\t\tr = -ENOMEM;\n\t\tgoto failure;",
"\t}",
"\tswitch (adev->asic_type) {\n\tcase CHIP_STONEY:\n\t\ti2s_pdata[0].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET |\n\t\t\tDW_I2S_QUIRK_16BIT_IDX_OVERRIDE;\n\t\tbreak;\n\tdefault:\n\t\ti2s_pdata[0].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET;\n\t}\n\ti2s_pdata[0].cap = DWC_I2S_PLAY;\n\ti2s_pdata[0].snd_rates = SNDRV_PCM_RATE_8000_96000;\n\ti2s_pdata[0].i2s_reg_comp1 = ACP_I2S_COMP1_PLAY_REG_OFFSET;\n\ti2s_pdata[0].i2s_reg_comp2 = ACP_I2S_COMP2_PLAY_REG_OFFSET;\n\tswitch (adev->asic_type) {\n\tcase CHIP_STONEY:\n\t\ti2s_pdata[1].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET |\n\t\t\tDW_I2S_QUIRK_COMP_PARAM1 |\n\t\t\tDW_I2S_QUIRK_16BIT_IDX_OVERRIDE;\n\t\tbreak;\n\tdefault:\n\t\ti2s_pdata[1].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET |\n\t\t\tDW_I2S_QUIRK_COMP_PARAM1;\n\t}",
"\ti2s_pdata[1].cap = DWC_I2S_RECORD;\n\ti2s_pdata[1].snd_rates = SNDRV_PCM_RATE_8000_96000;\n\ti2s_pdata[1].i2s_reg_comp1 = ACP_I2S_COMP1_CAP_REG_OFFSET;\n\ti2s_pdata[1].i2s_reg_comp2 = ACP_I2S_COMP2_CAP_REG_OFFSET;",
"\ti2s_pdata[2].quirks = DW_I2S_QUIRK_COMP_REG_OFFSET;\n\tswitch (adev->asic_type) {\n\tcase CHIP_STONEY:\n\t\ti2s_pdata[2].quirks |= DW_I2S_QUIRK_16BIT_IDX_OVERRIDE;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}",
"\ti2s_pdata[2].cap = DWC_I2S_PLAY | DWC_I2S_RECORD;\n\ti2s_pdata[2].snd_rates = SNDRV_PCM_RATE_8000_96000;\n\ti2s_pdata[2].i2s_reg_comp1 = ACP_BT_COMP1_REG_OFFSET;\n\ti2s_pdata[2].i2s_reg_comp2 = ACP_BT_COMP2_REG_OFFSET;",
"\tadev->acp.acp_res[0].name = \"acp2x_dma\";\n\tadev->acp.acp_res[0].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[0].start = acp_base;\n\tadev->acp.acp_res[0].end = acp_base + ACP_DMA_REGS_END;",
"\tadev->acp.acp_res[1].name = \"acp2x_dw_i2s_play\";\n\tadev->acp.acp_res[1].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[1].start = acp_base + ACP_I2S_PLAY_REGS_START;\n\tadev->acp.acp_res[1].end = acp_base + ACP_I2S_PLAY_REGS_END;",
"\tadev->acp.acp_res[2].name = \"acp2x_dw_i2s_cap\";\n\tadev->acp.acp_res[2].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[2].start = acp_base + ACP_I2S_CAP_REGS_START;\n\tadev->acp.acp_res[2].end = acp_base + ACP_I2S_CAP_REGS_END;",
"\tadev->acp.acp_res[3].name = \"acp2x_dw_bt_i2s_play_cap\";\n\tadev->acp.acp_res[3].flags = IORESOURCE_MEM;\n\tadev->acp.acp_res[3].start = acp_base + ACP_BT_PLAY_REGS_START;\n\tadev->acp.acp_res[3].end = acp_base + ACP_BT_PLAY_REGS_END;",
"\tadev->acp.acp_res[4].name = \"acp2x_dma_irq\";\n\tadev->acp.acp_res[4].flags = IORESOURCE_IRQ;\n\tadev->acp.acp_res[4].start = amdgpu_irq_create_mapping(adev, 162);\n\tadev->acp.acp_res[4].end = adev->acp.acp_res[4].start;",
"\tadev->acp.acp_cell[0].name = \"acp_audio_dma\";\n\tadev->acp.acp_cell[0].num_resources = 5;\n\tadev->acp.acp_cell[0].resources = &adev->acp.acp_res[0];\n\tadev->acp.acp_cell[0].platform_data = &adev->asic_type;\n\tadev->acp.acp_cell[0].pdata_size = sizeof(adev->asic_type);",
"\tadev->acp.acp_cell[1].name = \"designware-i2s\";\n\tadev->acp.acp_cell[1].num_resources = 1;\n\tadev->acp.acp_cell[1].resources = &adev->acp.acp_res[1];\n\tadev->acp.acp_cell[1].platform_data = &i2s_pdata[0];\n\tadev->acp.acp_cell[1].pdata_size = sizeof(struct i2s_platform_data);",
"\tadev->acp.acp_cell[2].name = \"designware-i2s\";\n\tadev->acp.acp_cell[2].num_resources = 1;\n\tadev->acp.acp_cell[2].resources = &adev->acp.acp_res[2];\n\tadev->acp.acp_cell[2].platform_data = &i2s_pdata[1];\n\tadev->acp.acp_cell[2].pdata_size = sizeof(struct i2s_platform_data);",
"\tadev->acp.acp_cell[3].name = \"designware-i2s\";\n\tadev->acp.acp_cell[3].num_resources = 1;\n\tadev->acp.acp_cell[3].resources = &adev->acp.acp_res[3];\n\tadev->acp.acp_cell[3].platform_data = &i2s_pdata[2];\n\tadev->acp.acp_cell[3].pdata_size = sizeof(struct i2s_platform_data);",
"\tr = mfd_add_hotplug_devices(adev->acp.parent, adev->acp.acp_cell,\n\t\t\t\t\t\t\t\tACP_DEVS);\n\tif (r)",
"\t\tgoto failure;",
"\n\tfor (i = 0; i < ACP_DEVS ; i++) {\n\t\tdev = get_mfd_cell_dev(adev->acp.acp_cell[i].name, i);\n\t\tr = pm_genpd_add_device(&adev->acp.acp_genpd->gpd, dev);\n\t\tif (r) {\n\t\t\tdev_err(dev, \"Failed to add dev to genpd\\n\");",
"\t\t\tgoto failure;",
"\t\t}\n\t}",
"\n\t/* Assert Soft reset of ACP */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);",
"\tval |= ACP_SOFT_RESET__SoftResetAud_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val);",
"\tcount = ACP_SOFT_RESET_DONE_TIME_OUT_VALUE;\n\twhile (true) {\n\t\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);\n\t\tif (ACP_SOFT_RESET__SoftResetAudDone_MASK ==\n\t\t (val & ACP_SOFT_RESET__SoftResetAudDone_MASK))\n\t\t\tbreak;\n\t\tif (--count == 0) {\n\t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");",
"\t\t\tr = -ETIMEDOUT;\n\t\t\tgoto failure;",
"\t\t}\n\t\tudelay(100);\n\t}\n\t/* Enable clock to ACP and wait until the clock is enabled */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_CONTROL);\n\tval = val | ACP_CONTROL__ClkEn_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_CONTROL, val);",
"\tcount = ACP_CLOCK_EN_TIME_OUT_VALUE;",
"\twhile (true) {\n\t\tval = cgs_read_register(adev->acp.cgs_device, mmACP_STATUS);\n\t\tif (val & (u32) 0x1)\n\t\t\tbreak;\n\t\tif (--count == 0) {\n\t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");",
"\t\t\tr = -ETIMEDOUT;\n\t\t\tgoto failure;",
"\t\t}\n\t\tudelay(100);\n\t}\n\t/* Deassert the SOFT RESET flags */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);\n\tval &= ~ACP_SOFT_RESET__SoftResetAud_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val);\n\treturn 0;",
"\nfailure:\n\tkfree(i2s_pdata);\n\tkfree(adev->acp.acp_res);\n\tkfree(adev->acp.acp_cell);\n\tkfree(adev->acp.acp_genpd);\n\treturn r;",
"}",
"/**\n * acp_hw_fini - stop the hardware block\n *\n * @adev: amdgpu_device pointer\n *\n */\nstatic int acp_hw_fini(void *handle)\n{\n\tint i, ret;\n\tu32 val = 0;\n\tu32 count = 0;\n\tstruct device *dev;\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\t/* return early if no ACP */\n\tif (!adev->acp.acp_genpd) {\n\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, false);\n\t\treturn 0;\n\t}",
"\t/* Assert Soft reset of ACP */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);",
"\tval |= ACP_SOFT_RESET__SoftResetAud_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val);",
"\tcount = ACP_SOFT_RESET_DONE_TIME_OUT_VALUE;\n\twhile (true) {\n\t\tval = cgs_read_register(adev->acp.cgs_device, mmACP_SOFT_RESET);\n\t\tif (ACP_SOFT_RESET__SoftResetAudDone_MASK ==\n\t\t (val & ACP_SOFT_RESET__SoftResetAudDone_MASK))\n\t\t\tbreak;\n\t\tif (--count == 0) {\n\t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");\n\t\t\treturn -ETIMEDOUT;\n\t\t}\n\t\tudelay(100);\n\t}\n\t/* Disable ACP clock */\n\tval = cgs_read_register(adev->acp.cgs_device, mmACP_CONTROL);\n\tval &= ~ACP_CONTROL__ClkEn_MASK;\n\tcgs_write_register(adev->acp.cgs_device, mmACP_CONTROL, val);",
"\tcount = ACP_CLOCK_EN_TIME_OUT_VALUE;",
"\twhile (true) {\n\t\tval = cgs_read_register(adev->acp.cgs_device, mmACP_STATUS);\n\t\tif (val & (u32) 0x1)\n\t\t\tbreak;\n\t\tif (--count == 0) {\n\t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");\n\t\t\treturn -ETIMEDOUT;\n\t\t}\n\t\tudelay(100);\n\t}",
"\tfor (i = 0; i < ACP_DEVS ; i++) {\n\t\tdev = get_mfd_cell_dev(adev->acp.acp_cell[i].name, i);\n\t\tret = pm_genpd_remove_device(dev);\n\t\t/* If removal fails, dont giveup and try rest */\n\t\tif (ret)\n\t\t\tdev_err(dev, \"remove dev from genpd failed\\n\");\n\t}",
"\tmfd_remove_devices(adev->acp.parent);\n\tkfree(adev->acp.acp_res);\n\tkfree(adev->acp.acp_genpd);\n\tkfree(adev->acp.acp_cell);",
"\treturn 0;\n}",
"static int acp_suspend(void *handle)\n{\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\t/* power up on suspend */\n\tif (!adev->acp.acp_cell)\n\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, false);\n\treturn 0;\n}",
"static int acp_resume(void *handle)\n{\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;",
"\t/* power down again on resume */\n\tif (!adev->acp.acp_cell)\n\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, true);\n\treturn 0;\n}",
"static int acp_early_init(void *handle)\n{\n\treturn 0;\n}",
"static bool acp_is_idle(void *handle)\n{\n\treturn true;\n}",
"static int acp_wait_for_idle(void *handle)\n{\n\treturn 0;\n}",
"static int acp_soft_reset(void *handle)\n{\n\treturn 0;\n}",
"static int acp_set_clockgating_state(void *handle,\n\t\t\t\t enum amd_clockgating_state state)\n{\n\treturn 0;\n}",
"static int acp_set_powergating_state(void *handle,\n\t\t\t\t enum amd_powergating_state state)\n{\n\tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;\n\tbool enable = state == AMD_PG_STATE_GATE ? true : false;",
"\tif (adev->powerplay.pp_funcs &&\n\t\tadev->powerplay.pp_funcs->set_powergating_by_smu)\n\t\tamdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_ACP, enable);",
"\treturn 0;\n}",
"static const struct amd_ip_funcs acp_ip_funcs = {\n\t.name = \"acp_ip\",\n\t.early_init = acp_early_init,\n\t.late_init = NULL,\n\t.sw_init = acp_sw_init,\n\t.sw_fini = acp_sw_fini,\n\t.hw_init = acp_hw_init,\n\t.hw_fini = acp_hw_fini,\n\t.suspend = acp_suspend,\n\t.resume = acp_resume,\n\t.is_idle = acp_is_idle,\n\t.wait_for_idle = acp_wait_for_idle,\n\t.soft_reset = acp_soft_reset,\n\t.set_clockgating_state = acp_set_clockgating_state,\n\t.set_powergating_state = acp_set_powergating_state,\n};",
"const struct amdgpu_ip_block_version acp_ip_block =\n{\n\t.type = AMD_IP_BLOCK_TYPE_ACP,\n\t.major = 2,\n\t.minor = 2,\n\t.rev = 0,\n\t.funcs = &acp_ip_funcs,\n};"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [395], "buggy_code_start_loc": [192], "filenames": ["drivers/gpu/drm/amd/amdgpu/amdgpu_acp.c"], "fixing_code_end_loc": [406], "fixing_code_start_loc": [192], "message": "** DISPUTED ** Four memory leaks in the acp_hw_init() function in drivers/gpu/drm/amd/amdgpu/amdgpu_acp.c in the Linux kernel before 5.3.8 allow attackers to cause a denial of service (memory consumption) by triggering mfd_add_hotplug_devices() or pm_genpd_add_device() failures, aka CID-57be09c6e874. NOTE: third parties dispute the relevance of this because the attacker must already have privileges for module loading.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "AEC4B6C4-7934-4B29-A754-F6B88C80CF6E", "versionEndExcluding": "5.3.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:19.04:*:*:*:*:*:*:*", "matchCriteriaId": "CD783B0C-9246-47D9-A937-6144FE8BFF0F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:19.10:*:*:*:*:*:*:*", "matchCriteriaId": "A31C8344-3E02-4EB8-8BD8-4C84B7959624", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "** DISPUTED ** Four memory leaks in the acp_hw_init() function in drivers/gpu/drm/amd/amdgpu/amdgpu_acp.c in the Linux kernel before 5.3.8 allow attackers to cause a denial of service (memory consumption) by triggering mfd_add_hotplug_devices() or pm_genpd_add_device() failures, aka CID-57be09c6e874. NOTE: third parties dispute the relevance of this because the attacker must already have privileges for module loading."}, {"lang": "es", "value": "** EN DISPUTA ** Cuatro p\u00e9rdidas de memoria en la funci\u00f3n acp_hw_init() en el archivo drivers/gpu/drm/amd/amdgpu/amdgpu_acp.c en el kernel de Linux versiones anteriores a la versi\u00f3n 5.3.8, permiten a atacantes causar una denegaci\u00f3n de servicio (consumo de memoria) al desencadenar fallos de la funci\u00f3n mfd_add_hotplug_devices() o pm_genpd_add_device(), tambi\u00e9n se conoce como CID-57be09c6e874. NOTA: terceros discuten la relevancia de esto porque el atacante ya debe tener privilegios para cargar el m\u00f3dulo."}], "evaluatorComment": null, "id": "CVE-2019-19067", "lastModified": "2020-09-25T18:15:14.050", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.9, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 4.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:H/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 0.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-11-18T06:15:12.797", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-12/msg00029.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.suse.com/show_bug.cgi?id=1157180"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v5.x/ChangeLog-5.3.8"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/57be09c6e8747bf48704136d9e3f92bfb93f5725"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/4208-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/4226-1/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://usn.ubuntu.com/4526-1/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-401"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/57be09c6e8747bf48704136d9e3f92bfb93f5725"}, "type": "CWE-401"}
| 250
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"namespace MicroweberPackages\\Media;",
"use Conner\\Tagging\\Model\\Tagged;\nuse \\Intervention\\Image\\ImageManagerStatic as Image;",
"",
"use MicroweberPackages\\Media\\Models\\Media;\nuse MicroweberPackages\\Media\\Models\\MediaThumbnail;\nuse MicroweberPackages\\Utils\\Media\\Thumbnailer;\nuse MicroweberPackages\\Utils\\System\\Files;",
"\nclass MediaManager\n{\n public $app;\n public $tables = array();\n public $table_prefix = false;\n public $download_remote_images = false;\n public $no_cache;",
" public $thumbnails_path_in_userfiles = 'cache/thumbnails';",
" public function __construct($app = null)\n {\n if (!is_object($this->app)) {\n if (is_object($app)) {\n $this->app = $app;\n } else {\n $this->app = mw();\n }\n }",
" $this->tables['media'] = 'media';\n }",
" public function get_picture($content_id, $for = 'content', $full = false)\n {\n if ($for == 'post' or $for == 'posts' or $for == 'page' or $for == 'pages') {\n $for = 'content';\n } elseif ($for == 'category' or $for == 'categories') {\n $for = 'categories';\n }",
" $media = app()->media_repository->getPictureByRelIdAndRelType($content_id, $for);\n if (!empty($media)) {",
" if ($full) {\n return $media;\n }\n return $media['filename'];\n }",
" return false;\n }",
" public function get_first_image_from_html($html)\n {\n if (preg_match('/<img.+?src=\"(.+?)\"/', $html, $matches)) {\n return $matches[1];\n } elseif (preg_match('/<img.+?src=\\'(.+?)\\'/', $html, $matches)) {\n return $matches[1];\n } else {\n return false;\n }\n }",
" public function get_by_id($id)\n {",
" $table = $this->tables['media'];\n $id = intval($id);\n if ($id == 0) {\n return false;\n }\n $params = array();\n $params['id'] = $id;\n $params['limit'] = 1;",
" $params['table'] = $table;\n $params['cache_group'] = 'media/' . $id;",
" $q = $this->get($params);\n if (is_array($q) and isset($q[0])) {\n $content = $q[0];",
" if (isset($content['image_options'])) {\n $content['image_options'] = @json_decode($content['image_options'], true);\n }",
"\n } else {\n return false;\n }",
" return $content;\n }",
" public function upload_progress_check()\n {\n if ($this->app->user_manager->is_admin() == false) {\n mw_error('not logged in as admin');\n }\n if (isset($_SERVER['HTTP_REFERER'])) {\n $ref_str = md5($_SERVER['HTTP_REFERER']);\n } else {\n $ref_str = 'no_HTTP_REFERER';\n }\n $ref_str = 'no_HTTP_REFERER';\n $cache_id = 'upload_progress_' . $ref_str;\n $cache_group = 'media/global';",
" $cache_content = $this->app->cache_manager->get($cache_id, $cache_group);\n if ($cache_content != false) {\n if (isset($cache_content['tmp_name']) != false) {\n if (isset($cache_content['f']) != false) {\n $filename = $cache_content['tmp_name'];\n if (is_file($filename)) {\n $filesize = filesize($filename);\n }",
" $filename = $cache_content['f'];",
" if (is_file($filename)) {\n $filesize = filesize($filename);\n }",
" $perc = $this->app->format->percent($filesize, $cache_content['size']);",
" return $perc;\n }\n }\n }\n }",
" public function upload($data)\n {\n if ($this->app->user_manager->is_admin() == false) {\n mw_error('not logged in as admin');\n }\n $files_utils = new Files();",
"\n ini_set('upload_max_filesize', '2500M');\n // ini_set('memory_limit', '256M');\n ini_set('max_execution_time', 0);\n ini_set('post_max_size', '2500M');\n ini_set('max_input_time', 9999999);",
" // ini_set(\"session.upload_progress.enabled\", 1);\n if (isset($_SERVER['HTTP_REFERER'])) {\n $ref_str = md5($_SERVER['HTTP_REFERER']);\n } else {\n $ref_str = 'no_HTTP_REFERER';\n }\n $ref_str = 'no_HTTP_REFERER';\n $cache_id = 'upload_progress_' . $ref_str;\n $cache_group = 'media/global';",
" $target_path = media_base_path() . 'uploaded' . DS;\n $target_path = normalize_path($target_path, 1);",
" if (!is_dir($target_path)) {\n mkdir_recursive($target_path);\n }\n $rerturn = array();",
" if ((!isset($_FILES) or empty($_FILES)) and isset($data['file'])) {\n if (isset($data['name'])) {\n $data['name'] = mw()->url_manager->clean_url_wrappers($data['name']);",
" $is_dangerous_file = $files_utils->is_dangerous_file($data['name']);\n if ($is_dangerous_file) {\n return;\n }",
"\n $f = $target_path . $data['name'];\n if (is_file($f)) {\n $f = $target_path . date('YmdHis') . $data['name'];\n }",
" $df = strpos($data['file'], 'base64,');\n if ($df != false) {\n // $df = substr($data['file'], 0, $df);\n $data['file'] = substr($data['file'], $df + 7);\n $data['file'] = str_replace(' ', '+', $data['file']);\n // d($data['file']);\n }",
" $up = $this->base64_to_file($data['file'], $f);",
" $rerturn['src'] = $this->app->url_manager->link_to_file($f);\n $rerturn['name'] = $data['name'];",
" return json_encode($rerturn);\n }\n } else {\n $allowedExts = array('jpg', 'jpeg', 'gif', 'png', 'bmp');",
" //$upl = $this->app->cache_manager->save($_FILES, $cache_id, $cache_group);\n foreach ($_FILES as $item) {\n $item['name'] = mw()->url_manager->clean_url_wrappers($item['name']);\n $extension = get_file_extension($item['name']);",
" $is_dangerous_file = $files_utils->is_dangerous_file($data['name']);\n if ($is_dangerous_file) {\n return;\n }",
" if (in_array($extension, $allowedExts)) {\n if ($item['error'] > 0) {\n mw_error('Error: ' . $item['error']);\n } else {\n $upl = $this->app->cache_manager->save($item, $cache_id, $cache_group);",
" $f = $target_path . $item['name'];\n if (is_file($f)) {\n $f = $target_path . date('YmdHis') . $item['name'];\n }",
" $progress = (array)$item;\n $progress['f'] = $f;\n $upl = $this->app->cache_manager->save($progress, $cache_id, $cache_group);",
" if (move_uploaded_file($item['tmp_name'], $f)) {\n $rerturn['src'] = $this->app->url_manager->link_to_file($f);\n $rerturn['name'] = $item['name'];\n }\n }\n } else {\n mw_error('Invalid file ext');\n }",
" //\n // $input = fopen(\"php://input\", \"r\");\n // $temp = tmpfile();\n //\n // $realSize = stream_copy_to_stream($input, $temp);\n // fclose($input);\n //\n //\n //\n //\n // $target = fopen($f, \"w\");\n // fseek($temp, 0, SEEK_SET);\n // stream_copy_to_stream($temp, $target);\n // $rerturn['src'] = $this->app->url_manager->link_to_file($f);\n // $rerturn['name'] = $item['name'];\n // fclose($target);\n }\n }",
" exit(json_encode($rerturn));\n }",
" private function base64_to_file($data, $target)\n {\n touch($target);\n if (is_writable($target) == false) {\n exit(\"$target is not writable\");\n }\n $whandle = fopen($target, 'wb');\n stream_filter_append($whandle, 'convert.base64-decode', STREAM_FILTER_WRITE);\n fwrite($whandle, $data);\n fclose($whandle);\n }",
" public function reorder($data)\n {\n $adm = $this->app->user_manager->is_admin();\n if ($adm == false) {\n mw_error('Error: not logged in as admin.' . __FILE__ . __LINE__);\n }",
" $table = $this->tables['media'];\n foreach ($data as $value) {\n if (is_array($value)) {\n $indx = array();\n $i = 0;\n foreach ($value as $value2) {\n $indx[$i] = $value2;\n ++$i;\n }",
" $this->app->database_manager->update_position_field($table, $indx);",
" return true;\n // d($indx);\n }\n }\n }",
" public function delete($data)\n {\n $adm = $this->app->user_manager->is_admin();\n $ids_to_delete = array();\n if (!isset($data['id']) and (!is_array($data) and intval($data) > 0)) {\n $ids_to_delete[] = intval($data);\n } elseif (isset($data['id']) and is_array($data['id'])) {\n $ids_to_delete = $data['id'];\n } elseif (isset($data['id']) and !is_array($data['id'])) {\n $ids_to_delete[] = intval($data['id']);\n } elseif (isset($data['ids']) and is_array($data['ids'])) {\n $ids_to_delete = $data['ids'];\n } elseif (isset($data['ids']) and !is_array($data['ids'])) {\n $ids_to_delete = explode(',', $data['ids']);\n }\n if ($ids_to_delete) {\n foreach ($ids_to_delete as $delete) {\n $c_id = intval($delete);\n $pic_data = $this->get_by_id($c_id);",
"\n if ($adm == false) {\n if ($pic_data['created_by'] != $this->app->user_manager->id()) {\n mw_error('Error: not logged in as admin to delete media.');\n }\n }\n// if (isset($pic_data['filename'])) {\n// $fn_remove = $this->app->url_manager->to_path($pic_data['filename']);\n// if (is_file($fn_remove)) {\n// @unlink($fn_remove);\n// }\n// }",
" $this->app->database_manager->delete_by_id('media', $c_id);\n }",
" return true;\n }\n }",
" public function get_all($params)\n {\n if (!is_array($params)) {\n $params = parse_params($params);\n }\n $table = $this->tables['media'];\n $params['table'] = $table;",
" return $this->app->database_manager->get($params);\n }",
" public function get($params)\n {\n $table = $this->tables['media'];",
" if ($params != false and !is_array($params) and intval($params) > 0) {\n $params2 = array();",
" $params2['rel_type'] = 'content';\n $params2['rel_id'] = intval($params);\n $params = $params2;\n } else {\n $params = parse_params($params);\n }",
" if (!isset($params['rel_type']) and isset($params['for'])) {\n $params['rel_type'] = $this->app->database_manager->assoc_table_name($params['for']);\n }\n if (!isset($params['rel_type'])) {\n $params['rel_type'] = 'content';\n }",
" if (!isset($params['limit'])) {\n $params['limit'] = 'nolimit';\n }",
" $params['table'] = $table;\n $params['order_by'] = 'position ASC';\n//d($params);\n $data = $this->app->database_manager->get($params);\n if (isset($params['single'])) {\n if (isset($data['image_options']) and !is_array($data['image_options'])) {\n $data['image_options'] = @json_decode($data['image_options'], true);\n }\n return $data;\n }\n // if (media_base_url()) {\n if (!empty($data)) {\n $return = array();\n foreach ($data as $item) {\n if (isset($item['filename']) and $item['filename'] != false) {\n if (!stristr($item['filename'], '{SITE_URL}')\n and !stristr($item['filename'], '{MEDIA_URL}')\n and !stristr($item['filename'], '://')\n and !stristr($item['filename'], media_base_url())\n ) {\n $item['filename'] = media_base_url() . $item['filename'];\n }\n }",
" if (isset($item['title']) and $item['title'] != '') {\n $item['title'] = html_entity_decode($item['title']);\n $item['title'] = strip_tags($item['title']);\n $item['title'] = $this->app->format->clean_html($item['title']);\n }",
" if (isset($item['image_options']) and !is_array($item['image_options'])) {\n $item['image_options'] = @json_decode($item['image_options'], true);\n }",
"\n $return[] = $item;\n }",
" $data = $return;\n }\n // }",
" return $data;\n }",
" public function save($data)\n {\n $s = array();",
" if (isset($data['content-id'])) {\n $t = trim($data['content-id']);\n $s['rel_id'] = $t;\n $s['rel_type'] = 'content';\n } elseif (isset($data['content_id'])) {\n $t = trim($data['content_id']);\n $s['rel_id'] = $t;\n $s['rel_type'] = 'content';\n $s['rel_type'] = 'content';\n }",
" if (isset($data['for'])) {\n $t = trim($data['for']);\n $t = $this->app->database_manager->assoc_table_name($t);\n $s['rel_type'] = $t;\n }\n if (isset($data['rel_id'])) {\n $t = $data['rel_id'];\n $s['rel_id'] = $t;\n }\n if (isset($data['rel_type'])) {\n $t = $data['rel_type'];\n $s['rel_type'] = $t;\n }",
" if (isset($data['for-id'])) {\n $t = trim($data['for-id']);\n $s['rel_id'] = $t;\n }",
" if (isset($data['for_id'])) {\n $t = trim($data['for_id']);\n $s['rel_id'] = $t;\n }",
" if (isset($data['id'])) {\n $t = intval($data['id']);\n $s['id'] = $t;\n }",
" if (isset($data['title'])) {\n $t = ($data['title']);\n $s['title'] = $t;\n }\n if (!isset($data['src']) and isset($data['filename'])) {\n $data['src'] = $data['filename'];\n }",
" if (isset($data['src'])) {\n $host = (parse_url(site_url()));",
" $host_dir = false;\n if (isset($host['host'])) {\n $host_dir = $host['host'];\n $host_dir = str_ireplace('www.', '', $host_dir);\n $host_dir = str_ireplace('.', '-', $host_dir);\n }",
" $url2dir = $this->app->url_manager->to_path($data['src']);\n $uploaded_files_dir = media_base_path() . DS . 'uploaded';",
" if (isset($s['rel_type']) and isset($s['rel_id'])) {\n $s['rel_type'] = str_replace('..', '', $s['rel_type']);",
" $move_uploaded_files_dir = media_base_path() . 'downloaded' . DS . $s['rel_type'] . DS;\n $move_uploaded_files_dir_index = media_base_path() . 'downloaded' . DS . $s['rel_type'] . DS . 'index.php';",
" $uploaded_files_dir = normalize_path($uploaded_files_dir);\n if (!is_dir($move_uploaded_files_dir)) {\n mkdir_recursive($move_uploaded_files_dir);\n @touch($move_uploaded_files_dir_index);\n }",
" $url2dir = normalize_path($url2dir, false);",
" $dl_remote = $this->download_remote_images;",
" if (isset($data['allow_remote_download']) and $data['allow_remote_download']) {\n $dl_remote = $data['allow_remote_download'];\n }",
" if ($dl_remote and isset($data['src'])) {\n $ext = get_file_extension($data['src']);\n $data['media_type'] = $this->_guess_media_type_from_file_ext($ext);\n if ($data['media_type'] != false) {\n // starting download",
" $is_remote = strtolower($data['src']);",
" if (strstr($is_remote, 'http:') || strstr($is_remote, 'https:')) {\n $dl_host = (parse_url($is_remote));",
" $dl_host_host_dir = false;\n if (isset($dl_host['host'])) {\n $dl_host_host_dir = $dl_host['host'];\n $dl_host_host_dir = str_ireplace('www.', '', $dl_host_host_dir);\n $dl_host_host_dir = str_ireplace('.', '-', $dl_host_host_dir);\n }",
" $move_uploaded_files_dir = $move_uploaded_files_dir . 'external' . DS;\n if ($dl_host_host_dir) {\n $move_uploaded_files_dir = $move_uploaded_files_dir . $dl_host_host_dir . DS;\n }",
" if (!is_dir($move_uploaded_files_dir)) {\n mkdir_recursive($move_uploaded_files_dir);\n }",
" $newfile = basename($data['src']);",
" $newfile = preg_replace('/[^\\w\\._]+/', '_', $newfile);\n $newfile = $move_uploaded_files_dir . $newfile;",
" if (!is_file($newfile)) {\n mw()->http->url($data['src'])->download($newfile);\n }\n if (is_file($newfile)) {\n $url2dir = $this->app->url_manager->to_path($newfile);\n }\n }\n }\n }",
" if (is_file($url2dir)) {\n $data['src'] = $this->app->url_manager->link_to_file($url2dir);\n }\n }",
" $s['filename'] = $data['src'];\n }",
" if (!isset($data['position']) and !isset($s['id'])) {\n $s['position'] = 9999999;\n }",
" if (isset($data['for_id'])) {\n $t = trim($data['for_id']);\n $s['rel_id'] = $t;\n }",
" if ((!isset($s['id']) or (isset($s['id']) and $s['id'] == 0))\n and isset($s['filename'])\n and isset($s['rel_id'])\n and isset($s['rel_type'])\n ) {\n $s['filename'] = str_replace(site_url(), '{SITE_URL}', $s['filename']);\n $check = array();\n $check['rel_type'] = $s['rel_type'];\n $check['rel_id'] = $s['rel_id'];\n $check['filename'] = $s['filename'];\n $check['single'] = true;\n $check = $this->get_all($check);\n if (isset($check['id'])) {\n $s['id'] = $check['id'];\n }\n }",
" if (!isset($s['id']) and isset($s['filename']) and !isset($data['media_type'])) {\n $ext = get_file_extension($s['filename']);\n $data['media_type'] = $this->_guess_media_type_from_file_ext($ext);\n }",
" if (isset($data['media_type'])) {\n $t = $this->app->database_manager->escape_string($data['media_type']);\n $s['media_type'] = $t;\n }",
" if (isset($data['tags'])) {\n $s['tags'] = $data['tags'];\n }",
"\n if (isset($data['image_options'])) {\n $s['image_options'] = @json_encode($data['image_options']);\n }",
" if (isset($s['filename']) && is_array($s['filename'])) {\n if (isset($s['filename']['error'])) {\n return false;\n }\n }",
" if (isset($s['rel_type']) and isset($s['rel_id'])) {\n $s['rel_id'] = trim($s['rel_id']);\n $table = $this->tables['media'];\n $s = $this->app->database_manager->extended_save($table, $s);\n $this->app->cache_manager->delete('media');",
" return $s;\n } elseif (isset($s['id'])) {\n $table = $this->tables['media'];\n $s = $this->app->database_manager->extended_save($table, $s);\n $this->app->cache_manager->delete('media');",
" return $s;\n } else {\n mw_error('Invalid data');\n }\n }",
" public function tags($media_id = false, $return_full = false)\n {\n /* $data = array();\n $data['table'] = $this->tables['media'];\n if ($media_id) {\n $data['id'] = intval($media_id);\n }\n return $this->app->tags_manager->get_values($data, $return_full);*/",
" $query = Tagged::query();\n $query->where('taggable_type', 'media');",
" if ($media_id) {\n $query->where('taggable_id', $media_id);\n }\n $tags = $query->get();\n $pluck = $tags->pluck('tag_name');\n if ($return_full) {\n return $tags;\n } else {\n return $pluck->toArray();\n }\n }",
"\n public function pixum($width = 150, $height = false)\n {\n $cache_folder = media_base_path() . 'pixum' . DS;\n if ($height) {\n $h = $height;\n } else {\n $h = $width;\n }\n $h = intval($h);\n $w = intval($width);\n if ($h == 0) {\n $h = 1;\n }",
" if ($w == 0) {\n $w = 1;\n }\n $extension = '.png';",
" $hash = 'pixum-' . ($h) . 'x' . $w;\n $cachefile = normalize_path($cache_folder . DS . $hash . $extension, false);\n if (!file_exists($cachefile)) {\n $dirname_file = dirname($cachefile);\n if (!is_dir($dirname_file)) {\n mkdir_recursive($dirname_file);\n }",
" $img = imagecreatetruecolor($w, $h);",
" $white = imagecolorallocatealpha($img, 239, 236, 236, 0);\n imagefill($img, 0, 0, $white);\n imagealphablending($img, false);\n imagesavealpha($img, true);\n imagepng($img, $cachefile);\n imagedestroy($img);\n }\n if (file_exists($cachefile)) {\n $url = media_base_url() . 'pixum/' . $hash . $extension;\n } else {\n $url = $this->app->url_manager->site('api_nosession/pixum_img') . '?width=' . $width . '&height=' . $height;\n }",
" return $url;\n }",
" public function pixum_img()\n {\n $mime_type = 'image/png';\n $extension = '.png';\n $cache_folder = media_base_path() . 'pixum' . DS;\n $cache_folder = normalize_path($cache_folder, true);",
" if (!is_dir($cache_folder)) {\n mkdir_recursive($cache_folder);\n }",
" if (isset($_REQUEST['width'])) {\n $w = $_REQUEST['width'];\n } else {\n $w = 1;\n }",
" if (isset($_REQUEST['height'])) {\n $h = $_REQUEST['height'];\n } else {\n $h = 1;\n }\n $h = intval($h);\n $w = intval($w);\n if ($h == 0) {\n $h = 1;\n }",
" if ($w == 0) {\n $w = 1;\n }\n $hash = 'pixum-' . ($h) . 'x' . $w;\n $cachefile = $cache_folder . '/' . $hash . $extension;",
" header('Content-Type: image/png');",
" if (!file_exists($cachefile)) {\n try {\n $img = @imagecreatetruecolor($w, $h);\n } catch (\\Exception $e) {\n exit;\n }",
" if (!$img) {\n exit;\n }",
"\n $white = imagecolorallocatealpha($img, 239, 236, 236, 0);\n imagefill($img, 0, 0, $white);\n imagealphablending($img, false);\n imagesavealpha($img, true);\n imagepng($img, $cachefile);\n imagedestroy($img);\n $fp = fopen($cachefile, 'rb');\n fpassthru($fp);\n exit;\n } else {\n $fp = fopen($cachefile, 'rb');\n fpassthru($fp);\n exit;\n }\n }",
" private function _guess_media_type_from_file_ext($ext)\n {\n $type = false;\n switch ($ext) {\n case 'jpeg':\n case 'jpg':\n case 'png':\n case 'gif':\n case 'bpm':\n case 'svg':\n $type = 'picture';\n break;\n case 'avi':\n case 'ogg':\n case 'flv':\n case 'mp4':\n case 'qt':\n case 'mpeg':\n $type = 'video';\n break;\n case 'mp3':\n case 'wav':\n case 'flac':\n $type = 'audio';\n break;\n }",
" return $type;\n }",
" private function svgScaleHack($svg, $minWidth, $minHeight)\n {\n $reW = '/(.*<svg[^>]* width=\")([\\d.]+px)(.*)/si';\n $reH = '/(.*<svg[^>]* height=\")([\\d.]+px)(.*)/si';\n preg_match($reW, $svg, $mw);\n preg_match($reH, $svg, $mh);",
" if (!isset($mw[2]) and isset($mh[2])) {\n $mw[2] = $mh[2];\n }",
" if (empty($mw)) {\n $width = floatval($minWidth);\n $height = floatval($minHeight);\n } else {\n $width = floatval($mw[2]);\n $height = floatval($mh[2]);\n }",
" if (!$width || !$height) {\n return false;\n }",
" // scale to make width and height big enough\n $scale = 1;\n if ($width < $minWidth) {\n $scale = $minWidth / $width;\n }\n if ($height < $minHeight) {\n $scale = max($scale, ($minHeight / $height));\n }\n $scale = 1;",
" $svg = preg_replace($reW, \"\\${1}{$width}px\\${3}\", $svg);\n $svg = preg_replace($reH, \"\\${1}{$height}px\\${3}\", $svg);",
" return $svg;\n }",
" public function thumbnail($src, $width = 200, $height = null, $crop = null)\n {\n if ($src == false) {\n return $this->pixum($width, $height);\n }",
" if (is_array($src)) {\n extract($src);\n }",
" if (!is_string($src)) {\n return $this->pixum($width, $height);\n }",
"\n $src = html_entity_decode($src);\n $src = htmlspecialchars_decode($src);",
" $surl = $this->app->url_manager->site();\n $src = str_replace('{SITE_URL}', $surl, $src);\n $src = str_replace('%7BSITE_URL%7D', $surl, $src);\n $base_src = str_replace($surl, '', $src);",
" if (!isset($width)) {\n $width = 200;\n } else {\n $width = intval($width);\n }",
" $src = strtok($src, '?');\n if (!isset($height)) {\n $height = 0;\n } else {\n $height = intval($height);\n }",
" $cd = $this->_thumbnails_path() . $width . DS;\n $cd_relative = $this->thumbnails_path_in_userfiles . DS . $width . DS;",
" $ext = strtolower(get_file_extension($base_src));",
"\n $cache = ($base_src . $width . $height) . '.' . $ext;",
" $cache = str_replace(' ', '_', $cache);",
" $ext = strtolower(get_file_extension($src));",
"\n if ($this->_is_webp_supported()) {\n $ext = 'webp';\n }\n $is_remote = false;\n if (!stristr($src, $surl)) {\n if (strstr($src, 'http://')) {\n $is_remote = true;\n } elseif (strstr($src, 'https://')) {\n $is_remote = true;\n }\n }",
" $cache_id_data = array();\n $cache_id_data['mtime'] = '';\n if (!$is_remote and @is_file($base_src)) {\n $cache_id_data['mtime'] = filemtime($base_src);\n }\n $cache_id_data['base_src'] = $base_src;\n $cache_id_data['ext'] = $ext;",
"\n $src_for_db = $src;\n if (!$is_remote) {\n $src_for_db = str_replace(site_url(), '{SITE_URL}', $src);\n }",
" $cache_id_data['src'] = $src_for_db;",
" $cache_id_data['width'] = $width;\n $cache_id_data['height'] = $height;\n if ($crop) {\n $cache_id_data['crop'] = $crop;\n }\n $cache_id_without_ext = 'tn-' . $this->tn_cache_id($cache_id_data);\n $cache_id = $cache_id_without_ext . '.' . $ext;\n $cache_path = $cd . $cache_id;\n $cache_path_relative = $cd_relative . $cache_id;\n $cache_path = normalize_path($cache_path, false);\n $cache_path_relative = normalize_path($cache_path_relative, false);\n //dump($cache_path);\n if ($is_remote) {\n return $src;\n } elseif (@is_file($cache_path)) {\n $cache_path = $this->app->url_manager->link_to_file($cache_path);\n return $cache_path;\n } else {\n if (stristr($base_src, 'pixum_img')) {\n return $this->pixum($width, $height);\n }\n $file_exists_local = url2dir($src);\n if (!@is_file($file_exists_local)) {\n return $this->pixum($width, $height);\n }",
"\n// if (!defined('MW_NO_OUTPUT_CACHE')) {\n// define('MW_NO_OUTPUT_CACHE', true);\n// }",
" // $cache_id_data['cache_path'] = $cache_path;\n $cache_id_data['cache_path_relative'] = $cache_path_relative;\n// if (!get_option($cache_id_without_ext, 'media_tn_temp')) {\n// save_option($cache_id_without_ext, @json_encode($cache_id_data), 'media_tn_temp');\n// }",
"\n //$check = MediaThumbnail::where('filename', $cache_id_without_ext)->first();\n $check = app()->media_repository->getThumbnailCachedItem($cache_id_without_ext);",
"\n if (!$check) {\n $media_tn_temp = new MediaThumbnail();\n $media_tn_temp->filename = $cache_id_without_ext;\n //$media_tn_temp->filename = null;\n $media_tn_temp->image_options = $cache_id_data;\n $media_tn_temp->save();",
" return $this->app->url_manager->site('api/image-generate-tn-request/') . $media_tn_temp->id . '?saved';\n } elseif (isset($check['image_options']) and isset($check['image_options']['cache_path_relative'])) {\n $file_check = normalize_path(userfiles_path() . '' . $check['image_options']['cache_path_relative'], false);\n if (is_file($file_check)) {\n return userfiles_url() . $check['image_options']['cache_path_relative'];\n }",
" }",
" return $this->app->url_manager->site('api/image-generate-tn-request/') . $check['id'] . '?finded';\n }",
" }",
" public function thumbnail_img($params)\n {",
" if (php_can_use_func('ini_set')) {\n ini_set('memory_limit', '-1');\n }",
" // ini_set('memory_limit', '256M');",
" extract($params);",
" if (!isset($width)) {\n $width = 200;\n } else {\n $width = intval($width);\n }",
" if (!isset($height)) {\n $height = null;\n } else {\n $height = intval($height);\n }",
" if (!isset($crop)) {\n $crop = null;\n } else {\n $crop = trim($crop);\n }",
"\n if (!isset($src) or $src == false) {\n return $this->pixum($width, $height);\n }",
" $src = strtok($src, '?');",
" $surl = $this->app->url_manager->site();\n $local = false;",
" $media_url = media_base_url();\n $media_url = trim($media_url);\n $src = str_replace('{SITE_URL}', $surl, $src);\n $src = str_replace('%7BSITE_URL%7D', $surl, $src);\n $src = str_replace('..', '', $src);",
" if (strstr($src, $surl) or strpos($src, $surl)) {\n $src = str_replace($surl . '/', $surl, $src);\n //$src = str_replace($media_url, '', $src);\n $src = str_replace($surl, '', $src);\n $src = ltrim($src, DS);\n $src = ltrim($src, '/');\n $src = rtrim($src, DS);\n $src = rtrim($src, '/');\n //$src = media_base_path() . $src;\n $src = MW_ROOTPATH . $src;\n $src = normalize_path($src, false);\n } else {\n $src = $this->app->url_manager->clean_url_wrappers($src);",
" $src1 = media_base_path() . $src;\n $src1 = normalize_path($src1, false);",
" $src2 = MW_ROOTPATH . $src;\n $src2 = normalize_path($src2, false);\n $src3 = strtolower($src2);",
" if (is_file($src1)) {\n $src = $src1;\n } elseif (is_file($src2)) {\n $src = $src2;\n } elseif (is_file($src3)) {\n $src = $src3;\n } else {\n $no_img = true;",
" if ($no_img) {\n return $this->pixum_img();\n }\n }\n }\n $media_root = media_base_path();",
" $cd = $this->_thumbnails_path() . $width . DS;",
" if (!is_dir($cd)) {\n mkdir_recursive($cd);\n }",
" $index_file = $cd . 'index.html';\n if (!is_file($index_file)) {\n file_put_contents($index_file, 'Thumbnail directory is not allowed');\n }\n if (!isset($ext)) {\n $ext = strtolower(get_file_extension($src));\n }\n if ($ext == 'webp') {\n if (!$this->_is_webp_supported()) {\n $ext = strtolower(get_file_extension($src));",
" }\n }",
" // $cache = md5(serialize($params)) . '.' . $ext;\n $cache = $this->tn_cache_id($params) . '.' . $ext;",
" $cache = str_replace('..', '', $cache);",
" if (isset($cache_id)) {\n $cache = str_replace('..', '', $cache_id);",
" // $cache = url_title($cache_id);\n }\n// if(!isset($cache_path)){\n// $cache_path = $cd . $cache;\n// }\n $cache_path = $cd . $cache;\n if (isset($cache_path_relative)) {\n $cache_path = normalize_path(userfiles_path() . $cache_path_relative, false);\n }\n// if (!file_exists($cache_path)) {\n// if(!isset($cache_path)){\n// $cache_path = $cd . $cache;\n// }\n// }",
" if (file_exists($cache_path)) {",
" if (!isset($return_cache_path)) {",
" // if (!isset($return_cache_path) and isset($params['cache_id'])) {\n // delete_option($cache_id, 'media_tn_temp');\n // }",
"\n if (!headers_sent()) {\n if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {\n $if_modified_since = preg_replace('/;.*$/', '', $_SERVER['HTTP_IF_MODIFIED_SINCE']);\n } else {\n $if_modified_since = '';\n }\n $mtime = filemtime($src);\n $gmdate_mod = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';\n if ($if_modified_since == $gmdate_mod) {\n // header('HTTP/1.0 304 Not Modified');\n }\n }\n }",
" } else {\n $src = $this->app->url_manager->clean_url_wrappers($src);",
" if (file_exists($src)) {\n if (($ext) == 'svg') {\n $res1 = file_get_contents($src);\n $res1 = $this->svgScaleHack($res1, $width, $height);\n file_put_contents($cache_path, $res1);\n } else {\n if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'gif' || $ext == 'png' || $ext == 'bmp' || $ext == 'webp') {",
" if (!$height) {\n $height = $width;\n }\n $tn = new Thumbnailer($src);\n $thumbOptions = array('height' => $height, 'width' => $width);\n if ($crop) {\n $thumbOptions['crop'] = $crop;\n }",
" $cache_path_dir = dirname($cache_path);\n if (!is_dir($cache_path_dir)) {\n mkdir_recursive($cache_path_dir);\n }\n $tn->createThumb($thumbOptions, $cache_path);",
"// if (!isset($return_cache_path) and isset($params['cache_id'])) {\n// delete_option($params['cache_id'], 'media_tn_temp');\n// }",
"\n if (!defined('MW_NO_OUTPUT_CACHE')) {\n define('MW_NO_OUTPUT_CACHE', true);\n }",
"\n unset($tn);",
" } else {\n return $this->pixum_img();\n }\n }\n }\n }",
"\n if (isset($return_cache_path) and $return_cache_path) {\n return $cache_path;\n }",
" if (is_file($cache_path)) {\n $ext = get_file_extension($cache_path);\n if ($ext == 'jpg') {\n $ext = 'jpeg';\n }",
"// if (isset($return_cache_path)) {\n// delete_option($cache_id, 'media_tn_temp');\n// return $cache_path;\n// }",
" if ($ext == 'svg') {\n header('Content-Type: image/svg+xml');\n } else {\n header('Content-Type: image/' . $ext);\n }",
" header('Content-Length: ' . filesize($cache_path));\n readfile($cache_path);\n exit;\n } else {\n return $this->pixum_img();\n }\n }",
"\n public function create_media_dir($params)\n {",
"",
" must_have_access();\n $resp = array();\n // $target_path = media_base_path() . 'uploaded' . DS;\n $target_path = media_uploads_path();\n $fn_path = media_base_path();\n if (isset($_REQUEST['path']) and trim($_REQUEST['path']) != '') {\n $_REQUEST['path'] = urldecode($_REQUEST['path']);",
" $fn_path = $target_path . DS . $_REQUEST['path'] . DS;\n $fn_path = str_replace('..', '', $fn_path);\n $fn_path = normalize_path($fn_path, false);",
" $target_path = $fn_path;\n }",
" if (!isset($_REQUEST['name'])) {",
" $resp = array('error' => 'You must send new_folder parameter');\n } else {\n $fn_new_folder_path = $_REQUEST['name'];\n $fn_new_folder_path = urldecode($fn_new_folder_path);\n $fn_new_folder_path = str_replace('..', '', $fn_new_folder_path);\n $fn_new_folder_path_new = $target_path . DS . $fn_new_folder_path;\n $fn_path = normalize_path($fn_new_folder_path_new, false);\n if (!is_dir($fn_path)) {\n mkdir_recursive($fn_path);\n $resp = array('success' => 'Folder ' . $fn_path . ' is created');\n } else {\n $resp = array('error' => 'Folder ' . $fn_new_folder_path . ' already exists');\n }\n }",
" return $resp;\n }",
" public function delete_media_file($params)\n {\n must_have_access();",
" // $target_path = media_base_path() . 'uploaded' . DS;\n $target_path = media_uploads_path();\n $target_path = normalize_path($target_path, 0);\n $path_restirct = userfiles_path();",
" $fn_remove_path = $_REQUEST['path'];\n $resp = array();\n if ($fn_remove_path != false and is_array($fn_remove_path)) {\n foreach ($fn_remove_path as $key => $value) {\n $fn_remove = $this->app->url_manager->to_path($value);",
" if (isset($fn_remove) and trim($fn_remove) != '' and trim($fn_remove) != 'false') {\n $path = urldecode($fn_remove);\n $path = normalize_path($path, 0);\n $path = str_replace('..', '', $path);\n $path = str_replace($path_restirct, '', $path);\n $target_path = userfiles_path() . DS . $path;\n $target_path = normalize_path($target_path, false);",
" // if (stristr($target_path, media_base_path())) {\n if (stristr($target_path, media_uploads_path())) {\n if (is_dir($target_path)) {\n mw('MicroweberPackages\\Utils\\System\\Files')->rmdir($target_path, false);\n $resp = array('success' => 'Directory ' . $target_path . ' is deleted');\n } elseif (is_file($target_path)) {\n unlink($target_path);\n $resp = array('success' => 'File ' . basename($target_path) . ' is deleted');\n } else {\n $resp = array('error' => 'Not valid file or folder ' . $target_path . ' ');\n }\n } else {\n $resp = array('error' => 'Not allowed to delete on ' . $target_path . ' ');\n }\n }\n }\n }",
" return $resp;\n }",
" public function tn_cache_id($params)\n {",
" $tnhash = crc32(json_encode($params));\n if (isset($params['src'])) {\n $src = basename($params['src']);\n $src = no_ext($src);\n if ($src) {\n $src = str_slug($src);\n $tnhash = $src . '-' . $tnhash;\n }\n }",
" return $tnhash;\n }",
" public function relative_media_start_path()\n {",
"\n static $path;\n if ($path == false) {\n $environment = \\App::environment();",
" $path = MW_MEDIA_FOLDER_NAME . '/' . $environment . '';\n }",
" return $path;\n }",
"\n private function _is_webp_supported()\n {\n if (function_exists('imagewebp') and $_SERVER and isset($_SERVER['HTTP_ACCEPT']) and is_string($_SERVER['HTTP_ACCEPT']) and strpos($_SERVER['HTTP_ACCEPT'], 'image/webp') !== false) {\n return true;\n }\n }",
" private function _thumbnails_path()\n {\n $userfiles_dir = userfiles_path();\n // $userfiles_dir = media_base_path();\n $userfiles_cache_dir = normalize_path($userfiles_dir . $this->thumbnails_path_in_userfiles);",
" // media_base_path() . 'thumbnail' . DS;",
" return $userfiles_cache_dir;\n }\n}"
] |
[
1,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [1202], "buggy_code_start_loc": [6], "filenames": ["src/MicroweberPackages/Media/MediaManager.php"], "fixing_code_end_loc": [1207], "fixing_code_start_loc": [7], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository microweber/microweber prior to 1.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:microweber:microweber:*:*:*:*:*:*:*:*", "matchCriteriaId": "CEE7F7A1-F20B-4F8B-A3DE-989A059B7E0E", "versionEndExcluding": "1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Stored in GitHub repository microweber/microweber prior to 1.3."}, {"lang": "es", "value": "Una vulnerabilidad de tipo Cross-site Scripting (XSS) - Almacenado en el repositorio de GitHub microweber/microweber versiones anteriores a 1.3."}], "evaluatorComment": null, "id": "CVE-2022-0763", "lastModified": "2022-03-08T17:25:17.980", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.7, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-26T10:15:08.547", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/microweber/microweber/commit/c897d0dc159849763a813184d9b75b966c6360bf"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/6de9c621-740d-4d7a-9d77-d90c6c87f3b6"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/microweber/microweber/commit/c897d0dc159849763a813184d9b75b966c6360bf"}, "type": "CWE-79"}
| 251
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"namespace MicroweberPackages\\Media;",
"use Conner\\Tagging\\Model\\Tagged;\nuse \\Intervention\\Image\\ImageManagerStatic as Image;",
"use MicroweberPackages\\Helper\\HTMLClean;",
"use MicroweberPackages\\Media\\Models\\Media;\nuse MicroweberPackages\\Media\\Models\\MediaThumbnail;\nuse MicroweberPackages\\Utils\\Media\\Thumbnailer;\nuse MicroweberPackages\\Utils\\System\\Files;",
"\nclass MediaManager\n{\n public $app;\n public $tables = array();\n public $table_prefix = false;\n public $download_remote_images = false;\n public $no_cache;",
" public $thumbnails_path_in_userfiles = 'cache/thumbnails';",
" public function __construct($app = null)\n {\n if (!is_object($this->app)) {\n if (is_object($app)) {\n $this->app = $app;\n } else {\n $this->app = mw();\n }\n }",
" $this->tables['media'] = 'media';\n }",
" public function get_picture($content_id, $for = 'content', $full = false)\n {\n if ($for == 'post' or $for == 'posts' or $for == 'page' or $for == 'pages') {\n $for = 'content';\n } elseif ($for == 'category' or $for == 'categories') {\n $for = 'categories';\n }",
" $media = app()->media_repository->getPictureByRelIdAndRelType($content_id, $for);\n if (!empty($media)) {",
" if ($full) {\n return $media;\n }\n return $media['filename'];\n }",
" return false;\n }",
" public function get_first_image_from_html($html)\n {\n if (preg_match('/<img.+?src=\"(.+?)\"/', $html, $matches)) {\n return $matches[1];\n } elseif (preg_match('/<img.+?src=\\'(.+?)\\'/', $html, $matches)) {\n return $matches[1];\n } else {\n return false;\n }\n }",
" public function get_by_id($id)\n {",
" $table = $this->tables['media'];\n $id = intval($id);\n if ($id == 0) {\n return false;\n }\n $params = array();\n $params['id'] = $id;\n $params['limit'] = 1;",
" $params['table'] = $table;\n $params['cache_group'] = 'media/' . $id;",
" $q = $this->get($params);\n if (is_array($q) and isset($q[0])) {\n $content = $q[0];",
" if (isset($content['image_options'])) {\n $content['image_options'] = @json_decode($content['image_options'], true);\n }",
"\n } else {\n return false;\n }",
" return $content;\n }",
" public function upload_progress_check()\n {\n if ($this->app->user_manager->is_admin() == false) {\n mw_error('not logged in as admin');\n }\n if (isset($_SERVER['HTTP_REFERER'])) {\n $ref_str = md5($_SERVER['HTTP_REFERER']);\n } else {\n $ref_str = 'no_HTTP_REFERER';\n }\n $ref_str = 'no_HTTP_REFERER';\n $cache_id = 'upload_progress_' . $ref_str;\n $cache_group = 'media/global';",
" $cache_content = $this->app->cache_manager->get($cache_id, $cache_group);\n if ($cache_content != false) {\n if (isset($cache_content['tmp_name']) != false) {\n if (isset($cache_content['f']) != false) {\n $filename = $cache_content['tmp_name'];\n if (is_file($filename)) {\n $filesize = filesize($filename);\n }",
" $filename = $cache_content['f'];",
" if (is_file($filename)) {\n $filesize = filesize($filename);\n }",
" $perc = $this->app->format->percent($filesize, $cache_content['size']);",
" return $perc;\n }\n }\n }\n }",
" public function upload($data)\n {\n if ($this->app->user_manager->is_admin() == false) {\n mw_error('not logged in as admin');\n }\n $files_utils = new Files();",
"\n ini_set('upload_max_filesize', '2500M');\n // ini_set('memory_limit', '256M');\n ini_set('max_execution_time', 0);\n ini_set('post_max_size', '2500M');\n ini_set('max_input_time', 9999999);",
" // ini_set(\"session.upload_progress.enabled\", 1);\n if (isset($_SERVER['HTTP_REFERER'])) {\n $ref_str = md5($_SERVER['HTTP_REFERER']);\n } else {\n $ref_str = 'no_HTTP_REFERER';\n }\n $ref_str = 'no_HTTP_REFERER';\n $cache_id = 'upload_progress_' . $ref_str;\n $cache_group = 'media/global';",
" $target_path = media_base_path() . 'uploaded' . DS;\n $target_path = normalize_path($target_path, 1);",
" if (!is_dir($target_path)) {\n mkdir_recursive($target_path);\n }\n $rerturn = array();",
" if ((!isset($_FILES) or empty($_FILES)) and isset($data['file'])) {\n if (isset($data['name'])) {\n $data['name'] = mw()->url_manager->clean_url_wrappers($data['name']);",
" $is_dangerous_file = $files_utils->is_dangerous_file($data['name']);\n if ($is_dangerous_file) {\n return;\n }",
"\n $f = $target_path . $data['name'];\n if (is_file($f)) {\n $f = $target_path . date('YmdHis') . $data['name'];\n }",
" $df = strpos($data['file'], 'base64,');\n if ($df != false) {\n // $df = substr($data['file'], 0, $df);\n $data['file'] = substr($data['file'], $df + 7);\n $data['file'] = str_replace(' ', '+', $data['file']);\n // d($data['file']);\n }",
" $up = $this->base64_to_file($data['file'], $f);",
" $rerturn['src'] = $this->app->url_manager->link_to_file($f);\n $rerturn['name'] = $data['name'];",
" return json_encode($rerturn);\n }\n } else {\n $allowedExts = array('jpg', 'jpeg', 'gif', 'png', 'bmp');",
" //$upl = $this->app->cache_manager->save($_FILES, $cache_id, $cache_group);\n foreach ($_FILES as $item) {\n $item['name'] = mw()->url_manager->clean_url_wrappers($item['name']);\n $extension = get_file_extension($item['name']);",
" $is_dangerous_file = $files_utils->is_dangerous_file($data['name']);\n if ($is_dangerous_file) {\n return;\n }",
" if (in_array($extension, $allowedExts)) {\n if ($item['error'] > 0) {\n mw_error('Error: ' . $item['error']);\n } else {\n $upl = $this->app->cache_manager->save($item, $cache_id, $cache_group);",
" $f = $target_path . $item['name'];\n if (is_file($f)) {\n $f = $target_path . date('YmdHis') . $item['name'];\n }",
" $progress = (array)$item;\n $progress['f'] = $f;\n $upl = $this->app->cache_manager->save($progress, $cache_id, $cache_group);",
" if (move_uploaded_file($item['tmp_name'], $f)) {\n $rerturn['src'] = $this->app->url_manager->link_to_file($f);\n $rerturn['name'] = $item['name'];\n }\n }\n } else {\n mw_error('Invalid file ext');\n }",
" //\n // $input = fopen(\"php://input\", \"r\");\n // $temp = tmpfile();\n //\n // $realSize = stream_copy_to_stream($input, $temp);\n // fclose($input);\n //\n //\n //\n //\n // $target = fopen($f, \"w\");\n // fseek($temp, 0, SEEK_SET);\n // stream_copy_to_stream($temp, $target);\n // $rerturn['src'] = $this->app->url_manager->link_to_file($f);\n // $rerturn['name'] = $item['name'];\n // fclose($target);\n }\n }",
" exit(json_encode($rerturn));\n }",
" private function base64_to_file($data, $target)\n {\n touch($target);\n if (is_writable($target) == false) {\n exit(\"$target is not writable\");\n }\n $whandle = fopen($target, 'wb');\n stream_filter_append($whandle, 'convert.base64-decode', STREAM_FILTER_WRITE);\n fwrite($whandle, $data);\n fclose($whandle);\n }",
" public function reorder($data)\n {\n $adm = $this->app->user_manager->is_admin();\n if ($adm == false) {\n mw_error('Error: not logged in as admin.' . __FILE__ . __LINE__);\n }",
" $table = $this->tables['media'];\n foreach ($data as $value) {\n if (is_array($value)) {\n $indx = array();\n $i = 0;\n foreach ($value as $value2) {\n $indx[$i] = $value2;\n ++$i;\n }",
" $this->app->database_manager->update_position_field($table, $indx);",
" return true;\n // d($indx);\n }\n }\n }",
" public function delete($data)\n {\n $adm = $this->app->user_manager->is_admin();\n $ids_to_delete = array();\n if (!isset($data['id']) and (!is_array($data) and intval($data) > 0)) {\n $ids_to_delete[] = intval($data);\n } elseif (isset($data['id']) and is_array($data['id'])) {\n $ids_to_delete = $data['id'];\n } elseif (isset($data['id']) and !is_array($data['id'])) {\n $ids_to_delete[] = intval($data['id']);\n } elseif (isset($data['ids']) and is_array($data['ids'])) {\n $ids_to_delete = $data['ids'];\n } elseif (isset($data['ids']) and !is_array($data['ids'])) {\n $ids_to_delete = explode(',', $data['ids']);\n }\n if ($ids_to_delete) {\n foreach ($ids_to_delete as $delete) {\n $c_id = intval($delete);\n $pic_data = $this->get_by_id($c_id);",
"\n if ($adm == false) {\n if ($pic_data['created_by'] != $this->app->user_manager->id()) {\n mw_error('Error: not logged in as admin to delete media.');\n }\n }\n// if (isset($pic_data['filename'])) {\n// $fn_remove = $this->app->url_manager->to_path($pic_data['filename']);\n// if (is_file($fn_remove)) {\n// @unlink($fn_remove);\n// }\n// }",
" $this->app->database_manager->delete_by_id('media', $c_id);\n }",
" return true;\n }\n }",
" public function get_all($params)\n {\n if (!is_array($params)) {\n $params = parse_params($params);\n }\n $table = $this->tables['media'];\n $params['table'] = $table;",
" return $this->app->database_manager->get($params);\n }",
" public function get($params)\n {\n $table = $this->tables['media'];",
" if ($params != false and !is_array($params) and intval($params) > 0) {\n $params2 = array();",
" $params2['rel_type'] = 'content';\n $params2['rel_id'] = intval($params);\n $params = $params2;\n } else {\n $params = parse_params($params);\n }",
" if (!isset($params['rel_type']) and isset($params['for'])) {\n $params['rel_type'] = $this->app->database_manager->assoc_table_name($params['for']);\n }\n if (!isset($params['rel_type'])) {\n $params['rel_type'] = 'content';\n }",
" if (!isset($params['limit'])) {\n $params['limit'] = 'nolimit';\n }",
" $params['table'] = $table;\n $params['order_by'] = 'position ASC';\n//d($params);\n $data = $this->app->database_manager->get($params);\n if (isset($params['single'])) {\n if (isset($data['image_options']) and !is_array($data['image_options'])) {\n $data['image_options'] = @json_decode($data['image_options'], true);\n }\n return $data;\n }\n // if (media_base_url()) {\n if (!empty($data)) {\n $return = array();\n foreach ($data as $item) {\n if (isset($item['filename']) and $item['filename'] != false) {\n if (!stristr($item['filename'], '{SITE_URL}')\n and !stristr($item['filename'], '{MEDIA_URL}')\n and !stristr($item['filename'], '://')\n and !stristr($item['filename'], media_base_url())\n ) {\n $item['filename'] = media_base_url() . $item['filename'];\n }\n }",
" if (isset($item['title']) and $item['title'] != '') {\n $item['title'] = html_entity_decode($item['title']);\n $item['title'] = strip_tags($item['title']);\n $item['title'] = $this->app->format->clean_html($item['title']);\n }",
" if (isset($item['image_options']) and !is_array($item['image_options'])) {\n $item['image_options'] = @json_decode($item['image_options'], true);\n }",
"\n $return[] = $item;\n }",
" $data = $return;\n }\n // }",
" return $data;\n }",
" public function save($data)\n {\n $s = array();",
" if (isset($data['content-id'])) {\n $t = trim($data['content-id']);\n $s['rel_id'] = $t;\n $s['rel_type'] = 'content';\n } elseif (isset($data['content_id'])) {\n $t = trim($data['content_id']);\n $s['rel_id'] = $t;\n $s['rel_type'] = 'content';\n $s['rel_type'] = 'content';\n }",
" if (isset($data['for'])) {\n $t = trim($data['for']);\n $t = $this->app->database_manager->assoc_table_name($t);\n $s['rel_type'] = $t;\n }\n if (isset($data['rel_id'])) {\n $t = $data['rel_id'];\n $s['rel_id'] = $t;\n }\n if (isset($data['rel_type'])) {\n $t = $data['rel_type'];\n $s['rel_type'] = $t;\n }",
" if (isset($data['for-id'])) {\n $t = trim($data['for-id']);\n $s['rel_id'] = $t;\n }",
" if (isset($data['for_id'])) {\n $t = trim($data['for_id']);\n $s['rel_id'] = $t;\n }",
" if (isset($data['id'])) {\n $t = intval($data['id']);\n $s['id'] = $t;\n }",
" if (isset($data['title'])) {\n $t = ($data['title']);\n $s['title'] = $t;\n }\n if (!isset($data['src']) and isset($data['filename'])) {\n $data['src'] = $data['filename'];\n }",
" if (isset($data['src'])) {\n $host = (parse_url(site_url()));",
" $host_dir = false;\n if (isset($host['host'])) {\n $host_dir = $host['host'];\n $host_dir = str_ireplace('www.', '', $host_dir);\n $host_dir = str_ireplace('.', '-', $host_dir);\n }",
" $url2dir = $this->app->url_manager->to_path($data['src']);\n $uploaded_files_dir = media_base_path() . DS . 'uploaded';",
" if (isset($s['rel_type']) and isset($s['rel_id'])) {\n $s['rel_type'] = str_replace('..', '', $s['rel_type']);",
" $move_uploaded_files_dir = media_base_path() . 'downloaded' . DS . $s['rel_type'] . DS;\n $move_uploaded_files_dir_index = media_base_path() . 'downloaded' . DS . $s['rel_type'] . DS . 'index.php';",
" $uploaded_files_dir = normalize_path($uploaded_files_dir);\n if (!is_dir($move_uploaded_files_dir)) {\n mkdir_recursive($move_uploaded_files_dir);\n @touch($move_uploaded_files_dir_index);\n }",
" $url2dir = normalize_path($url2dir, false);",
" $dl_remote = $this->download_remote_images;",
" if (isset($data['allow_remote_download']) and $data['allow_remote_download']) {\n $dl_remote = $data['allow_remote_download'];\n }",
" if ($dl_remote and isset($data['src'])) {\n $ext = get_file_extension($data['src']);\n $data['media_type'] = $this->_guess_media_type_from_file_ext($ext);\n if ($data['media_type'] != false) {\n // starting download",
" $is_remote = strtolower($data['src']);",
" if (strstr($is_remote, 'http:') || strstr($is_remote, 'https:')) {\n $dl_host = (parse_url($is_remote));",
" $dl_host_host_dir = false;\n if (isset($dl_host['host'])) {\n $dl_host_host_dir = $dl_host['host'];\n $dl_host_host_dir = str_ireplace('www.', '', $dl_host_host_dir);\n $dl_host_host_dir = str_ireplace('.', '-', $dl_host_host_dir);\n }",
" $move_uploaded_files_dir = $move_uploaded_files_dir . 'external' . DS;\n if ($dl_host_host_dir) {\n $move_uploaded_files_dir = $move_uploaded_files_dir . $dl_host_host_dir . DS;\n }",
" if (!is_dir($move_uploaded_files_dir)) {\n mkdir_recursive($move_uploaded_files_dir);\n }",
" $newfile = basename($data['src']);",
" $newfile = preg_replace('/[^\\w\\._]+/', '_', $newfile);\n $newfile = $move_uploaded_files_dir . $newfile;",
" if (!is_file($newfile)) {\n mw()->http->url($data['src'])->download($newfile);\n }\n if (is_file($newfile)) {\n $url2dir = $this->app->url_manager->to_path($newfile);\n }\n }\n }\n }",
" if (is_file($url2dir)) {\n $data['src'] = $this->app->url_manager->link_to_file($url2dir);\n }\n }",
" $s['filename'] = $data['src'];\n }",
" if (!isset($data['position']) and !isset($s['id'])) {\n $s['position'] = 9999999;\n }",
" if (isset($data['for_id'])) {\n $t = trim($data['for_id']);\n $s['rel_id'] = $t;\n }",
" if ((!isset($s['id']) or (isset($s['id']) and $s['id'] == 0))\n and isset($s['filename'])\n and isset($s['rel_id'])\n and isset($s['rel_type'])\n ) {\n $s['filename'] = str_replace(site_url(), '{SITE_URL}', $s['filename']);\n $check = array();\n $check['rel_type'] = $s['rel_type'];\n $check['rel_id'] = $s['rel_id'];\n $check['filename'] = $s['filename'];\n $check['single'] = true;\n $check = $this->get_all($check);\n if (isset($check['id'])) {\n $s['id'] = $check['id'];\n }\n }",
" if (!isset($s['id']) and isset($s['filename']) and !isset($data['media_type'])) {\n $ext = get_file_extension($s['filename']);\n $data['media_type'] = $this->_guess_media_type_from_file_ext($ext);\n }",
" if (isset($data['media_type'])) {\n $t = $this->app->database_manager->escape_string($data['media_type']);\n $s['media_type'] = $t;\n }",
" if (isset($data['tags'])) {\n $s['tags'] = $data['tags'];\n }",
"\n if (isset($data['image_options'])) {\n $s['image_options'] = @json_encode($data['image_options']);\n }",
" if (isset($s['filename']) && is_array($s['filename'])) {\n if (isset($s['filename']['error'])) {\n return false;\n }\n }",
" if (isset($s['rel_type']) and isset($s['rel_id'])) {\n $s['rel_id'] = trim($s['rel_id']);\n $table = $this->tables['media'];\n $s = $this->app->database_manager->extended_save($table, $s);\n $this->app->cache_manager->delete('media');",
" return $s;\n } elseif (isset($s['id'])) {\n $table = $this->tables['media'];\n $s = $this->app->database_manager->extended_save($table, $s);\n $this->app->cache_manager->delete('media');",
" return $s;\n } else {\n mw_error('Invalid data');\n }\n }",
" public function tags($media_id = false, $return_full = false)\n {\n /* $data = array();\n $data['table'] = $this->tables['media'];\n if ($media_id) {\n $data['id'] = intval($media_id);\n }\n return $this->app->tags_manager->get_values($data, $return_full);*/",
" $query = Tagged::query();\n $query->where('taggable_type', 'media');",
" if ($media_id) {\n $query->where('taggable_id', $media_id);\n }\n $tags = $query->get();\n $pluck = $tags->pluck('tag_name');\n if ($return_full) {\n return $tags;\n } else {\n return $pluck->toArray();\n }\n }",
"\n public function pixum($width = 150, $height = false)\n {\n $cache_folder = media_base_path() . 'pixum' . DS;\n if ($height) {\n $h = $height;\n } else {\n $h = $width;\n }\n $h = intval($h);\n $w = intval($width);\n if ($h == 0) {\n $h = 1;\n }",
" if ($w == 0) {\n $w = 1;\n }\n $extension = '.png';",
" $hash = 'pixum-' . ($h) . 'x' . $w;\n $cachefile = normalize_path($cache_folder . DS . $hash . $extension, false);\n if (!file_exists($cachefile)) {\n $dirname_file = dirname($cachefile);\n if (!is_dir($dirname_file)) {\n mkdir_recursive($dirname_file);\n }",
" $img = imagecreatetruecolor($w, $h);",
" $white = imagecolorallocatealpha($img, 239, 236, 236, 0);\n imagefill($img, 0, 0, $white);\n imagealphablending($img, false);\n imagesavealpha($img, true);\n imagepng($img, $cachefile);\n imagedestroy($img);\n }\n if (file_exists($cachefile)) {\n $url = media_base_url() . 'pixum/' . $hash . $extension;\n } else {\n $url = $this->app->url_manager->site('api_nosession/pixum_img') . '?width=' . $width . '&height=' . $height;\n }",
" return $url;\n }",
" public function pixum_img()\n {\n $mime_type = 'image/png';\n $extension = '.png';\n $cache_folder = media_base_path() . 'pixum' . DS;\n $cache_folder = normalize_path($cache_folder, true);",
" if (!is_dir($cache_folder)) {\n mkdir_recursive($cache_folder);\n }",
" if (isset($_REQUEST['width'])) {\n $w = $_REQUEST['width'];\n } else {\n $w = 1;\n }",
" if (isset($_REQUEST['height'])) {\n $h = $_REQUEST['height'];\n } else {\n $h = 1;\n }\n $h = intval($h);\n $w = intval($w);\n if ($h == 0) {\n $h = 1;\n }",
" if ($w == 0) {\n $w = 1;\n }\n $hash = 'pixum-' . ($h) . 'x' . $w;\n $cachefile = $cache_folder . '/' . $hash . $extension;",
" header('Content-Type: image/png');",
" if (!file_exists($cachefile)) {\n try {\n $img = @imagecreatetruecolor($w, $h);\n } catch (\\Exception $e) {\n exit;\n }",
" if (!$img) {\n exit;\n }",
"\n $white = imagecolorallocatealpha($img, 239, 236, 236, 0);\n imagefill($img, 0, 0, $white);\n imagealphablending($img, false);\n imagesavealpha($img, true);\n imagepng($img, $cachefile);\n imagedestroy($img);\n $fp = fopen($cachefile, 'rb');\n fpassthru($fp);\n exit;\n } else {\n $fp = fopen($cachefile, 'rb');\n fpassthru($fp);\n exit;\n }\n }",
" private function _guess_media_type_from_file_ext($ext)\n {\n $type = false;\n switch ($ext) {\n case 'jpeg':\n case 'jpg':\n case 'png':\n case 'gif':\n case 'bpm':\n case 'svg':\n $type = 'picture';\n break;\n case 'avi':\n case 'ogg':\n case 'flv':\n case 'mp4':\n case 'qt':\n case 'mpeg':\n $type = 'video';\n break;\n case 'mp3':\n case 'wav':\n case 'flac':\n $type = 'audio';\n break;\n }",
" return $type;\n }",
" private function svgScaleHack($svg, $minWidth, $minHeight)\n {\n $reW = '/(.*<svg[^>]* width=\")([\\d.]+px)(.*)/si';\n $reH = '/(.*<svg[^>]* height=\")([\\d.]+px)(.*)/si';\n preg_match($reW, $svg, $mw);\n preg_match($reH, $svg, $mh);",
" if (!isset($mw[2]) and isset($mh[2])) {\n $mw[2] = $mh[2];\n }",
" if (empty($mw)) {\n $width = floatval($minWidth);\n $height = floatval($minHeight);\n } else {\n $width = floatval($mw[2]);\n $height = floatval($mh[2]);\n }",
" if (!$width || !$height) {\n return false;\n }",
" // scale to make width and height big enough\n $scale = 1;\n if ($width < $minWidth) {\n $scale = $minWidth / $width;\n }\n if ($height < $minHeight) {\n $scale = max($scale, ($minHeight / $height));\n }\n $scale = 1;",
" $svg = preg_replace($reW, \"\\${1}{$width}px\\${3}\", $svg);\n $svg = preg_replace($reH, \"\\${1}{$height}px\\${3}\", $svg);",
" return $svg;\n }",
" public function thumbnail($src, $width = 200, $height = null, $crop = null)\n {\n if ($src == false) {\n return $this->pixum($width, $height);\n }",
" if (is_array($src)) {\n extract($src);\n }",
" if (!is_string($src)) {\n return $this->pixum($width, $height);\n }",
"\n $src = html_entity_decode($src);\n $src = htmlspecialchars_decode($src);",
" $surl = $this->app->url_manager->site();\n $src = str_replace('{SITE_URL}', $surl, $src);\n $src = str_replace('%7BSITE_URL%7D', $surl, $src);\n $base_src = str_replace($surl, '', $src);",
" if (!isset($width)) {\n $width = 200;\n } else {\n $width = intval($width);\n }",
" $src = strtok($src, '?');\n if (!isset($height)) {\n $height = 0;\n } else {\n $height = intval($height);\n }",
" $cd = $this->_thumbnails_path() . $width . DS;\n $cd_relative = $this->thumbnails_path_in_userfiles . DS . $width . DS;",
" $ext = strtolower(get_file_extension($base_src));",
"\n $cache = ($base_src . $width . $height) . '.' . $ext;",
" $cache = str_replace(' ', '_', $cache);",
" $ext = strtolower(get_file_extension($src));",
"\n if ($this->_is_webp_supported()) {\n $ext = 'webp';\n }\n $is_remote = false;\n if (!stristr($src, $surl)) {\n if (strstr($src, 'http://')) {\n $is_remote = true;\n } elseif (strstr($src, 'https://')) {\n $is_remote = true;\n }\n }",
" $cache_id_data = array();\n $cache_id_data['mtime'] = '';\n if (!$is_remote and @is_file($base_src)) {\n $cache_id_data['mtime'] = filemtime($base_src);\n }\n $cache_id_data['base_src'] = $base_src;\n $cache_id_data['ext'] = $ext;",
"\n $src_for_db = $src;\n if (!$is_remote) {\n $src_for_db = str_replace(site_url(), '{SITE_URL}', $src);\n }",
" $cache_id_data['src'] = $src_for_db;",
" $cache_id_data['width'] = $width;\n $cache_id_data['height'] = $height;\n if ($crop) {\n $cache_id_data['crop'] = $crop;\n }\n $cache_id_without_ext = 'tn-' . $this->tn_cache_id($cache_id_data);\n $cache_id = $cache_id_without_ext . '.' . $ext;\n $cache_path = $cd . $cache_id;\n $cache_path_relative = $cd_relative . $cache_id;\n $cache_path = normalize_path($cache_path, false);\n $cache_path_relative = normalize_path($cache_path_relative, false);\n //dump($cache_path);\n if ($is_remote) {\n return $src;\n } elseif (@is_file($cache_path)) {\n $cache_path = $this->app->url_manager->link_to_file($cache_path);\n return $cache_path;\n } else {\n if (stristr($base_src, 'pixum_img')) {\n return $this->pixum($width, $height);\n }\n $file_exists_local = url2dir($src);\n if (!@is_file($file_exists_local)) {\n return $this->pixum($width, $height);\n }",
"\n// if (!defined('MW_NO_OUTPUT_CACHE')) {\n// define('MW_NO_OUTPUT_CACHE', true);\n// }",
" // $cache_id_data['cache_path'] = $cache_path;\n $cache_id_data['cache_path_relative'] = $cache_path_relative;\n// if (!get_option($cache_id_without_ext, 'media_tn_temp')) {\n// save_option($cache_id_without_ext, @json_encode($cache_id_data), 'media_tn_temp');\n// }",
"\n //$check = MediaThumbnail::where('filename', $cache_id_without_ext)->first();\n $check = app()->media_repository->getThumbnailCachedItem($cache_id_without_ext);",
"\n if (!$check) {\n $media_tn_temp = new MediaThumbnail();\n $media_tn_temp->filename = $cache_id_without_ext;\n //$media_tn_temp->filename = null;\n $media_tn_temp->image_options = $cache_id_data;\n $media_tn_temp->save();",
" return $this->app->url_manager->site('api/image-generate-tn-request/') . $media_tn_temp->id . '?saved';\n } elseif (isset($check['image_options']) and isset($check['image_options']['cache_path_relative'])) {\n $file_check = normalize_path(userfiles_path() . '' . $check['image_options']['cache_path_relative'], false);\n if (is_file($file_check)) {\n return userfiles_url() . $check['image_options']['cache_path_relative'];\n }",
" }",
" return $this->app->url_manager->site('api/image-generate-tn-request/') . $check['id'] . '?finded';\n }",
" }",
" public function thumbnail_img($params)\n {",
" if (php_can_use_func('ini_set')) {\n ini_set('memory_limit', '-1');\n }",
" // ini_set('memory_limit', '256M');",
" extract($params);",
" if (!isset($width)) {\n $width = 200;\n } else {\n $width = intval($width);\n }",
" if (!isset($height)) {\n $height = null;\n } else {\n $height = intval($height);\n }",
" if (!isset($crop)) {\n $crop = null;\n } else {\n $crop = trim($crop);\n }",
"\n if (!isset($src) or $src == false) {\n return $this->pixum($width, $height);\n }",
" $src = strtok($src, '?');",
" $surl = $this->app->url_manager->site();\n $local = false;",
" $media_url = media_base_url();\n $media_url = trim($media_url);\n $src = str_replace('{SITE_URL}', $surl, $src);\n $src = str_replace('%7BSITE_URL%7D', $surl, $src);\n $src = str_replace('..', '', $src);",
" if (strstr($src, $surl) or strpos($src, $surl)) {\n $src = str_replace($surl . '/', $surl, $src);\n //$src = str_replace($media_url, '', $src);\n $src = str_replace($surl, '', $src);\n $src = ltrim($src, DS);\n $src = ltrim($src, '/');\n $src = rtrim($src, DS);\n $src = rtrim($src, '/');\n //$src = media_base_path() . $src;\n $src = MW_ROOTPATH . $src;\n $src = normalize_path($src, false);\n } else {\n $src = $this->app->url_manager->clean_url_wrappers($src);",
" $src1 = media_base_path() . $src;\n $src1 = normalize_path($src1, false);",
" $src2 = MW_ROOTPATH . $src;\n $src2 = normalize_path($src2, false);\n $src3 = strtolower($src2);",
" if (is_file($src1)) {\n $src = $src1;\n } elseif (is_file($src2)) {\n $src = $src2;\n } elseif (is_file($src3)) {\n $src = $src3;\n } else {\n $no_img = true;",
" if ($no_img) {\n return $this->pixum_img();\n }\n }\n }\n $media_root = media_base_path();",
" $cd = $this->_thumbnails_path() . $width . DS;",
" if (!is_dir($cd)) {\n mkdir_recursive($cd);\n }",
" $index_file = $cd . 'index.html';\n if (!is_file($index_file)) {\n file_put_contents($index_file, 'Thumbnail directory is not allowed');\n }\n if (!isset($ext)) {\n $ext = strtolower(get_file_extension($src));\n }\n if ($ext == 'webp') {\n if (!$this->_is_webp_supported()) {\n $ext = strtolower(get_file_extension($src));",
" }\n }",
" // $cache = md5(serialize($params)) . '.' . $ext;\n $cache = $this->tn_cache_id($params) . '.' . $ext;",
" $cache = str_replace('..', '', $cache);",
" if (isset($cache_id)) {\n $cache = str_replace('..', '', $cache_id);",
" // $cache = url_title($cache_id);\n }\n// if(!isset($cache_path)){\n// $cache_path = $cd . $cache;\n// }\n $cache_path = $cd . $cache;\n if (isset($cache_path_relative)) {\n $cache_path = normalize_path(userfiles_path() . $cache_path_relative, false);\n }\n// if (!file_exists($cache_path)) {\n// if(!isset($cache_path)){\n// $cache_path = $cd . $cache;\n// }\n// }",
" if (file_exists($cache_path)) {",
" if (!isset($return_cache_path)) {",
" // if (!isset($return_cache_path) and isset($params['cache_id'])) {\n // delete_option($cache_id, 'media_tn_temp');\n // }",
"\n if (!headers_sent()) {\n if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {\n $if_modified_since = preg_replace('/;.*$/', '', $_SERVER['HTTP_IF_MODIFIED_SINCE']);\n } else {\n $if_modified_since = '';\n }\n $mtime = filemtime($src);\n $gmdate_mod = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';\n if ($if_modified_since == $gmdate_mod) {\n // header('HTTP/1.0 304 Not Modified');\n }\n }\n }",
" } else {\n $src = $this->app->url_manager->clean_url_wrappers($src);",
" if (file_exists($src)) {\n if (($ext) == 'svg') {\n $res1 = file_get_contents($src);\n $res1 = $this->svgScaleHack($res1, $width, $height);\n file_put_contents($cache_path, $res1);\n } else {\n if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'gif' || $ext == 'png' || $ext == 'bmp' || $ext == 'webp') {",
" if (!$height) {\n $height = $width;\n }\n $tn = new Thumbnailer($src);\n $thumbOptions = array('height' => $height, 'width' => $width);\n if ($crop) {\n $thumbOptions['crop'] = $crop;\n }",
" $cache_path_dir = dirname($cache_path);\n if (!is_dir($cache_path_dir)) {\n mkdir_recursive($cache_path_dir);\n }\n $tn->createThumb($thumbOptions, $cache_path);",
"// if (!isset($return_cache_path) and isset($params['cache_id'])) {\n// delete_option($params['cache_id'], 'media_tn_temp');\n// }",
"\n if (!defined('MW_NO_OUTPUT_CACHE')) {\n define('MW_NO_OUTPUT_CACHE', true);\n }",
"\n unset($tn);",
" } else {\n return $this->pixum_img();\n }\n }\n }\n }",
"\n if (isset($return_cache_path) and $return_cache_path) {\n return $cache_path;\n }",
" if (is_file($cache_path)) {\n $ext = get_file_extension($cache_path);\n if ($ext == 'jpg') {\n $ext = 'jpeg';\n }",
"// if (isset($return_cache_path)) {\n// delete_option($cache_id, 'media_tn_temp');\n// return $cache_path;\n// }",
" if ($ext == 'svg') {\n header('Content-Type: image/svg+xml');\n } else {\n header('Content-Type: image/' . $ext);\n }",
" header('Content-Length: ' . filesize($cache_path));\n readfile($cache_path);\n exit;\n } else {\n return $this->pixum_img();\n }\n }",
"\n public function create_media_dir($params)\n {",
"\n $clean = new HTMLClean();\n $_REQUEST = $clean->cleanArray($_REQUEST);\n",
" must_have_access();\n $resp = array();\n // $target_path = media_base_path() . 'uploaded' . DS;\n $target_path = media_uploads_path();\n $fn_path = media_base_path();\n if (isset($_REQUEST['path']) and trim($_REQUEST['path']) != '') {\n $_REQUEST['path'] = urldecode($_REQUEST['path']);",
" $fn_path = $target_path . DS . $_REQUEST['path'] . DS;\n $fn_path = str_replace('..', '', $fn_path);\n $fn_path = normalize_path($fn_path, false);",
" $target_path = $fn_path;\n }",
" if (!isset($_REQUEST['name']) || empty($_REQUEST['name'])) {",
" $resp = array('error' => 'You must send new_folder parameter');\n } else {\n $fn_new_folder_path = $_REQUEST['name'];\n $fn_new_folder_path = urldecode($fn_new_folder_path);\n $fn_new_folder_path = str_replace('..', '', $fn_new_folder_path);\n $fn_new_folder_path_new = $target_path . DS . $fn_new_folder_path;\n $fn_path = normalize_path($fn_new_folder_path_new, false);\n if (!is_dir($fn_path)) {\n mkdir_recursive($fn_path);\n $resp = array('success' => 'Folder ' . $fn_path . ' is created');\n } else {\n $resp = array('error' => 'Folder ' . $fn_new_folder_path . ' already exists');\n }\n }",
" return $resp;\n }",
" public function delete_media_file($params)\n {\n must_have_access();",
" // $target_path = media_base_path() . 'uploaded' . DS;\n $target_path = media_uploads_path();\n $target_path = normalize_path($target_path, 0);\n $path_restirct = userfiles_path();",
" $fn_remove_path = $_REQUEST['path'];\n $resp = array();\n if ($fn_remove_path != false and is_array($fn_remove_path)) {\n foreach ($fn_remove_path as $key => $value) {\n $fn_remove = $this->app->url_manager->to_path($value);",
" if (isset($fn_remove) and trim($fn_remove) != '' and trim($fn_remove) != 'false') {\n $path = urldecode($fn_remove);\n $path = normalize_path($path, 0);\n $path = str_replace('..', '', $path);\n $path = str_replace($path_restirct, '', $path);\n $target_path = userfiles_path() . DS . $path;\n $target_path = normalize_path($target_path, false);",
" // if (stristr($target_path, media_base_path())) {\n if (stristr($target_path, media_uploads_path())) {\n if (is_dir($target_path)) {\n mw('MicroweberPackages\\Utils\\System\\Files')->rmdir($target_path, false);\n $resp = array('success' => 'Directory ' . $target_path . ' is deleted');\n } elseif (is_file($target_path)) {\n unlink($target_path);\n $resp = array('success' => 'File ' . basename($target_path) . ' is deleted');\n } else {\n $resp = array('error' => 'Not valid file or folder ' . $target_path . ' ');\n }\n } else {\n $resp = array('error' => 'Not allowed to delete on ' . $target_path . ' ');\n }\n }\n }\n }",
" return $resp;\n }",
" public function tn_cache_id($params)\n {",
" $tnhash = crc32(json_encode($params));\n if (isset($params['src'])) {\n $src = basename($params['src']);\n $src = no_ext($src);\n if ($src) {\n $src = str_slug($src);\n $tnhash = $src . '-' . $tnhash;\n }\n }",
" return $tnhash;\n }",
" public function relative_media_start_path()\n {",
"\n static $path;\n if ($path == false) {\n $environment = \\App::environment();",
" $path = MW_MEDIA_FOLDER_NAME . '/' . $environment . '';\n }",
" return $path;\n }",
"\n private function _is_webp_supported()\n {\n if (function_exists('imagewebp') and $_SERVER and isset($_SERVER['HTTP_ACCEPT']) and is_string($_SERVER['HTTP_ACCEPT']) and strpos($_SERVER['HTTP_ACCEPT'], 'image/webp') !== false) {\n return true;\n }\n }",
" private function _thumbnails_path()\n {\n $userfiles_dir = userfiles_path();\n // $userfiles_dir = media_base_path();\n $userfiles_cache_dir = normalize_path($userfiles_dir . $this->thumbnails_path_in_userfiles);",
" // media_base_path() . 'thumbnail' . DS;",
" return $userfiles_cache_dir;\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [1202], "buggy_code_start_loc": [6], "filenames": ["src/MicroweberPackages/Media/MediaManager.php"], "fixing_code_end_loc": [1207], "fixing_code_start_loc": [7], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository microweber/microweber prior to 1.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:microweber:microweber:*:*:*:*:*:*:*:*", "matchCriteriaId": "CEE7F7A1-F20B-4F8B-A3DE-989A059B7E0E", "versionEndExcluding": "1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Stored in GitHub repository microweber/microweber prior to 1.3."}, {"lang": "es", "value": "Una vulnerabilidad de tipo Cross-site Scripting (XSS) - Almacenado en el repositorio de GitHub microweber/microweber versiones anteriores a 1.3."}], "evaluatorComment": null, "id": "CVE-2022-0763", "lastModified": "2022-03-08T17:25:17.980", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.7, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-26T10:15:08.547", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/microweber/microweber/commit/c897d0dc159849763a813184d9b75b966c6360bf"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/6de9c621-740d-4d7a-9d77-d90c6c87f3b6"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/microweber/microweber/commit/c897d0dc159849763a813184d9b75b966c6360bf"}, "type": "CWE-79"}
| 251
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * mm/mmap.c\n *\n * Written by obz.\n *\n * Address space accounting code\t<alan@lxorguk.ukuu.org.uk>\n */",
"#define pr_fmt(fmt) KBUILD_MODNAME \": \" fmt",
"#include <linux/kernel.h>\n#include <linux/slab.h>\n#include <linux/backing-dev.h>\n#include <linux/mm.h>\n#include <linux/vmacache.h>\n#include <linux/shm.h>\n#include <linux/mman.h>\n#include <linux/pagemap.h>\n#include <linux/swap.h>\n#include <linux/syscalls.h>\n#include <linux/capability.h>\n#include <linux/init.h>\n#include <linux/file.h>\n#include <linux/fs.h>\n#include <linux/personality.h>\n#include <linux/security.h>\n#include <linux/hugetlb.h>\n#include <linux/shmem_fs.h>\n#include <linux/profile.h>\n#include <linux/export.h>\n#include <linux/mount.h>\n#include <linux/mempolicy.h>\n#include <linux/rmap.h>\n#include <linux/mmu_notifier.h>\n#include <linux/mmdebug.h>\n#include <linux/perf_event.h>\n#include <linux/audit.h>\n#include <linux/khugepaged.h>\n#include <linux/uprobes.h>\n#include <linux/rbtree_augmented.h>\n#include <linux/notifier.h>\n#include <linux/memory.h>\n#include <linux/printk.h>\n#include <linux/userfaultfd_k.h>\n#include <linux/moduleparam.h>\n#include <linux/pkeys.h>\n#include <linux/oom.h>",
"#include <linux/uaccess.h>\n#include <asm/cacheflush.h>\n#include <asm/tlb.h>\n#include <asm/mmu_context.h>",
"#include \"internal.h\"",
"#ifndef arch_mmap_check\n#define arch_mmap_check(addr, len, flags)\t(0)\n#endif",
"#ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS\nconst int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;\nconst int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;\nint mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;\n#endif\n#ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS\nconst int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;\nconst int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;\nint mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;\n#endif",
"static bool ignore_rlimit_data;\ncore_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);",
"static void unmap_region(struct mm_struct *mm,\n\t\tstruct vm_area_struct *vma, struct vm_area_struct *prev,\n\t\tunsigned long start, unsigned long end);",
"/* description of effects of mapping type and prot in current implementation.\n * this is due to the limited x86 page protection hardware. The expected\n * behavior is in parens:\n *\n * map_type\tprot\n *\t\tPROT_NONE\tPROT_READ\tPROT_WRITE\tPROT_EXEC\n * MAP_SHARED\tr: (no) no\tr: (yes) yes\tr: (no) yes\tr: (no) yes\n *\t\tw: (no) no\tw: (no) no\tw: (yes) yes\tw: (no) no\n *\t\tx: (no) no\tx: (no) yes\tx: (no) yes\tx: (yes) yes\n *\n * MAP_PRIVATE\tr: (no) no\tr: (yes) yes\tr: (no) yes\tr: (no) yes\n *\t\tw: (no) no\tw: (no) no\tw: (copy) copy\tw: (no) no\n *\t\tx: (no) no\tx: (no) yes\tx: (no) yes\tx: (yes) yes\n *\n * On arm64, PROT_EXEC has the following behaviour for both MAP_SHARED and\n * MAP_PRIVATE:\n *\t\t\t\t\t\t\t\tr: (no) no\n *\t\t\t\t\t\t\t\tw: (no) no\n *\t\t\t\t\t\t\t\tx: (yes) yes\n */\npgprot_t protection_map[16] __ro_after_init = {\n\t__P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,\n\t__S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111\n};",
"#ifndef CONFIG_ARCH_HAS_FILTER_PGPROT\nstatic inline pgprot_t arch_filter_pgprot(pgprot_t prot)\n{\n\treturn prot;\n}\n#endif",
"pgprot_t vm_get_page_prot(unsigned long vm_flags)\n{\n\tpgprot_t ret = __pgprot(pgprot_val(protection_map[vm_flags &\n\t\t\t\t(VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)]) |\n\t\t\tpgprot_val(arch_vm_get_page_prot(vm_flags)));",
"\treturn arch_filter_pgprot(ret);\n}\nEXPORT_SYMBOL(vm_get_page_prot);",
"static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)\n{\n\treturn pgprot_modify(oldprot, vm_get_page_prot(vm_flags));\n}",
"/* Update vma->vm_page_prot to reflect vma->vm_flags. */\nvoid vma_set_page_prot(struct vm_area_struct *vma)\n{\n\tunsigned long vm_flags = vma->vm_flags;\n\tpgprot_t vm_page_prot;",
"\tvm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);\n\tif (vma_wants_writenotify(vma, vm_page_prot)) {\n\t\tvm_flags &= ~VM_SHARED;\n\t\tvm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);\n\t}\n\t/* remove_protection_ptes reads vma->vm_page_prot without mmap_sem */\n\tWRITE_ONCE(vma->vm_page_prot, vm_page_prot);\n}",
"/*\n * Requires inode->i_mapping->i_mmap_rwsem\n */\nstatic void __remove_shared_vm_struct(struct vm_area_struct *vma,\n\t\tstruct file *file, struct address_space *mapping)\n{\n\tif (vma->vm_flags & VM_DENYWRITE)\n\t\tatomic_inc(&file_inode(file)->i_writecount);\n\tif (vma->vm_flags & VM_SHARED)\n\t\tmapping_unmap_writable(mapping);",
"\tflush_dcache_mmap_lock(mapping);\n\tvma_interval_tree_remove(vma, &mapping->i_mmap);\n\tflush_dcache_mmap_unlock(mapping);\n}",
"/*\n * Unlink a file-based vm structure from its interval tree, to hide\n * vma from rmap and vmtruncate before freeing its page tables.\n */\nvoid unlink_file_vma(struct vm_area_struct *vma)\n{\n\tstruct file *file = vma->vm_file;",
"\tif (file) {\n\t\tstruct address_space *mapping = file->f_mapping;\n\t\ti_mmap_lock_write(mapping);\n\t\t__remove_shared_vm_struct(vma, file, mapping);\n\t\ti_mmap_unlock_write(mapping);\n\t}\n}",
"/*\n * Close a vm structure and free it, returning the next.\n */\nstatic struct vm_area_struct *remove_vma(struct vm_area_struct *vma)\n{\n\tstruct vm_area_struct *next = vma->vm_next;",
"\tmight_sleep();\n\tif (vma->vm_ops && vma->vm_ops->close)\n\t\tvma->vm_ops->close(vma);\n\tif (vma->vm_file)\n\t\tfput(vma->vm_file);\n\tmpol_put(vma_policy(vma));\n\tvm_area_free(vma);\n\treturn next;\n}",
"static int do_brk_flags(unsigned long addr, unsigned long request, unsigned long flags,\n\t\tstruct list_head *uf);\nSYSCALL_DEFINE1(brk, unsigned long, brk)\n{\n\tunsigned long retval;\n\tunsigned long newbrk, oldbrk, origbrk;\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *next;\n\tunsigned long min_brk;\n\tbool populate;\n\tbool downgraded = false;\n\tLIST_HEAD(uf);",
"\tif (down_write_killable(&mm->mmap_sem))\n\t\treturn -EINTR;",
"\torigbrk = mm->brk;",
"#ifdef CONFIG_COMPAT_BRK\n\t/*\n\t * CONFIG_COMPAT_BRK can still be overridden by setting\n\t * randomize_va_space to 2, which will still cause mm->start_brk\n\t * to be arbitrarily shifted\n\t */\n\tif (current->brk_randomized)\n\t\tmin_brk = mm->start_brk;\n\telse\n\t\tmin_brk = mm->end_data;\n#else\n\tmin_brk = mm->start_brk;\n#endif\n\tif (brk < min_brk)\n\t\tgoto out;",
"\t/*\n\t * Check against rlimit here. If this check is done later after the test\n\t * of oldbrk with newbrk then it can escape the test and let the data\n\t * segment grow beyond its set limit the in case where the limit is\n\t * not page aligned -Ram Gupta\n\t */\n\tif (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,\n\t\t\t mm->end_data, mm->start_data))\n\t\tgoto out;",
"\tnewbrk = PAGE_ALIGN(brk);\n\toldbrk = PAGE_ALIGN(mm->brk);\n\tif (oldbrk == newbrk) {\n\t\tmm->brk = brk;\n\t\tgoto success;\n\t}",
"\t/*\n\t * Always allow shrinking brk.\n\t * __do_munmap() may downgrade mmap_sem to read.\n\t */\n\tif (brk <= mm->brk) {\n\t\tint ret;",
"\t\t/*\n\t\t * mm->brk must to be protected by write mmap_sem so update it\n\t\t * before downgrading mmap_sem. When __do_munmap() fails,\n\t\t * mm->brk will be restored from origbrk.\n\t\t */\n\t\tmm->brk = brk;\n\t\tret = __do_munmap(mm, newbrk, oldbrk-newbrk, &uf, true);\n\t\tif (ret < 0) {\n\t\t\tmm->brk = origbrk;\n\t\t\tgoto out;\n\t\t} else if (ret == 1) {\n\t\t\tdowngraded = true;\n\t\t}\n\t\tgoto success;\n\t}",
"\t/* Check against existing mmap mappings. */\n\tnext = find_vma(mm, oldbrk);\n\tif (next && newbrk + PAGE_SIZE > vm_start_gap(next))\n\t\tgoto out;",
"\t/* Ok, looks good - let it rip. */\n\tif (do_brk_flags(oldbrk, newbrk-oldbrk, 0, &uf) < 0)\n\t\tgoto out;\n\tmm->brk = brk;",
"success:\n\tpopulate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;\n\tif (downgraded)\n\t\tup_read(&mm->mmap_sem);\n\telse\n\t\tup_write(&mm->mmap_sem);\n\tuserfaultfd_unmap_complete(mm, &uf);\n\tif (populate)\n\t\tmm_populate(oldbrk, newbrk - oldbrk);\n\treturn brk;",
"out:\n\tretval = origbrk;\n\tup_write(&mm->mmap_sem);\n\treturn retval;\n}",
"static long vma_compute_subtree_gap(struct vm_area_struct *vma)\n{\n\tunsigned long max, prev_end, subtree_gap;",
"\t/*\n\t * Note: in the rare case of a VM_GROWSDOWN above a VM_GROWSUP, we\n\t * allow two stack_guard_gaps between them here, and when choosing\n\t * an unmapped area; whereas when expanding we only require one.\n\t * That's a little inconsistent, but keeps the code here simpler.\n\t */\n\tmax = vm_start_gap(vma);\n\tif (vma->vm_prev) {\n\t\tprev_end = vm_end_gap(vma->vm_prev);\n\t\tif (max > prev_end)\n\t\t\tmax -= prev_end;\n\t\telse\n\t\t\tmax = 0;\n\t}\n\tif (vma->vm_rb.rb_left) {\n\t\tsubtree_gap = rb_entry(vma->vm_rb.rb_left,\n\t\t\t\tstruct vm_area_struct, vm_rb)->rb_subtree_gap;\n\t\tif (subtree_gap > max)\n\t\t\tmax = subtree_gap;\n\t}\n\tif (vma->vm_rb.rb_right) {\n\t\tsubtree_gap = rb_entry(vma->vm_rb.rb_right,\n\t\t\t\tstruct vm_area_struct, vm_rb)->rb_subtree_gap;\n\t\tif (subtree_gap > max)\n\t\t\tmax = subtree_gap;\n\t}\n\treturn max;\n}",
"#ifdef CONFIG_DEBUG_VM_RB\nstatic int browse_rb(struct mm_struct *mm)\n{\n\tstruct rb_root *root = &mm->mm_rb;\n\tint i = 0, j, bug = 0;\n\tstruct rb_node *nd, *pn = NULL;\n\tunsigned long prev = 0, pend = 0;",
"\tfor (nd = rb_first(root); nd; nd = rb_next(nd)) {\n\t\tstruct vm_area_struct *vma;\n\t\tvma = rb_entry(nd, struct vm_area_struct, vm_rb);\n\t\tif (vma->vm_start < prev) {\n\t\t\tpr_emerg(\"vm_start %lx < prev %lx\\n\",\n\t\t\t\t vma->vm_start, prev);\n\t\t\tbug = 1;\n\t\t}\n\t\tif (vma->vm_start < pend) {\n\t\t\tpr_emerg(\"vm_start %lx < pend %lx\\n\",\n\t\t\t\t vma->vm_start, pend);\n\t\t\tbug = 1;\n\t\t}\n\t\tif (vma->vm_start > vma->vm_end) {\n\t\t\tpr_emerg(\"vm_start %lx > vm_end %lx\\n\",\n\t\t\t\t vma->vm_start, vma->vm_end);\n\t\t\tbug = 1;\n\t\t}\n\t\tspin_lock(&mm->page_table_lock);\n\t\tif (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {\n\t\t\tpr_emerg(\"free gap %lx, correct %lx\\n\",\n\t\t\t vma->rb_subtree_gap,\n\t\t\t vma_compute_subtree_gap(vma));\n\t\t\tbug = 1;\n\t\t}\n\t\tspin_unlock(&mm->page_table_lock);\n\t\ti++;\n\t\tpn = nd;\n\t\tprev = vma->vm_start;\n\t\tpend = vma->vm_end;\n\t}\n\tj = 0;\n\tfor (nd = pn; nd; nd = rb_prev(nd))\n\t\tj++;\n\tif (i != j) {\n\t\tpr_emerg(\"backwards %d, forwards %d\\n\", j, i);\n\t\tbug = 1;\n\t}\n\treturn bug ? -1 : i;\n}",
"static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)\n{\n\tstruct rb_node *nd;",
"\tfor (nd = rb_first(root); nd; nd = rb_next(nd)) {\n\t\tstruct vm_area_struct *vma;\n\t\tvma = rb_entry(nd, struct vm_area_struct, vm_rb);\n\t\tVM_BUG_ON_VMA(vma != ignore &&\n\t\t\tvma->rb_subtree_gap != vma_compute_subtree_gap(vma),\n\t\t\tvma);\n\t}\n}",
"static void validate_mm(struct mm_struct *mm)\n{\n\tint bug = 0;\n\tint i = 0;\n\tunsigned long highest_address = 0;\n\tstruct vm_area_struct *vma = mm->mmap;",
"\twhile (vma) {\n\t\tstruct anon_vma *anon_vma = vma->anon_vma;\n\t\tstruct anon_vma_chain *avc;",
"\t\tif (anon_vma) {\n\t\t\tanon_vma_lock_read(anon_vma);\n\t\t\tlist_for_each_entry(avc, &vma->anon_vma_chain, same_vma)\n\t\t\t\tanon_vma_interval_tree_verify(avc);\n\t\t\tanon_vma_unlock_read(anon_vma);\n\t\t}",
"\t\thighest_address = vm_end_gap(vma);\n\t\tvma = vma->vm_next;\n\t\ti++;\n\t}\n\tif (i != mm->map_count) {\n\t\tpr_emerg(\"map_count %d vm_next %d\\n\", mm->map_count, i);\n\t\tbug = 1;\n\t}\n\tif (highest_address != mm->highest_vm_end) {\n\t\tpr_emerg(\"mm->highest_vm_end %lx, found %lx\\n\",\n\t\t\t mm->highest_vm_end, highest_address);\n\t\tbug = 1;\n\t}\n\ti = browse_rb(mm);\n\tif (i != mm->map_count) {\n\t\tif (i != -1)\n\t\t\tpr_emerg(\"map_count %d rb %d\\n\", mm->map_count, i);\n\t\tbug = 1;\n\t}\n\tVM_BUG_ON_MM(bug, mm);\n}\n#else\n#define validate_mm_rb(root, ignore) do { } while (0)\n#define validate_mm(mm) do { } while (0)\n#endif",
"RB_DECLARE_CALLBACKS(static, vma_gap_callbacks, struct vm_area_struct, vm_rb,\n\t\t unsigned long, rb_subtree_gap, vma_compute_subtree_gap)",
"/*\n * Update augmented rbtree rb_subtree_gap values after vma->vm_start or\n * vma->vm_prev->vm_end values changed, without modifying the vma's position\n * in the rbtree.\n */\nstatic void vma_gap_update(struct vm_area_struct *vma)\n{\n\t/*\n\t * As it turns out, RB_DECLARE_CALLBACKS() already created a callback\n\t * function that does exacltly what we want.\n\t */\n\tvma_gap_callbacks_propagate(&vma->vm_rb, NULL);\n}",
"static inline void vma_rb_insert(struct vm_area_struct *vma,\n\t\t\t\t struct rb_root *root)\n{\n\t/* All rb_subtree_gap values must be consistent prior to insertion */\n\tvalidate_mm_rb(root, NULL);",
"\trb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);\n}",
"static void __vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)\n{\n\t/*\n\t * Note rb_erase_augmented is a fairly large inline function,\n\t * so make sure we instantiate it only once with our desired\n\t * augmented rbtree callbacks.\n\t */\n\trb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);\n}",
"static __always_inline void vma_rb_erase_ignore(struct vm_area_struct *vma,\n\t\t\t\t\t\tstruct rb_root *root,\n\t\t\t\t\t\tstruct vm_area_struct *ignore)\n{\n\t/*\n\t * All rb_subtree_gap values must be consistent prior to erase,\n\t * with the possible exception of the \"next\" vma being erased if\n\t * next->vm_start was reduced.\n\t */\n\tvalidate_mm_rb(root, ignore);",
"\t__vma_rb_erase(vma, root);\n}",
"static __always_inline void vma_rb_erase(struct vm_area_struct *vma,\n\t\t\t\t\t struct rb_root *root)\n{\n\t/*\n\t * All rb_subtree_gap values must be consistent prior to erase,\n\t * with the possible exception of the vma being erased.\n\t */\n\tvalidate_mm_rb(root, vma);",
"\t__vma_rb_erase(vma, root);\n}",
"/*\n * vma has some anon_vma assigned, and is already inserted on that\n * anon_vma's interval trees.\n *\n * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the\n * vma must be removed from the anon_vma's interval trees using\n * anon_vma_interval_tree_pre_update_vma().\n *\n * After the update, the vma will be reinserted using\n * anon_vma_interval_tree_post_update_vma().\n *\n * The entire update must be protected by exclusive mmap_sem and by\n * the root anon_vma's mutex.\n */\nstatic inline void\nanon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)\n{\n\tstruct anon_vma_chain *avc;",
"\tlist_for_each_entry(avc, &vma->anon_vma_chain, same_vma)\n\t\tanon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);\n}",
"static inline void\nanon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)\n{\n\tstruct anon_vma_chain *avc;",
"\tlist_for_each_entry(avc, &vma->anon_vma_chain, same_vma)\n\t\tanon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);\n}",
"static int find_vma_links(struct mm_struct *mm, unsigned long addr,\n\t\tunsigned long end, struct vm_area_struct **pprev,\n\t\tstruct rb_node ***rb_link, struct rb_node **rb_parent)\n{\n\tstruct rb_node **__rb_link, *__rb_parent, *rb_prev;",
"\t__rb_link = &mm->mm_rb.rb_node;\n\trb_prev = __rb_parent = NULL;",
"\twhile (*__rb_link) {\n\t\tstruct vm_area_struct *vma_tmp;",
"\t\t__rb_parent = *__rb_link;\n\t\tvma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);",
"\t\tif (vma_tmp->vm_end > addr) {\n\t\t\t/* Fail if an existing vma overlaps the area */\n\t\t\tif (vma_tmp->vm_start < end)\n\t\t\t\treturn -ENOMEM;\n\t\t\t__rb_link = &__rb_parent->rb_left;\n\t\t} else {\n\t\t\trb_prev = __rb_parent;\n\t\t\t__rb_link = &__rb_parent->rb_right;\n\t\t}\n\t}",
"\t*pprev = NULL;\n\tif (rb_prev)\n\t\t*pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);\n\t*rb_link = __rb_link;\n\t*rb_parent = __rb_parent;\n\treturn 0;\n}",
"static unsigned long count_vma_pages_range(struct mm_struct *mm,\n\t\tunsigned long addr, unsigned long end)\n{\n\tunsigned long nr_pages = 0;\n\tstruct vm_area_struct *vma;",
"\t/* Find first overlaping mapping */\n\tvma = find_vma_intersection(mm, addr, end);\n\tif (!vma)\n\t\treturn 0;",
"\tnr_pages = (min(end, vma->vm_end) -\n\t\tmax(addr, vma->vm_start)) >> PAGE_SHIFT;",
"\t/* Iterate over the rest of the overlaps */\n\tfor (vma = vma->vm_next; vma; vma = vma->vm_next) {\n\t\tunsigned long overlap_len;",
"\t\tif (vma->vm_start > end)\n\t\t\tbreak;",
"\t\toverlap_len = min(end, vma->vm_end) - vma->vm_start;\n\t\tnr_pages += overlap_len >> PAGE_SHIFT;\n\t}",
"\treturn nr_pages;\n}",
"void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,\n\t\tstruct rb_node **rb_link, struct rb_node *rb_parent)\n{\n\t/* Update tracking information for the gap following the new vma. */\n\tif (vma->vm_next)\n\t\tvma_gap_update(vma->vm_next);\n\telse\n\t\tmm->highest_vm_end = vm_end_gap(vma);",
"\t/*\n\t * vma->vm_prev wasn't known when we followed the rbtree to find the\n\t * correct insertion point for that vma. As a result, we could not\n\t * update the vma vm_rb parents rb_subtree_gap values on the way down.\n\t * So, we first insert the vma with a zero rb_subtree_gap value\n\t * (to be consistent with what we did on the way down), and then\n\t * immediately update the gap to the correct value. Finally we\n\t * rebalance the rbtree after all augmented values have been set.\n\t */\n\trb_link_node(&vma->vm_rb, rb_parent, rb_link);\n\tvma->rb_subtree_gap = 0;\n\tvma_gap_update(vma);\n\tvma_rb_insert(vma, &mm->mm_rb);\n}",
"static void __vma_link_file(struct vm_area_struct *vma)\n{\n\tstruct file *file;",
"\tfile = vma->vm_file;\n\tif (file) {\n\t\tstruct address_space *mapping = file->f_mapping;",
"\t\tif (vma->vm_flags & VM_DENYWRITE)\n\t\t\tatomic_dec(&file_inode(file)->i_writecount);\n\t\tif (vma->vm_flags & VM_SHARED)\n\t\t\tatomic_inc(&mapping->i_mmap_writable);",
"\t\tflush_dcache_mmap_lock(mapping);\n\t\tvma_interval_tree_insert(vma, &mapping->i_mmap);\n\t\tflush_dcache_mmap_unlock(mapping);\n\t}\n}",
"static void\n__vma_link(struct mm_struct *mm, struct vm_area_struct *vma,\n\tstruct vm_area_struct *prev, struct rb_node **rb_link,\n\tstruct rb_node *rb_parent)\n{\n\t__vma_link_list(mm, vma, prev, rb_parent);\n\t__vma_link_rb(mm, vma, rb_link, rb_parent);\n}",
"static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,\n\t\t\tstruct vm_area_struct *prev, struct rb_node **rb_link,\n\t\t\tstruct rb_node *rb_parent)\n{\n\tstruct address_space *mapping = NULL;",
"\tif (vma->vm_file) {\n\t\tmapping = vma->vm_file->f_mapping;\n\t\ti_mmap_lock_write(mapping);\n\t}",
"\t__vma_link(mm, vma, prev, rb_link, rb_parent);\n\t__vma_link_file(vma);",
"\tif (mapping)\n\t\ti_mmap_unlock_write(mapping);",
"\tmm->map_count++;\n\tvalidate_mm(mm);\n}",
"/*\n * Helper for vma_adjust() in the split_vma insert case: insert a vma into the\n * mm's list and rbtree. It has already been inserted into the interval tree.\n */\nstatic void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)\n{\n\tstruct vm_area_struct *prev;\n\tstruct rb_node **rb_link, *rb_parent;",
"\tif (find_vma_links(mm, vma->vm_start, vma->vm_end,\n\t\t\t &prev, &rb_link, &rb_parent))\n\t\tBUG();\n\t__vma_link(mm, vma, prev, rb_link, rb_parent);\n\tmm->map_count++;\n}",
"static __always_inline void __vma_unlink_common(struct mm_struct *mm,\n\t\t\t\t\t\tstruct vm_area_struct *vma,\n\t\t\t\t\t\tstruct vm_area_struct *prev,\n\t\t\t\t\t\tbool has_prev,\n\t\t\t\t\t\tstruct vm_area_struct *ignore)\n{\n\tstruct vm_area_struct *next;",
"\tvma_rb_erase_ignore(vma, &mm->mm_rb, ignore);\n\tnext = vma->vm_next;\n\tif (has_prev)\n\t\tprev->vm_next = next;\n\telse {\n\t\tprev = vma->vm_prev;\n\t\tif (prev)\n\t\t\tprev->vm_next = next;\n\t\telse\n\t\t\tmm->mmap = next;\n\t}\n\tif (next)\n\t\tnext->vm_prev = prev;",
"\t/* Kill the cache */\n\tvmacache_invalidate(mm);\n}",
"static inline void __vma_unlink_prev(struct mm_struct *mm,\n\t\t\t\t struct vm_area_struct *vma,\n\t\t\t\t struct vm_area_struct *prev)\n{\n\t__vma_unlink_common(mm, vma, prev, true, vma);\n}",
"/*\n * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that\n * is already present in an i_mmap tree without adjusting the tree.\n * The following helper function should be used when such adjustments\n * are necessary. The \"insert\" vma (if any) is to be inserted\n * before we drop the necessary locks.\n */\nint __vma_adjust(struct vm_area_struct *vma, unsigned long start,\n\tunsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,\n\tstruct vm_area_struct *expand)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tstruct vm_area_struct *next = vma->vm_next, *orig_vma = vma;\n\tstruct address_space *mapping = NULL;\n\tstruct rb_root_cached *root = NULL;\n\tstruct anon_vma *anon_vma = NULL;\n\tstruct file *file = vma->vm_file;\n\tbool start_changed = false, end_changed = false;\n\tlong adjust_next = 0;\n\tint remove_next = 0;",
"\tif (next && !insert) {\n\t\tstruct vm_area_struct *exporter = NULL, *importer = NULL;",
"\t\tif (end >= next->vm_end) {\n\t\t\t/*\n\t\t\t * vma expands, overlapping all the next, and\n\t\t\t * perhaps the one after too (mprotect case 6).\n\t\t\t * The only other cases that gets here are\n\t\t\t * case 1, case 7 and case 8.\n\t\t\t */\n\t\t\tif (next == expand) {\n\t\t\t\t/*\n\t\t\t\t * The only case where we don't expand \"vma\"\n\t\t\t\t * and we expand \"next\" instead is case 8.\n\t\t\t\t */\n\t\t\t\tVM_WARN_ON(end != next->vm_end);\n\t\t\t\t/*\n\t\t\t\t * remove_next == 3 means we're\n\t\t\t\t * removing \"vma\" and that to do so we\n\t\t\t\t * swapped \"vma\" and \"next\".\n\t\t\t\t */\n\t\t\t\tremove_next = 3;\n\t\t\t\tVM_WARN_ON(file != next->vm_file);\n\t\t\t\tswap(vma, next);\n\t\t\t} else {\n\t\t\t\tVM_WARN_ON(expand != vma);\n\t\t\t\t/*\n\t\t\t\t * case 1, 6, 7, remove_next == 2 is case 6,\n\t\t\t\t * remove_next == 1 is case 1 or 7.\n\t\t\t\t */\n\t\t\t\tremove_next = 1 + (end > next->vm_end);\n\t\t\t\tVM_WARN_ON(remove_next == 2 &&\n\t\t\t\t\t end != next->vm_next->vm_end);\n\t\t\t\tVM_WARN_ON(remove_next == 1 &&\n\t\t\t\t\t end != next->vm_end);\n\t\t\t\t/* trim end to next, for case 6 first pass */\n\t\t\t\tend = next->vm_end;\n\t\t\t}",
"\t\t\texporter = next;\n\t\t\timporter = vma;",
"\t\t\t/*\n\t\t\t * If next doesn't have anon_vma, import from vma after\n\t\t\t * next, if the vma overlaps with it.\n\t\t\t */\n\t\t\tif (remove_next == 2 && !next->anon_vma)\n\t\t\t\texporter = next->vm_next;",
"\t\t} else if (end > next->vm_start) {\n\t\t\t/*\n\t\t\t * vma expands, overlapping part of the next:\n\t\t\t * mprotect case 5 shifting the boundary up.\n\t\t\t */\n\t\t\tadjust_next = (end - next->vm_start) >> PAGE_SHIFT;\n\t\t\texporter = next;\n\t\t\timporter = vma;\n\t\t\tVM_WARN_ON(expand != importer);\n\t\t} else if (end < vma->vm_end) {\n\t\t\t/*\n\t\t\t * vma shrinks, and !insert tells it's not\n\t\t\t * split_vma inserting another: so it must be\n\t\t\t * mprotect case 4 shifting the boundary down.\n\t\t\t */\n\t\t\tadjust_next = -((vma->vm_end - end) >> PAGE_SHIFT);\n\t\t\texporter = vma;\n\t\t\timporter = next;\n\t\t\tVM_WARN_ON(expand != importer);\n\t\t}",
"\t\t/*\n\t\t * Easily overlooked: when mprotect shifts the boundary,\n\t\t * make sure the expanding vma has anon_vma set if the\n\t\t * shrinking vma had, to cover any anon pages imported.\n\t\t */\n\t\tif (exporter && exporter->anon_vma && !importer->anon_vma) {\n\t\t\tint error;",
"\t\t\timporter->anon_vma = exporter->anon_vma;\n\t\t\terror = anon_vma_clone(importer, exporter);\n\t\t\tif (error)\n\t\t\t\treturn error;\n\t\t}\n\t}\nagain:\n\tvma_adjust_trans_huge(orig_vma, start, end, adjust_next);",
"\tif (file) {\n\t\tmapping = file->f_mapping;\n\t\troot = &mapping->i_mmap;\n\t\tuprobe_munmap(vma, vma->vm_start, vma->vm_end);",
"\t\tif (adjust_next)\n\t\t\tuprobe_munmap(next, next->vm_start, next->vm_end);",
"\t\ti_mmap_lock_write(mapping);\n\t\tif (insert) {\n\t\t\t/*\n\t\t\t * Put into interval tree now, so instantiated pages\n\t\t\t * are visible to arm/parisc __flush_dcache_page\n\t\t\t * throughout; but we cannot insert into address\n\t\t\t * space until vma start or end is updated.\n\t\t\t */\n\t\t\t__vma_link_file(insert);\n\t\t}\n\t}",
"\tanon_vma = vma->anon_vma;\n\tif (!anon_vma && adjust_next)\n\t\tanon_vma = next->anon_vma;\n\tif (anon_vma) {\n\t\tVM_WARN_ON(adjust_next && next->anon_vma &&\n\t\t\t anon_vma != next->anon_vma);\n\t\tanon_vma_lock_write(anon_vma);\n\t\tanon_vma_interval_tree_pre_update_vma(vma);\n\t\tif (adjust_next)\n\t\t\tanon_vma_interval_tree_pre_update_vma(next);\n\t}",
"\tif (root) {\n\t\tflush_dcache_mmap_lock(mapping);\n\t\tvma_interval_tree_remove(vma, root);\n\t\tif (adjust_next)\n\t\t\tvma_interval_tree_remove(next, root);\n\t}",
"\tif (start != vma->vm_start) {\n\t\tvma->vm_start = start;\n\t\tstart_changed = true;\n\t}\n\tif (end != vma->vm_end) {\n\t\tvma->vm_end = end;\n\t\tend_changed = true;\n\t}\n\tvma->vm_pgoff = pgoff;\n\tif (adjust_next) {\n\t\tnext->vm_start += adjust_next << PAGE_SHIFT;\n\t\tnext->vm_pgoff += adjust_next;\n\t}",
"\tif (root) {\n\t\tif (adjust_next)\n\t\t\tvma_interval_tree_insert(next, root);\n\t\tvma_interval_tree_insert(vma, root);\n\t\tflush_dcache_mmap_unlock(mapping);\n\t}",
"\tif (remove_next) {\n\t\t/*\n\t\t * vma_merge has merged next into vma, and needs\n\t\t * us to remove next before dropping the locks.\n\t\t */\n\t\tif (remove_next != 3)\n\t\t\t__vma_unlink_prev(mm, next, vma);\n\t\telse\n\t\t\t/*\n\t\t\t * vma is not before next if they've been\n\t\t\t * swapped.\n\t\t\t *\n\t\t\t * pre-swap() next->vm_start was reduced so\n\t\t\t * tell validate_mm_rb to ignore pre-swap()\n\t\t\t * \"next\" (which is stored in post-swap()\n\t\t\t * \"vma\").\n\t\t\t */\n\t\t\t__vma_unlink_common(mm, next, NULL, false, vma);\n\t\tif (file)\n\t\t\t__remove_shared_vm_struct(next, file, mapping);\n\t} else if (insert) {\n\t\t/*\n\t\t * split_vma has split insert from vma, and needs\n\t\t * us to insert it before dropping the locks\n\t\t * (it may either follow vma or precede it).\n\t\t */\n\t\t__insert_vm_struct(mm, insert);\n\t} else {\n\t\tif (start_changed)\n\t\t\tvma_gap_update(vma);\n\t\tif (end_changed) {\n\t\t\tif (!next)\n\t\t\t\tmm->highest_vm_end = vm_end_gap(vma);\n\t\t\telse if (!adjust_next)\n\t\t\t\tvma_gap_update(next);\n\t\t}\n\t}",
"\tif (anon_vma) {\n\t\tanon_vma_interval_tree_post_update_vma(vma);\n\t\tif (adjust_next)\n\t\t\tanon_vma_interval_tree_post_update_vma(next);\n\t\tanon_vma_unlock_write(anon_vma);\n\t}\n\tif (mapping)\n\t\ti_mmap_unlock_write(mapping);",
"\tif (root) {\n\t\tuprobe_mmap(vma);",
"\t\tif (adjust_next)\n\t\t\tuprobe_mmap(next);\n\t}",
"\tif (remove_next) {\n\t\tif (file) {\n\t\t\tuprobe_munmap(next, next->vm_start, next->vm_end);\n\t\t\tfput(file);\n\t\t}\n\t\tif (next->anon_vma)\n\t\t\tanon_vma_merge(vma, next);\n\t\tmm->map_count--;\n\t\tmpol_put(vma_policy(next));\n\t\tvm_area_free(next);\n\t\t/*\n\t\t * In mprotect's case 6 (see comments on vma_merge),\n\t\t * we must remove another next too. It would clutter\n\t\t * up the code too much to do both in one go.\n\t\t */\n\t\tif (remove_next != 3) {\n\t\t\t/*\n\t\t\t * If \"next\" was removed and vma->vm_end was\n\t\t\t * expanded (up) over it, in turn\n\t\t\t * \"next->vm_prev->vm_end\" changed and the\n\t\t\t * \"vma->vm_next\" gap must be updated.\n\t\t\t */\n\t\t\tnext = vma->vm_next;\n\t\t} else {\n\t\t\t/*\n\t\t\t * For the scope of the comment \"next\" and\n\t\t\t * \"vma\" considered pre-swap(): if \"vma\" was\n\t\t\t * removed, next->vm_start was expanded (down)\n\t\t\t * over it and the \"next\" gap must be updated.\n\t\t\t * Because of the swap() the post-swap() \"vma\"\n\t\t\t * actually points to pre-swap() \"next\"\n\t\t\t * (post-swap() \"next\" as opposed is now a\n\t\t\t * dangling pointer).\n\t\t\t */\n\t\t\tnext = vma;\n\t\t}\n\t\tif (remove_next == 2) {\n\t\t\tremove_next = 1;\n\t\t\tend = next->vm_end;\n\t\t\tgoto again;\n\t\t}\n\t\telse if (next)\n\t\t\tvma_gap_update(next);\n\t\telse {\n\t\t\t/*\n\t\t\t * If remove_next == 2 we obviously can't\n\t\t\t * reach this path.\n\t\t\t *\n\t\t\t * If remove_next == 3 we can't reach this\n\t\t\t * path because pre-swap() next is always not\n\t\t\t * NULL. pre-swap() \"next\" is not being\n\t\t\t * removed and its next->vm_end is not altered\n\t\t\t * (and furthermore \"end\" already matches\n\t\t\t * next->vm_end in remove_next == 3).\n\t\t\t *\n\t\t\t * We reach this only in the remove_next == 1\n\t\t\t * case if the \"next\" vma that was removed was\n\t\t\t * the highest vma of the mm. However in such\n\t\t\t * case next->vm_end == \"end\" and the extended\n\t\t\t * \"vma\" has vma->vm_end == next->vm_end so\n\t\t\t * mm->highest_vm_end doesn't need any update\n\t\t\t * in remove_next == 1 case.\n\t\t\t */\n\t\t\tVM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));\n\t\t}\n\t}\n\tif (insert && file)\n\t\tuprobe_mmap(insert);",
"\tvalidate_mm(mm);",
"\treturn 0;\n}",
"/*\n * If the vma has a ->close operation then the driver probably needs to release\n * per-vma resources, so we don't attempt to merge those.\n */\nstatic inline int is_mergeable_vma(struct vm_area_struct *vma,\n\t\t\t\tstruct file *file, unsigned long vm_flags,\n\t\t\t\tstruct vm_userfaultfd_ctx vm_userfaultfd_ctx)\n{\n\t/*\n\t * VM_SOFTDIRTY should not prevent from VMA merging, if we\n\t * match the flags but dirty bit -- the caller should mark\n\t * merged VMA as dirty. If dirty bit won't be excluded from\n\t * comparison, we increase pressue on the memory system forcing\n\t * the kernel to generate new VMAs when old one could be\n\t * extended instead.\n\t */\n\tif ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)\n\t\treturn 0;\n\tif (vma->vm_file != file)\n\t\treturn 0;\n\tif (vma->vm_ops && vma->vm_ops->close)\n\t\treturn 0;\n\tif (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))\n\t\treturn 0;\n\treturn 1;\n}",
"static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,\n\t\t\t\t\tstruct anon_vma *anon_vma2,\n\t\t\t\t\tstruct vm_area_struct *vma)\n{\n\t/*\n\t * The list_is_singular() test is to avoid merging VMA cloned from\n\t * parents. This can improve scalability caused by anon_vma lock.\n\t */\n\tif ((!anon_vma1 || !anon_vma2) && (!vma ||\n\t\tlist_is_singular(&vma->anon_vma_chain)))\n\t\treturn 1;\n\treturn anon_vma1 == anon_vma2;\n}",
"/*\n * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)\n * in front of (at a lower virtual address and file offset than) the vma.\n *\n * We cannot merge two vmas if they have differently assigned (non-NULL)\n * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.\n *\n * We don't check here for the merged mmap wrapping around the end of pagecache\n * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which\n * wrap, nor mmaps which cover the final page at index -1UL.\n */\nstatic int\ncan_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,\n\t\t struct anon_vma *anon_vma, struct file *file,\n\t\t pgoff_t vm_pgoff,\n\t\t struct vm_userfaultfd_ctx vm_userfaultfd_ctx)\n{\n\tif (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&\n\t is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {\n\t\tif (vma->vm_pgoff == vm_pgoff)\n\t\t\treturn 1;\n\t}\n\treturn 0;\n}",
"/*\n * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)\n * beyond (at a higher virtual address and file offset than) the vma.\n *\n * We cannot merge two vmas if they have differently assigned (non-NULL)\n * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.\n */\nstatic int\ncan_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,\n\t\t struct anon_vma *anon_vma, struct file *file,\n\t\t pgoff_t vm_pgoff,\n\t\t struct vm_userfaultfd_ctx vm_userfaultfd_ctx)\n{\n\tif (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&\n\t is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {\n\t\tpgoff_t vm_pglen;\n\t\tvm_pglen = vma_pages(vma);\n\t\tif (vma->vm_pgoff + vm_pglen == vm_pgoff)\n\t\t\treturn 1;\n\t}\n\treturn 0;\n}",
"/*\n * Given a mapping request (addr,end,vm_flags,file,pgoff), figure out\n * whether that can be merged with its predecessor or its successor.\n * Or both (it neatly fills a hole).\n *\n * In most cases - when called for mmap, brk or mremap - [addr,end) is\n * certain not to be mapped by the time vma_merge is called; but when\n * called for mprotect, it is certain to be already mapped (either at\n * an offset within prev, or at the start of next), and the flags of\n * this area are about to be changed to vm_flags - and the no-change\n * case has already been eliminated.\n *\n * The following mprotect cases have to be considered, where AAAA is\n * the area passed down from mprotect_fixup, never extending beyond one\n * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:\n *\n * AAAA AAAA AAAA AAAA\n * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN PPPPNNNNXXXX\n * cannot merge might become might become might become\n * PPNNNNNNNNNN PPPPPPPPPPNN PPPPPPPPPPPP 6 or\n * mmap, brk or case 4 below case 5 below PPPPPPPPXXXX 7 or\n * mremap move: PPPPXXXXXXXX 8\n * AAAA\n * PPPP NNNN PPPPPPPPPPPP PPPPPPPPNNNN PPPPNNNNNNNN\n * might become case 1 below case 2 below case 3 below\n *\n * It is important for case 8 that the the vma NNNN overlapping the\n * region AAAA is never going to extended over XXXX. Instead XXXX must\n * be extended in region AAAA and NNNN must be removed. This way in\n * all cases where vma_merge succeeds, the moment vma_adjust drops the\n * rmap_locks, the properties of the merged vma will be already\n * correct for the whole merged range. Some of those properties like\n * vm_page_prot/vm_flags may be accessed by rmap_walks and they must\n * be correct for the whole merged range immediately after the\n * rmap_locks are released. Otherwise if XXXX would be removed and\n * NNNN would be extended over the XXXX range, remove_migration_ptes\n * or other rmap walkers (if working on addresses beyond the \"end\"\n * parameter) may establish ptes with the wrong permissions of NNNN\n * instead of the right permissions of XXXX.\n */\nstruct vm_area_struct *vma_merge(struct mm_struct *mm,\n\t\t\tstruct vm_area_struct *prev, unsigned long addr,\n\t\t\tunsigned long end, unsigned long vm_flags,\n\t\t\tstruct anon_vma *anon_vma, struct file *file,\n\t\t\tpgoff_t pgoff, struct mempolicy *policy,\n\t\t\tstruct vm_userfaultfd_ctx vm_userfaultfd_ctx)\n{\n\tpgoff_t pglen = (end - addr) >> PAGE_SHIFT;\n\tstruct vm_area_struct *area, *next;\n\tint err;",
"\t/*\n\t * We later require that vma->vm_flags == vm_flags,\n\t * so this tests vma->vm_flags & VM_SPECIAL, too.\n\t */\n\tif (vm_flags & VM_SPECIAL)\n\t\treturn NULL;",
"\tif (prev)\n\t\tnext = prev->vm_next;\n\telse\n\t\tnext = mm->mmap;\n\tarea = next;\n\tif (area && area->vm_end == end)\t\t/* cases 6, 7, 8 */\n\t\tnext = next->vm_next;",
"\t/* verify some invariant that must be enforced by the caller */\n\tVM_WARN_ON(prev && addr <= prev->vm_start);\n\tVM_WARN_ON(area && end > area->vm_end);\n\tVM_WARN_ON(addr >= end);",
"\t/*\n\t * Can it merge with the predecessor?\n\t */\n\tif (prev && prev->vm_end == addr &&\n\t\t\tmpol_equal(vma_policy(prev), policy) &&\n\t\t\tcan_vma_merge_after(prev, vm_flags,\n\t\t\t\t\t anon_vma, file, pgoff,\n\t\t\t\t\t vm_userfaultfd_ctx)) {\n\t\t/*\n\t\t * OK, it can. Can we now merge in the successor as well?\n\t\t */\n\t\tif (next && end == next->vm_start &&\n\t\t\t\tmpol_equal(policy, vma_policy(next)) &&\n\t\t\t\tcan_vma_merge_before(next, vm_flags,\n\t\t\t\t\t\t anon_vma, file,\n\t\t\t\t\t\t pgoff+pglen,\n\t\t\t\t\t\t vm_userfaultfd_ctx) &&\n\t\t\t\tis_mergeable_anon_vma(prev->anon_vma,\n\t\t\t\t\t\t next->anon_vma, NULL)) {\n\t\t\t\t\t\t\t/* cases 1, 6 */\n\t\t\terr = __vma_adjust(prev, prev->vm_start,\n\t\t\t\t\t next->vm_end, prev->vm_pgoff, NULL,\n\t\t\t\t\t prev);\n\t\t} else\t\t\t\t\t/* cases 2, 5, 7 */\n\t\t\terr = __vma_adjust(prev, prev->vm_start,\n\t\t\t\t\t end, prev->vm_pgoff, NULL, prev);\n\t\tif (err)\n\t\t\treturn NULL;\n\t\tkhugepaged_enter_vma_merge(prev, vm_flags);\n\t\treturn prev;\n\t}",
"\t/*\n\t * Can this new request be merged in front of next?\n\t */\n\tif (next && end == next->vm_start &&\n\t\t\tmpol_equal(policy, vma_policy(next)) &&\n\t\t\tcan_vma_merge_before(next, vm_flags,\n\t\t\t\t\t anon_vma, file, pgoff+pglen,\n\t\t\t\t\t vm_userfaultfd_ctx)) {\n\t\tif (prev && addr < prev->vm_end)\t/* case 4 */\n\t\t\terr = __vma_adjust(prev, prev->vm_start,\n\t\t\t\t\t addr, prev->vm_pgoff, NULL, next);\n\t\telse {\t\t\t\t\t/* cases 3, 8 */\n\t\t\terr = __vma_adjust(area, addr, next->vm_end,\n\t\t\t\t\t next->vm_pgoff - pglen, NULL, next);\n\t\t\t/*\n\t\t\t * In case 3 area is already equal to next and\n\t\t\t * this is a noop, but in case 8 \"area\" has\n\t\t\t * been removed and next was expanded over it.\n\t\t\t */\n\t\t\tarea = next;\n\t\t}\n\t\tif (err)\n\t\t\treturn NULL;\n\t\tkhugepaged_enter_vma_merge(area, vm_flags);\n\t\treturn area;\n\t}",
"\treturn NULL;\n}",
"/*\n * Rough compatbility check to quickly see if it's even worth looking\n * at sharing an anon_vma.\n *\n * They need to have the same vm_file, and the flags can only differ\n * in things that mprotect may change.\n *\n * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that\n * we can merge the two vma's. For example, we refuse to merge a vma if\n * there is a vm_ops->close() function, because that indicates that the\n * driver is doing some kind of reference counting. But that doesn't\n * really matter for the anon_vma sharing case.\n */\nstatic int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)\n{\n\treturn a->vm_end == b->vm_start &&\n\t\tmpol_equal(vma_policy(a), vma_policy(b)) &&\n\t\ta->vm_file == b->vm_file &&\n\t\t!((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC|VM_SOFTDIRTY)) &&\n\t\tb->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);\n}",
"/*\n * Do some basic sanity checking to see if we can re-use the anon_vma\n * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be\n * the same as 'old', the other will be the new one that is trying\n * to share the anon_vma.\n *\n * NOTE! This runs with mm_sem held for reading, so it is possible that\n * the anon_vma of 'old' is concurrently in the process of being set up\n * by another page fault trying to merge _that_. But that's ok: if it\n * is being set up, that automatically means that it will be a singleton\n * acceptable for merging, so we can do all of this optimistically. But\n * we do that READ_ONCE() to make sure that we never re-load the pointer.\n *\n * IOW: that the \"list_is_singular()\" test on the anon_vma_chain only\n * matters for the 'stable anon_vma' case (ie the thing we want to avoid\n * is to return an anon_vma that is \"complex\" due to having gone through\n * a fork).\n *\n * We also make sure that the two vma's are compatible (adjacent,\n * and with the same memory policies). That's all stable, even with just\n * a read lock on the mm_sem.\n */\nstatic struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)\n{\n\tif (anon_vma_compatible(a, b)) {\n\t\tstruct anon_vma *anon_vma = READ_ONCE(old->anon_vma);",
"\t\tif (anon_vma && list_is_singular(&old->anon_vma_chain))\n\t\t\treturn anon_vma;\n\t}\n\treturn NULL;\n}",
"/*\n * find_mergeable_anon_vma is used by anon_vma_prepare, to check\n * neighbouring vmas for a suitable anon_vma, before it goes off\n * to allocate a new anon_vma. It checks because a repetitive\n * sequence of mprotects and faults may otherwise lead to distinct\n * anon_vmas being allocated, preventing vma merge in subsequent\n * mprotect.\n */\nstruct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)\n{\n\tstruct anon_vma *anon_vma;\n\tstruct vm_area_struct *near;",
"\tnear = vma->vm_next;\n\tif (!near)\n\t\tgoto try_prev;",
"\tanon_vma = reusable_anon_vma(near, vma, near);\n\tif (anon_vma)\n\t\treturn anon_vma;\ntry_prev:\n\tnear = vma->vm_prev;\n\tif (!near)\n\t\tgoto none;",
"\tanon_vma = reusable_anon_vma(near, near, vma);\n\tif (anon_vma)\n\t\treturn anon_vma;\nnone:\n\t/*\n\t * There's no absolute need to look only at touching neighbours:\n\t * we could search further afield for \"compatible\" anon_vmas.\n\t * But it would probably just be a waste of time searching,\n\t * or lead to too many vmas hanging off the same anon_vma.\n\t * We're trying to allow mprotect remerging later on,\n\t * not trying to minimize memory used for anon_vmas.\n\t */\n\treturn NULL;\n}",
"/*\n * If a hint addr is less than mmap_min_addr change hint to be as\n * low as possible but still greater than mmap_min_addr\n */\nstatic inline unsigned long round_hint_to_min(unsigned long hint)\n{\n\thint &= PAGE_MASK;\n\tif (((void *)hint != NULL) &&\n\t (hint < mmap_min_addr))\n\t\treturn PAGE_ALIGN(mmap_min_addr);\n\treturn hint;\n}",
"static inline int mlock_future_check(struct mm_struct *mm,\n\t\t\t\t unsigned long flags,\n\t\t\t\t unsigned long len)\n{\n\tunsigned long locked, lock_limit;",
"\t/* mlock MCL_FUTURE? */\n\tif (flags & VM_LOCKED) {\n\t\tlocked = len >> PAGE_SHIFT;\n\t\tlocked += mm->locked_vm;\n\t\tlock_limit = rlimit(RLIMIT_MEMLOCK);\n\t\tlock_limit >>= PAGE_SHIFT;\n\t\tif (locked > lock_limit && !capable(CAP_IPC_LOCK))\n\t\t\treturn -EAGAIN;\n\t}\n\treturn 0;\n}",
"static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)\n{\n\tif (S_ISREG(inode->i_mode))\n\t\treturn MAX_LFS_FILESIZE;",
"\tif (S_ISBLK(inode->i_mode))\n\t\treturn MAX_LFS_FILESIZE;",
"\t/* Special \"we do even unsigned file positions\" case */\n\tif (file->f_mode & FMODE_UNSIGNED_OFFSET)\n\t\treturn 0;",
"\t/* Yes, random drivers might want more. But I'm tired of buggy drivers */\n\treturn ULONG_MAX;\n}",
"static inline bool file_mmap_ok(struct file *file, struct inode *inode,\n\t\t\t\tunsigned long pgoff, unsigned long len)\n{\n\tu64 maxsize = file_mmap_size_max(file, inode);",
"\tif (maxsize && len > maxsize)\n\t\treturn false;\n\tmaxsize -= len;\n\tif (pgoff > maxsize >> PAGE_SHIFT)\n\t\treturn false;\n\treturn true;\n}",
"/*\n * The caller must hold down_write(¤t->mm->mmap_sem).\n */\nunsigned long do_mmap(struct file *file, unsigned long addr,\n\t\t\tunsigned long len, unsigned long prot,\n\t\t\tunsigned long flags, vm_flags_t vm_flags,\n\t\t\tunsigned long pgoff, unsigned long *populate,\n\t\t\tstruct list_head *uf)\n{\n\tstruct mm_struct *mm = current->mm;\n\tint pkey = 0;",
"\t*populate = 0;",
"\tif (!len)\n\t\treturn -EINVAL;",
"\t/*\n\t * Does the application expect PROT_READ to imply PROT_EXEC?\n\t *\n\t * (the exception is when the underlying filesystem is noexec\n\t * mounted, in which case we dont add PROT_EXEC.)\n\t */\n\tif ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))\n\t\tif (!(file && path_noexec(&file->f_path)))\n\t\t\tprot |= PROT_EXEC;",
"\t/* force arch specific MAP_FIXED handling in get_unmapped_area */\n\tif (flags & MAP_FIXED_NOREPLACE)\n\t\tflags |= MAP_FIXED;",
"\tif (!(flags & MAP_FIXED))\n\t\taddr = round_hint_to_min(addr);",
"\t/* Careful about overflows.. */\n\tlen = PAGE_ALIGN(len);\n\tif (!len)\n\t\treturn -ENOMEM;",
"\t/* offset overflow? */\n\tif ((pgoff + (len >> PAGE_SHIFT)) < pgoff)\n\t\treturn -EOVERFLOW;",
"\t/* Too many mappings? */\n\tif (mm->map_count > sysctl_max_map_count)\n\t\treturn -ENOMEM;",
"\t/* Obtain the address to map to. we verify (or select) it and ensure\n\t * that it represents a valid section of the address space.\n\t */\n\taddr = get_unmapped_area(file, addr, len, pgoff, flags);\n\tif (offset_in_page(addr))\n\t\treturn addr;",
"\tif (flags & MAP_FIXED_NOREPLACE) {\n\t\tstruct vm_area_struct *vma = find_vma(mm, addr);",
"\t\tif (vma && vma->vm_start < addr + len)\n\t\t\treturn -EEXIST;\n\t}",
"\tif (prot == PROT_EXEC) {\n\t\tpkey = execute_only_pkey(mm);\n\t\tif (pkey < 0)\n\t\t\tpkey = 0;\n\t}",
"\t/* Do simple checking here so the lower-level routines won't have\n\t * to. we assume access permissions have been handled by the open\n\t * of the memory object, so we don't do any here.\n\t */\n\tvm_flags |= calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |\n\t\t\tmm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;",
"\tif (flags & MAP_LOCKED)\n\t\tif (!can_do_mlock())\n\t\t\treturn -EPERM;",
"\tif (mlock_future_check(mm, vm_flags, len))\n\t\treturn -EAGAIN;",
"\tif (file) {\n\t\tstruct inode *inode = file_inode(file);\n\t\tunsigned long flags_mask;",
"\t\tif (!file_mmap_ok(file, inode, pgoff, len))\n\t\t\treturn -EOVERFLOW;",
"\t\tflags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;",
"\t\tswitch (flags & MAP_TYPE) {\n\t\tcase MAP_SHARED:\n\t\t\t/*\n\t\t\t * Force use of MAP_SHARED_VALIDATE with non-legacy\n\t\t\t * flags. E.g. MAP_SYNC is dangerous to use with\n\t\t\t * MAP_SHARED as you don't know which consistency model\n\t\t\t * you will get. We silently ignore unsupported flags\n\t\t\t * with MAP_SHARED to preserve backward compatibility.\n\t\t\t */\n\t\t\tflags &= LEGACY_MAP_MASK;\n\t\t\t/* fall through */\n\t\tcase MAP_SHARED_VALIDATE:\n\t\t\tif (flags & ~flags_mask)\n\t\t\t\treturn -EOPNOTSUPP;\n\t\t\tif ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))\n\t\t\t\treturn -EACCES;",
"\t\t\t/*\n\t\t\t * Make sure we don't allow writing to an append-only\n\t\t\t * file..\n\t\t\t */\n\t\t\tif (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))\n\t\t\t\treturn -EACCES;",
"\t\t\t/*\n\t\t\t * Make sure there are no mandatory locks on the file.\n\t\t\t */\n\t\t\tif (locks_verify_locked(file))\n\t\t\t\treturn -EAGAIN;",
"\t\t\tvm_flags |= VM_SHARED | VM_MAYSHARE;\n\t\t\tif (!(file->f_mode & FMODE_WRITE))\n\t\t\t\tvm_flags &= ~(VM_MAYWRITE | VM_SHARED);",
"\t\t\t/* fall through */\n\t\tcase MAP_PRIVATE:\n\t\t\tif (!(file->f_mode & FMODE_READ))\n\t\t\t\treturn -EACCES;\n\t\t\tif (path_noexec(&file->f_path)) {\n\t\t\t\tif (vm_flags & VM_EXEC)\n\t\t\t\t\treturn -EPERM;\n\t\t\t\tvm_flags &= ~VM_MAYEXEC;\n\t\t\t}",
"\t\t\tif (!file->f_op->mmap)\n\t\t\t\treturn -ENODEV;\n\t\t\tif (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))\n\t\t\t\treturn -EINVAL;\n\t\t\tbreak;",
"\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\t} else {\n\t\tswitch (flags & MAP_TYPE) {\n\t\tcase MAP_SHARED:\n\t\t\tif (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))\n\t\t\t\treturn -EINVAL;\n\t\t\t/*\n\t\t\t * Ignore pgoff.\n\t\t\t */\n\t\t\tpgoff = 0;\n\t\t\tvm_flags |= VM_SHARED | VM_MAYSHARE;\n\t\t\tbreak;\n\t\tcase MAP_PRIVATE:\n\t\t\t/*\n\t\t\t * Set pgoff according to addr for anon_vma.\n\t\t\t */\n\t\t\tpgoff = addr >> PAGE_SHIFT;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\t}",
"\t/*\n\t * Set 'VM_NORESERVE' if we should not account for the\n\t * memory use of this mapping.\n\t */\n\tif (flags & MAP_NORESERVE) {\n\t\t/* We honor MAP_NORESERVE if allowed to overcommit */\n\t\tif (sysctl_overcommit_memory != OVERCOMMIT_NEVER)\n\t\t\tvm_flags |= VM_NORESERVE;",
"\t\t/* hugetlb applies strict overcommit unless MAP_NORESERVE */\n\t\tif (file && is_file_hugepages(file))\n\t\t\tvm_flags |= VM_NORESERVE;\n\t}",
"\taddr = mmap_region(file, addr, len, vm_flags, pgoff, uf);\n\tif (!IS_ERR_VALUE(addr) &&\n\t ((vm_flags & VM_LOCKED) ||\n\t (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))\n\t\t*populate = len;\n\treturn addr;\n}",
"unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,\n\t\t\t unsigned long prot, unsigned long flags,\n\t\t\t unsigned long fd, unsigned long pgoff)\n{\n\tstruct file *file = NULL;\n\tunsigned long retval;",
"\tif (!(flags & MAP_ANONYMOUS)) {\n\t\taudit_mmap_fd(fd, flags);\n\t\tfile = fget(fd);\n\t\tif (!file)\n\t\t\treturn -EBADF;\n\t\tif (is_file_hugepages(file))\n\t\t\tlen = ALIGN(len, huge_page_size(hstate_file(file)));\n\t\tretval = -EINVAL;\n\t\tif (unlikely(flags & MAP_HUGETLB && !is_file_hugepages(file)))\n\t\t\tgoto out_fput;\n\t} else if (flags & MAP_HUGETLB) {\n\t\tstruct user_struct *user = NULL;\n\t\tstruct hstate *hs;",
"\t\ths = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);\n\t\tif (!hs)\n\t\t\treturn -EINVAL;",
"\t\tlen = ALIGN(len, huge_page_size(hs));\n\t\t/*\n\t\t * VM_NORESERVE is used because the reservations will be\n\t\t * taken when vm_ops->mmap() is called\n\t\t * A dummy user value is used because we are not locking\n\t\t * memory so no accounting is necessary\n\t\t */\n\t\tfile = hugetlb_file_setup(HUGETLB_ANON_FILE, len,\n\t\t\t\tVM_NORESERVE,\n\t\t\t\t&user, HUGETLB_ANONHUGE_INODE,\n\t\t\t\t(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);\n\t\tif (IS_ERR(file))\n\t\t\treturn PTR_ERR(file);\n\t}",
"\tflags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);",
"\tretval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);\nout_fput:\n\tif (file)\n\t\tfput(file);\n\treturn retval;\n}",
"SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,\n\t\tunsigned long, prot, unsigned long, flags,\n\t\tunsigned long, fd, unsigned long, pgoff)\n{\n\treturn ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);\n}",
"#ifdef __ARCH_WANT_SYS_OLD_MMAP\nstruct mmap_arg_struct {\n\tunsigned long addr;\n\tunsigned long len;\n\tunsigned long prot;\n\tunsigned long flags;\n\tunsigned long fd;\n\tunsigned long offset;\n};",
"SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)\n{\n\tstruct mmap_arg_struct a;",
"\tif (copy_from_user(&a, arg, sizeof(a)))\n\t\treturn -EFAULT;\n\tif (offset_in_page(a.offset))\n\t\treturn -EINVAL;",
"\treturn ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,\n\t\t\t a.offset >> PAGE_SHIFT);\n}\n#endif /* __ARCH_WANT_SYS_OLD_MMAP */",
"/*\n * Some shared mappigns will want the pages marked read-only\n * to track write events. If so, we'll downgrade vm_page_prot\n * to the private version (using protection_map[] without the\n * VM_SHARED bit).\n */\nint vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)\n{\n\tvm_flags_t vm_flags = vma->vm_flags;\n\tconst struct vm_operations_struct *vm_ops = vma->vm_ops;",
"\t/* If it was private or non-writable, the write bit is already clear */\n\tif ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))\n\t\treturn 0;",
"\t/* The backer wishes to know when pages are first written to? */\n\tif (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))\n\t\treturn 1;",
"\t/* The open routine did something to the protections that pgprot_modify\n\t * won't preserve? */\n\tif (pgprot_val(vm_page_prot) !=\n\t pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))\n\t\treturn 0;",
"\t/* Do we need to track softdirty? */\n\tif (IS_ENABLED(CONFIG_MEM_SOFT_DIRTY) && !(vm_flags & VM_SOFTDIRTY))\n\t\treturn 1;",
"\t/* Specialty mapping? */\n\tif (vm_flags & VM_PFNMAP)\n\t\treturn 0;",
"\t/* Can the mapping track the dirty pages? */\n\treturn vma->vm_file && vma->vm_file->f_mapping &&\n\t\tmapping_cap_account_dirty(vma->vm_file->f_mapping);\n}",
"/*\n * We account for memory if it's a private writeable mapping,\n * not hugepages and VM_NORESERVE wasn't set.\n */\nstatic inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)\n{\n\t/*\n\t * hugetlb has its own accounting separate from the core VM\n\t * VM_HUGETLB may not be set yet so we cannot check for that flag.\n\t */\n\tif (file && is_file_hugepages(file))\n\t\treturn 0;",
"\treturn (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;\n}",
"unsigned long mmap_region(struct file *file, unsigned long addr,\n\t\tunsigned long len, vm_flags_t vm_flags, unsigned long pgoff,\n\t\tstruct list_head *uf)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma, *prev;\n\tint error;\n\tstruct rb_node **rb_link, *rb_parent;\n\tunsigned long charged = 0;",
"\t/* Check against address space limit. */\n\tif (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {\n\t\tunsigned long nr_pages;",
"\t\t/*\n\t\t * MAP_FIXED may remove pages of mappings that intersects with\n\t\t * requested mapping. Account for the pages it would unmap.\n\t\t */\n\t\tnr_pages = count_vma_pages_range(mm, addr, addr + len);",
"\t\tif (!may_expand_vm(mm, vm_flags,\n\t\t\t\t\t(len >> PAGE_SHIFT) - nr_pages))\n\t\t\treturn -ENOMEM;\n\t}",
"\t/* Clear old maps */\n\twhile (find_vma_links(mm, addr, addr + len, &prev, &rb_link,\n\t\t\t &rb_parent)) {\n\t\tif (do_munmap(mm, addr, len, uf))\n\t\t\treturn -ENOMEM;\n\t}",
"\t/*\n\t * Private writable mapping: check memory availability\n\t */\n\tif (accountable_mapping(file, vm_flags)) {\n\t\tcharged = len >> PAGE_SHIFT;\n\t\tif (security_vm_enough_memory_mm(mm, charged))\n\t\t\treturn -ENOMEM;\n\t\tvm_flags |= VM_ACCOUNT;\n\t}",
"\t/*\n\t * Can we just expand an old mapping?\n\t */\n\tvma = vma_merge(mm, prev, addr, addr + len, vm_flags,\n\t\t\tNULL, file, pgoff, NULL, NULL_VM_UFFD_CTX);\n\tif (vma)\n\t\tgoto out;",
"\t/*\n\t * Determine the object being mapped and call the appropriate\n\t * specific mapper. the address has already been validated, but\n\t * not unmapped, but the maps are removed from the list.\n\t */\n\tvma = vm_area_alloc(mm);\n\tif (!vma) {\n\t\terror = -ENOMEM;\n\t\tgoto unacct_error;\n\t}",
"\tvma->vm_start = addr;\n\tvma->vm_end = addr + len;\n\tvma->vm_flags = vm_flags;\n\tvma->vm_page_prot = vm_get_page_prot(vm_flags);\n\tvma->vm_pgoff = pgoff;",
"\tif (file) {\n\t\tif (vm_flags & VM_DENYWRITE) {\n\t\t\terror = deny_write_access(file);\n\t\t\tif (error)\n\t\t\t\tgoto free_vma;\n\t\t}\n\t\tif (vm_flags & VM_SHARED) {\n\t\t\terror = mapping_map_writable(file->f_mapping);\n\t\t\tif (error)\n\t\t\t\tgoto allow_write_and_free_vma;\n\t\t}",
"\t\t/* ->mmap() can change vma->vm_file, but must guarantee that\n\t\t * vma_link() below can deny write-access if VM_DENYWRITE is set\n\t\t * and map writably if VM_SHARED is set. This usually means the\n\t\t * new file must not have been exposed to user-space, yet.\n\t\t */\n\t\tvma->vm_file = get_file(file);\n\t\terror = call_mmap(file, vma);\n\t\tif (error)\n\t\t\tgoto unmap_and_free_vma;",
"\t\t/* Can addr have changed??\n\t\t *\n\t\t * Answer: Yes, several device drivers can do it in their\n\t\t * f_op->mmap method. -DaveM\n\t\t * Bug: If addr is changed, prev, rb_link, rb_parent should\n\t\t * be updated for vma_link()\n\t\t */\n\t\tWARN_ON_ONCE(addr != vma->vm_start);",
"\t\taddr = vma->vm_start;\n\t\tvm_flags = vma->vm_flags;\n\t} else if (vm_flags & VM_SHARED) {\n\t\terror = shmem_zero_setup(vma);\n\t\tif (error)\n\t\t\tgoto free_vma;\n\t} else {\n\t\tvma_set_anonymous(vma);\n\t}",
"\tvma_link(mm, vma, prev, rb_link, rb_parent);\n\t/* Once vma denies write, undo our temporary denial count */\n\tif (file) {\n\t\tif (vm_flags & VM_SHARED)\n\t\t\tmapping_unmap_writable(file->f_mapping);\n\t\tif (vm_flags & VM_DENYWRITE)\n\t\t\tallow_write_access(file);\n\t}\n\tfile = vma->vm_file;\nout:\n\tperf_event_mmap(vma);",
"\tvm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);\n\tif (vm_flags & VM_LOCKED) {\n\t\tif ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||\n\t\t\t\t\tis_vm_hugetlb_page(vma) ||\n\t\t\t\t\tvma == get_gate_vma(current->mm))\n\t\t\tvma->vm_flags &= VM_LOCKED_CLEAR_MASK;\n\t\telse\n\t\t\tmm->locked_vm += (len >> PAGE_SHIFT);\n\t}",
"\tif (file)\n\t\tuprobe_mmap(vma);",
"\t/*\n\t * New (or expanded) vma always get soft dirty status.\n\t * Otherwise user-space soft-dirty page tracker won't\n\t * be able to distinguish situation when vma area unmapped,\n\t * then new mapped in-place (which must be aimed as\n\t * a completely new data area).\n\t */\n\tvma->vm_flags |= VM_SOFTDIRTY;",
"\tvma_set_page_prot(vma);",
"\treturn addr;",
"unmap_and_free_vma:\n\tvma->vm_file = NULL;\n\tfput(file);",
"\t/* Undo any partial mapping done by a device driver. */\n\tunmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);\n\tcharged = 0;\n\tif (vm_flags & VM_SHARED)\n\t\tmapping_unmap_writable(file->f_mapping);\nallow_write_and_free_vma:\n\tif (vm_flags & VM_DENYWRITE)\n\t\tallow_write_access(file);\nfree_vma:\n\tvm_area_free(vma);\nunacct_error:\n\tif (charged)\n\t\tvm_unacct_memory(charged);\n\treturn error;\n}",
"unsigned long unmapped_area(struct vm_unmapped_area_info *info)\n{\n\t/*\n\t * We implement the search by looking for an rbtree node that\n\t * immediately follows a suitable gap. That is,\n\t * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;\n\t * - gap_end = vma->vm_start >= info->low_limit + length;\n\t * - gap_end - gap_start >= length\n\t */",
"\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tunsigned long length, low_limit, high_limit, gap_start, gap_end;",
"\t/* Adjust search length to account for worst case alignment overhead */\n\tlength = info->length + info->align_mask;\n\tif (length < info->length)\n\t\treturn -ENOMEM;",
"\t/* Adjust search limits by the desired length */\n\tif (info->high_limit < length)\n\t\treturn -ENOMEM;\n\thigh_limit = info->high_limit - length;",
"\tif (info->low_limit > high_limit)\n\t\treturn -ENOMEM;\n\tlow_limit = info->low_limit + length;",
"\t/* Check if rbtree root looks promising */\n\tif (RB_EMPTY_ROOT(&mm->mm_rb))\n\t\tgoto check_highest;\n\tvma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);\n\tif (vma->rb_subtree_gap < length)\n\t\tgoto check_highest;",
"\twhile (true) {\n\t\t/* Visit left subtree if it looks promising */\n\t\tgap_end = vm_start_gap(vma);\n\t\tif (gap_end >= low_limit && vma->vm_rb.rb_left) {\n\t\t\tstruct vm_area_struct *left =\n\t\t\t\trb_entry(vma->vm_rb.rb_left,\n\t\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (left->rb_subtree_gap >= length) {\n\t\t\t\tvma = left;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}",
"\t\tgap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;\ncheck_current:\n\t\t/* Check if current node has a suitable gap */\n\t\tif (gap_start > high_limit)\n\t\t\treturn -ENOMEM;\n\t\tif (gap_end >= low_limit &&\n\t\t gap_end > gap_start && gap_end - gap_start >= length)\n\t\t\tgoto found;",
"\t\t/* Visit right subtree if it looks promising */\n\t\tif (vma->vm_rb.rb_right) {\n\t\t\tstruct vm_area_struct *right =\n\t\t\t\trb_entry(vma->vm_rb.rb_right,\n\t\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (right->rb_subtree_gap >= length) {\n\t\t\t\tvma = right;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}",
"\t\t/* Go back up the rbtree to find next candidate node */\n\t\twhile (true) {\n\t\t\tstruct rb_node *prev = &vma->vm_rb;\n\t\t\tif (!rb_parent(prev))\n\t\t\t\tgoto check_highest;\n\t\t\tvma = rb_entry(rb_parent(prev),\n\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (prev == vma->vm_rb.rb_left) {\n\t\t\t\tgap_start = vm_end_gap(vma->vm_prev);\n\t\t\t\tgap_end = vm_start_gap(vma);\n\t\t\t\tgoto check_current;\n\t\t\t}\n\t\t}\n\t}",
"check_highest:\n\t/* Check highest gap, which does not precede any rbtree node */\n\tgap_start = mm->highest_vm_end;\n\tgap_end = ULONG_MAX; /* Only for VM_BUG_ON below */\n\tif (gap_start > high_limit)\n\t\treturn -ENOMEM;",
"found:\n\t/* We found a suitable gap. Clip it with the original low_limit. */\n\tif (gap_start < info->low_limit)\n\t\tgap_start = info->low_limit;",
"\t/* Adjust gap address to the desired alignment */\n\tgap_start += (info->align_offset - gap_start) & info->align_mask;",
"\tVM_BUG_ON(gap_start + info->length > info->high_limit);\n\tVM_BUG_ON(gap_start + info->length > gap_end);\n\treturn gap_start;\n}",
"unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tunsigned long length, low_limit, high_limit, gap_start, gap_end;",
"\t/* Adjust search length to account for worst case alignment overhead */\n\tlength = info->length + info->align_mask;\n\tif (length < info->length)\n\t\treturn -ENOMEM;",
"\t/*\n\t * Adjust search limits by the desired length.\n\t * See implementation comment at top of unmapped_area().\n\t */\n\tgap_end = info->high_limit;\n\tif (gap_end < length)\n\t\treturn -ENOMEM;\n\thigh_limit = gap_end - length;",
"\tif (info->low_limit > high_limit)\n\t\treturn -ENOMEM;\n\tlow_limit = info->low_limit + length;",
"\t/* Check highest gap, which does not precede any rbtree node */\n\tgap_start = mm->highest_vm_end;\n\tif (gap_start <= high_limit)\n\t\tgoto found_highest;",
"\t/* Check if rbtree root looks promising */\n\tif (RB_EMPTY_ROOT(&mm->mm_rb))\n\t\treturn -ENOMEM;\n\tvma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);\n\tif (vma->rb_subtree_gap < length)\n\t\treturn -ENOMEM;",
"\twhile (true) {\n\t\t/* Visit right subtree if it looks promising */\n\t\tgap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;\n\t\tif (gap_start <= high_limit && vma->vm_rb.rb_right) {\n\t\t\tstruct vm_area_struct *right =\n\t\t\t\trb_entry(vma->vm_rb.rb_right,\n\t\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (right->rb_subtree_gap >= length) {\n\t\t\t\tvma = right;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}",
"check_current:\n\t\t/* Check if current node has a suitable gap */\n\t\tgap_end = vm_start_gap(vma);\n\t\tif (gap_end < low_limit)\n\t\t\treturn -ENOMEM;\n\t\tif (gap_start <= high_limit &&\n\t\t gap_end > gap_start && gap_end - gap_start >= length)\n\t\t\tgoto found;",
"\t\t/* Visit left subtree if it looks promising */\n\t\tif (vma->vm_rb.rb_left) {\n\t\t\tstruct vm_area_struct *left =\n\t\t\t\trb_entry(vma->vm_rb.rb_left,\n\t\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (left->rb_subtree_gap >= length) {\n\t\t\t\tvma = left;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}",
"\t\t/* Go back up the rbtree to find next candidate node */\n\t\twhile (true) {\n\t\t\tstruct rb_node *prev = &vma->vm_rb;\n\t\t\tif (!rb_parent(prev))\n\t\t\t\treturn -ENOMEM;\n\t\t\tvma = rb_entry(rb_parent(prev),\n\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (prev == vma->vm_rb.rb_right) {\n\t\t\t\tgap_start = vma->vm_prev ?\n\t\t\t\t\tvm_end_gap(vma->vm_prev) : 0;\n\t\t\t\tgoto check_current;\n\t\t\t}\n\t\t}\n\t}",
"found:\n\t/* We found a suitable gap. Clip it with the original high_limit. */\n\tif (gap_end > info->high_limit)\n\t\tgap_end = info->high_limit;",
"found_highest:\n\t/* Compute highest gap address at the desired alignment */\n\tgap_end -= info->length;\n\tgap_end -= (gap_end - info->align_offset) & info->align_mask;",
"\tVM_BUG_ON(gap_end < info->low_limit);\n\tVM_BUG_ON(gap_end < gap_start);\n\treturn gap_end;\n}",
"\n#ifndef arch_get_mmap_end\n#define arch_get_mmap_end(addr)\t(TASK_SIZE)\n#endif",
"#ifndef arch_get_mmap_base\n#define arch_get_mmap_base(addr, base) (base)\n#endif",
"/* Get an address range which is currently unmapped.\n * For shmat() with addr=0.\n *\n * Ugly calling convention alert:\n * Return value with the low bits set means error value,\n * ie\n *\tif (ret & ~PAGE_MASK)\n *\t\terror = ret;\n *\n * This function \"knows\" that -ENOMEM has the bits set.\n */\n#ifndef HAVE_ARCH_UNMAPPED_AREA\nunsigned long\narch_get_unmapped_area(struct file *filp, unsigned long addr,\n\t\tunsigned long len, unsigned long pgoff, unsigned long flags)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma, *prev;\n\tstruct vm_unmapped_area_info info;\n\tconst unsigned long mmap_end = arch_get_mmap_end(addr);",
"\tif (len > mmap_end - mmap_min_addr)\n\t\treturn -ENOMEM;",
"\tif (flags & MAP_FIXED)\n\t\treturn addr;",
"\tif (addr) {\n\t\taddr = PAGE_ALIGN(addr);\n\t\tvma = find_vma_prev(mm, addr, &prev);\n\t\tif (mmap_end - len >= addr && addr >= mmap_min_addr &&\n\t\t (!vma || addr + len <= vm_start_gap(vma)) &&\n\t\t (!prev || addr >= vm_end_gap(prev)))\n\t\t\treturn addr;\n\t}",
"\tinfo.flags = 0;\n\tinfo.length = len;\n\tinfo.low_limit = mm->mmap_base;\n\tinfo.high_limit = mmap_end;\n\tinfo.align_mask = 0;\n\treturn vm_unmapped_area(&info);\n}\n#endif",
"/*\n * This mmap-allocator allocates new areas top-down from below the\n * stack's low limit (the base):\n */\n#ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN\nunsigned long\narch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,\n\t\t\t const unsigned long len, const unsigned long pgoff,\n\t\t\t const unsigned long flags)\n{\n\tstruct vm_area_struct *vma, *prev;\n\tstruct mm_struct *mm = current->mm;\n\tunsigned long addr = addr0;\n\tstruct vm_unmapped_area_info info;\n\tconst unsigned long mmap_end = arch_get_mmap_end(addr);",
"\t/* requested length too big for entire address space */\n\tif (len > mmap_end - mmap_min_addr)\n\t\treturn -ENOMEM;",
"\tif (flags & MAP_FIXED)\n\t\treturn addr;",
"\t/* requesting a specific address */\n\tif (addr) {\n\t\taddr = PAGE_ALIGN(addr);\n\t\tvma = find_vma_prev(mm, addr, &prev);\n\t\tif (mmap_end - len >= addr && addr >= mmap_min_addr &&\n\t\t\t\t(!vma || addr + len <= vm_start_gap(vma)) &&\n\t\t\t\t(!prev || addr >= vm_end_gap(prev)))\n\t\t\treturn addr;\n\t}",
"\tinfo.flags = VM_UNMAPPED_AREA_TOPDOWN;\n\tinfo.length = len;\n\tinfo.low_limit = max(PAGE_SIZE, mmap_min_addr);\n\tinfo.high_limit = arch_get_mmap_base(addr, mm->mmap_base);\n\tinfo.align_mask = 0;\n\taddr = vm_unmapped_area(&info);",
"\t/*\n\t * A failed mmap() very likely causes application failure,\n\t * so fall back to the bottom-up function here. This scenario\n\t * can happen with large stack limits and large mmap()\n\t * allocations.\n\t */\n\tif (offset_in_page(addr)) {\n\t\tVM_BUG_ON(addr != -ENOMEM);\n\t\tinfo.flags = 0;\n\t\tinfo.low_limit = TASK_UNMAPPED_BASE;\n\t\tinfo.high_limit = mmap_end;\n\t\taddr = vm_unmapped_area(&info);\n\t}",
"\treturn addr;\n}\n#endif",
"unsigned long\nget_unmapped_area(struct file *file, unsigned long addr, unsigned long len,\n\t\tunsigned long pgoff, unsigned long flags)\n{\n\tunsigned long (*get_area)(struct file *, unsigned long,\n\t\t\t\t unsigned long, unsigned long, unsigned long);",
"\tunsigned long error = arch_mmap_check(addr, len, flags);\n\tif (error)\n\t\treturn error;",
"\t/* Careful about overflows.. */\n\tif (len > TASK_SIZE)\n\t\treturn -ENOMEM;",
"\tget_area = current->mm->get_unmapped_area;\n\tif (file) {\n\t\tif (file->f_op->get_unmapped_area)\n\t\t\tget_area = file->f_op->get_unmapped_area;\n\t} else if (flags & MAP_SHARED) {\n\t\t/*\n\t\t * mmap_region() will call shmem_zero_setup() to create a file,\n\t\t * so use shmem's get_unmapped_area in case it can be huge.\n\t\t * do_mmap_pgoff() will clear pgoff, so match alignment.\n\t\t */\n\t\tpgoff = 0;\n\t\tget_area = shmem_get_unmapped_area;\n\t}",
"\taddr = get_area(file, addr, len, pgoff, flags);\n\tif (IS_ERR_VALUE(addr))\n\t\treturn addr;",
"\tif (addr > TASK_SIZE - len)\n\t\treturn -ENOMEM;\n\tif (offset_in_page(addr))\n\t\treturn -EINVAL;",
"\terror = security_mmap_addr(addr);\n\treturn error ? error : addr;\n}",
"EXPORT_SYMBOL(get_unmapped_area);",
"/* Look up the first VMA which satisfies addr < vm_end, NULL if none. */\nstruct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)\n{\n\tstruct rb_node *rb_node;\n\tstruct vm_area_struct *vma;",
"\t/* Check the cache first. */\n\tvma = vmacache_find(mm, addr);\n\tif (likely(vma))\n\t\treturn vma;",
"\trb_node = mm->mm_rb.rb_node;",
"\twhile (rb_node) {\n\t\tstruct vm_area_struct *tmp;",
"\t\ttmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);",
"\t\tif (tmp->vm_end > addr) {\n\t\t\tvma = tmp;\n\t\t\tif (tmp->vm_start <= addr)\n\t\t\t\tbreak;\n\t\t\trb_node = rb_node->rb_left;\n\t\t} else\n\t\t\trb_node = rb_node->rb_right;\n\t}",
"\tif (vma)\n\t\tvmacache_update(addr, vma);\n\treturn vma;\n}",
"EXPORT_SYMBOL(find_vma);",
"/*\n * Same as find_vma, but also return a pointer to the previous VMA in *pprev.\n */\nstruct vm_area_struct *\nfind_vma_prev(struct mm_struct *mm, unsigned long addr,\n\t\t\tstruct vm_area_struct **pprev)\n{\n\tstruct vm_area_struct *vma;",
"\tvma = find_vma(mm, addr);\n\tif (vma) {\n\t\t*pprev = vma->vm_prev;\n\t} else {\n\t\tstruct rb_node *rb_node = mm->mm_rb.rb_node;\n\t\t*pprev = NULL;\n\t\twhile (rb_node) {\n\t\t\t*pprev = rb_entry(rb_node, struct vm_area_struct, vm_rb);\n\t\t\trb_node = rb_node->rb_right;\n\t\t}\n\t}\n\treturn vma;\n}",
"/*\n * Verify that the stack growth is acceptable and\n * update accounting. This is shared with both the\n * grow-up and grow-down cases.\n */\nstatic int acct_stack_growth(struct vm_area_struct *vma,\n\t\t\t unsigned long size, unsigned long grow)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tunsigned long new_start;",
"\t/* address space limit tests */\n\tif (!may_expand_vm(mm, vma->vm_flags, grow))\n\t\treturn -ENOMEM;",
"\t/* Stack limit test */\n\tif (size > rlimit(RLIMIT_STACK))\n\t\treturn -ENOMEM;",
"\t/* mlock limit tests */\n\tif (vma->vm_flags & VM_LOCKED) {\n\t\tunsigned long locked;\n\t\tunsigned long limit;\n\t\tlocked = mm->locked_vm + grow;\n\t\tlimit = rlimit(RLIMIT_MEMLOCK);\n\t\tlimit >>= PAGE_SHIFT;\n\t\tif (locked > limit && !capable(CAP_IPC_LOCK))\n\t\t\treturn -ENOMEM;\n\t}",
"\t/* Check to ensure the stack will not grow into a hugetlb-only region */\n\tnew_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :\n\t\t\tvma->vm_end - size;\n\tif (is_hugepage_only_range(vma->vm_mm, new_start, size))\n\t\treturn -EFAULT;",
"\t/*\n\t * Overcommit.. This must be the final test, as it will\n\t * update security statistics.\n\t */\n\tif (security_vm_enough_memory_mm(mm, grow))\n\t\treturn -ENOMEM;",
"\treturn 0;\n}",
"#if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)\n/*\n * PA-RISC uses this for its stack; IA64 for its Register Backing Store.\n * vma is the last one with address > vma->vm_end. Have to extend vma.\n */\nint expand_upwards(struct vm_area_struct *vma, unsigned long address)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tstruct vm_area_struct *next;\n\tunsigned long gap_addr;\n\tint error = 0;",
"\tif (!(vma->vm_flags & VM_GROWSUP))\n\t\treturn -EFAULT;",
"\t/* Guard against exceeding limits of the address space. */\n\taddress &= PAGE_MASK;\n\tif (address >= (TASK_SIZE & PAGE_MASK))\n\t\treturn -ENOMEM;\n\taddress += PAGE_SIZE;",
"\t/* Enforce stack_guard_gap */\n\tgap_addr = address + stack_guard_gap;",
"\t/* Guard against overflow */\n\tif (gap_addr < address || gap_addr > TASK_SIZE)\n\t\tgap_addr = TASK_SIZE;",
"\tnext = vma->vm_next;\n\tif (next && next->vm_start < gap_addr &&\n\t\t\t(next->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {\n\t\tif (!(next->vm_flags & VM_GROWSUP))\n\t\t\treturn -ENOMEM;\n\t\t/* Check that both stack segments have the same anon_vma? */\n\t}",
"\t/* We must make sure the anon_vma is allocated. */\n\tif (unlikely(anon_vma_prepare(vma)))\n\t\treturn -ENOMEM;",
"\t/*\n\t * vma->vm_start/vm_end cannot change under us because the caller\n\t * is required to hold the mmap_sem in read mode. We need the\n\t * anon_vma lock to serialize against concurrent expand_stacks.\n\t */\n\tanon_vma_lock_write(vma->anon_vma);",
"\t/* Somebody else might have raced and expanded it already */\n\tif (address > vma->vm_end) {\n\t\tunsigned long size, grow;",
"\t\tsize = address - vma->vm_start;\n\t\tgrow = (address - vma->vm_end) >> PAGE_SHIFT;",
"\t\terror = -ENOMEM;\n\t\tif (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {\n\t\t\terror = acct_stack_growth(vma, size, grow);\n\t\t\tif (!error) {\n\t\t\t\t/*\n\t\t\t\t * vma_gap_update() doesn't support concurrent\n\t\t\t\t * updates, but we only hold a shared mmap_sem\n\t\t\t\t * lock here, so we need to protect against\n\t\t\t\t * concurrent vma expansions.\n\t\t\t\t * anon_vma_lock_write() doesn't help here, as\n\t\t\t\t * we don't guarantee that all growable vmas\n\t\t\t\t * in a mm share the same root anon vma.\n\t\t\t\t * So, we reuse mm->page_table_lock to guard\n\t\t\t\t * against concurrent vma expansions.\n\t\t\t\t */\n\t\t\t\tspin_lock(&mm->page_table_lock);\n\t\t\t\tif (vma->vm_flags & VM_LOCKED)\n\t\t\t\t\tmm->locked_vm += grow;\n\t\t\t\tvm_stat_account(mm, vma->vm_flags, grow);\n\t\t\t\tanon_vma_interval_tree_pre_update_vma(vma);\n\t\t\t\tvma->vm_end = address;\n\t\t\t\tanon_vma_interval_tree_post_update_vma(vma);\n\t\t\t\tif (vma->vm_next)\n\t\t\t\t\tvma_gap_update(vma->vm_next);\n\t\t\t\telse\n\t\t\t\t\tmm->highest_vm_end = vm_end_gap(vma);\n\t\t\t\tspin_unlock(&mm->page_table_lock);",
"\t\t\t\tperf_event_mmap(vma);\n\t\t\t}\n\t\t}\n\t}\n\tanon_vma_unlock_write(vma->anon_vma);\n\tkhugepaged_enter_vma_merge(vma, vma->vm_flags);\n\tvalidate_mm(mm);\n\treturn error;\n}\n#endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */",
"/*\n * vma is the first one with address < vma->vm_start. Have to extend vma.\n */\nint expand_downwards(struct vm_area_struct *vma,\n\t\t\t\t unsigned long address)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tstruct vm_area_struct *prev;",
"\tint error;",
"\n\taddress &= PAGE_MASK;",
"\terror = security_mmap_addr(address);\n\tif (error)\n\t\treturn error;",
"\n\t/* Enforce stack_guard_gap */\n\tprev = vma->vm_prev;\n\t/* Check that both stack segments have the same anon_vma? */\n\tif (prev && !(prev->vm_flags & VM_GROWSDOWN) &&\n\t\t\t(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {\n\t\tif (address - prev->vm_end < stack_guard_gap)\n\t\t\treturn -ENOMEM;\n\t}",
"\t/* We must make sure the anon_vma is allocated. */\n\tif (unlikely(anon_vma_prepare(vma)))\n\t\treturn -ENOMEM;",
"\t/*\n\t * vma->vm_start/vm_end cannot change under us because the caller\n\t * is required to hold the mmap_sem in read mode. We need the\n\t * anon_vma lock to serialize against concurrent expand_stacks.\n\t */\n\tanon_vma_lock_write(vma->anon_vma);",
"\t/* Somebody else might have raced and expanded it already */\n\tif (address < vma->vm_start) {\n\t\tunsigned long size, grow;",
"\t\tsize = vma->vm_end - address;\n\t\tgrow = (vma->vm_start - address) >> PAGE_SHIFT;",
"\t\terror = -ENOMEM;\n\t\tif (grow <= vma->vm_pgoff) {\n\t\t\terror = acct_stack_growth(vma, size, grow);\n\t\t\tif (!error) {\n\t\t\t\t/*\n\t\t\t\t * vma_gap_update() doesn't support concurrent\n\t\t\t\t * updates, but we only hold a shared mmap_sem\n\t\t\t\t * lock here, so we need to protect against\n\t\t\t\t * concurrent vma expansions.\n\t\t\t\t * anon_vma_lock_write() doesn't help here, as\n\t\t\t\t * we don't guarantee that all growable vmas\n\t\t\t\t * in a mm share the same root anon vma.\n\t\t\t\t * So, we reuse mm->page_table_lock to guard\n\t\t\t\t * against concurrent vma expansions.\n\t\t\t\t */\n\t\t\t\tspin_lock(&mm->page_table_lock);\n\t\t\t\tif (vma->vm_flags & VM_LOCKED)\n\t\t\t\t\tmm->locked_vm += grow;\n\t\t\t\tvm_stat_account(mm, vma->vm_flags, grow);\n\t\t\t\tanon_vma_interval_tree_pre_update_vma(vma);\n\t\t\t\tvma->vm_start = address;\n\t\t\t\tvma->vm_pgoff -= grow;\n\t\t\t\tanon_vma_interval_tree_post_update_vma(vma);\n\t\t\t\tvma_gap_update(vma);\n\t\t\t\tspin_unlock(&mm->page_table_lock);",
"\t\t\t\tperf_event_mmap(vma);\n\t\t\t}\n\t\t}\n\t}\n\tanon_vma_unlock_write(vma->anon_vma);\n\tkhugepaged_enter_vma_merge(vma, vma->vm_flags);\n\tvalidate_mm(mm);\n\treturn error;\n}",
"/* enforced gap between the expanding stack and other mappings. */\nunsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;",
"static int __init cmdline_parse_stack_guard_gap(char *p)\n{\n\tunsigned long val;\n\tchar *endptr;",
"\tval = simple_strtoul(p, &endptr, 10);\n\tif (!*endptr)\n\t\tstack_guard_gap = val << PAGE_SHIFT;",
"\treturn 0;\n}\n__setup(\"stack_guard_gap=\", cmdline_parse_stack_guard_gap);",
"#ifdef CONFIG_STACK_GROWSUP\nint expand_stack(struct vm_area_struct *vma, unsigned long address)\n{\n\treturn expand_upwards(vma, address);\n}",
"struct vm_area_struct *\nfind_extend_vma(struct mm_struct *mm, unsigned long addr)\n{\n\tstruct vm_area_struct *vma, *prev;",
"\taddr &= PAGE_MASK;\n\tvma = find_vma_prev(mm, addr, &prev);\n\tif (vma && (vma->vm_start <= addr))\n\t\treturn vma;\n\tif (!prev || expand_stack(prev, addr))\n\t\treturn NULL;\n\tif (prev->vm_flags & VM_LOCKED)\n\t\tpopulate_vma_page_range(prev, addr, prev->vm_end, NULL);\n\treturn prev;\n}\n#else\nint expand_stack(struct vm_area_struct *vma, unsigned long address)\n{\n\treturn expand_downwards(vma, address);\n}",
"struct vm_area_struct *\nfind_extend_vma(struct mm_struct *mm, unsigned long addr)\n{\n\tstruct vm_area_struct *vma;\n\tunsigned long start;",
"\taddr &= PAGE_MASK;\n\tvma = find_vma(mm, addr);\n\tif (!vma)\n\t\treturn NULL;\n\tif (vma->vm_start <= addr)\n\t\treturn vma;\n\tif (!(vma->vm_flags & VM_GROWSDOWN))\n\t\treturn NULL;\n\tstart = vma->vm_start;\n\tif (expand_stack(vma, addr))\n\t\treturn NULL;\n\tif (vma->vm_flags & VM_LOCKED)\n\t\tpopulate_vma_page_range(vma, addr, start, NULL);\n\treturn vma;\n}\n#endif",
"EXPORT_SYMBOL_GPL(find_extend_vma);",
"/*\n * Ok - we have the memory areas we should free on the vma list,\n * so release them, and do the vma updates.\n *\n * Called with the mm semaphore held.\n */\nstatic void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)\n{\n\tunsigned long nr_accounted = 0;",
"\t/* Update high watermark before we lower total_vm */\n\tupdate_hiwater_vm(mm);\n\tdo {\n\t\tlong nrpages = vma_pages(vma);",
"\t\tif (vma->vm_flags & VM_ACCOUNT)\n\t\t\tnr_accounted += nrpages;\n\t\tvm_stat_account(mm, vma->vm_flags, -nrpages);\n\t\tvma = remove_vma(vma);\n\t} while (vma);\n\tvm_unacct_memory(nr_accounted);\n\tvalidate_mm(mm);\n}",
"/*\n * Get rid of page table information in the indicated region.\n *\n * Called with the mm semaphore held.\n */\nstatic void unmap_region(struct mm_struct *mm,\n\t\tstruct vm_area_struct *vma, struct vm_area_struct *prev,\n\t\tunsigned long start, unsigned long end)\n{\n\tstruct vm_area_struct *next = prev ? prev->vm_next : mm->mmap;\n\tstruct mmu_gather tlb;",
"\tlru_add_drain();\n\ttlb_gather_mmu(&tlb, mm, start, end);\n\tupdate_hiwater_rss(mm);\n\tunmap_vmas(&tlb, vma, start, end);\n\tfree_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,\n\t\t\t\t next ? next->vm_start : USER_PGTABLES_CEILING);\n\ttlb_finish_mmu(&tlb, start, end);\n}",
"/*\n * Create a list of vma's touched by the unmap, removing them from the mm's\n * vma list as we go..\n */\nstatic void\ndetach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,\n\tstruct vm_area_struct *prev, unsigned long end)\n{\n\tstruct vm_area_struct **insertion_point;\n\tstruct vm_area_struct *tail_vma = NULL;",
"\tinsertion_point = (prev ? &prev->vm_next : &mm->mmap);\n\tvma->vm_prev = NULL;\n\tdo {\n\t\tvma_rb_erase(vma, &mm->mm_rb);\n\t\tmm->map_count--;\n\t\ttail_vma = vma;\n\t\tvma = vma->vm_next;\n\t} while (vma && vma->vm_start < end);\n\t*insertion_point = vma;\n\tif (vma) {\n\t\tvma->vm_prev = prev;\n\t\tvma_gap_update(vma);\n\t} else\n\t\tmm->highest_vm_end = prev ? vm_end_gap(prev) : 0;\n\ttail_vma->vm_next = NULL;",
"\t/* Kill the cache */\n\tvmacache_invalidate(mm);\n}",
"/*\n * __split_vma() bypasses sysctl_max_map_count checking. We use this where it\n * has already been checked or doesn't make sense to fail.\n */\nint __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,\n\t\tunsigned long addr, int new_below)\n{\n\tstruct vm_area_struct *new;\n\tint err;",
"\tif (vma->vm_ops && vma->vm_ops->split) {\n\t\terr = vma->vm_ops->split(vma, addr);\n\t\tif (err)\n\t\t\treturn err;\n\t}",
"\tnew = vm_area_dup(vma);\n\tif (!new)\n\t\treturn -ENOMEM;",
"\tif (new_below)\n\t\tnew->vm_end = addr;\n\telse {\n\t\tnew->vm_start = addr;\n\t\tnew->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);\n\t}",
"\terr = vma_dup_policy(vma, new);\n\tif (err)\n\t\tgoto out_free_vma;",
"\terr = anon_vma_clone(new, vma);\n\tif (err)\n\t\tgoto out_free_mpol;",
"\tif (new->vm_file)\n\t\tget_file(new->vm_file);",
"\tif (new->vm_ops && new->vm_ops->open)\n\t\tnew->vm_ops->open(new);",
"\tif (new_below)\n\t\terr = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +\n\t\t\t((addr - new->vm_start) >> PAGE_SHIFT), new);\n\telse\n\t\terr = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);",
"\t/* Success. */\n\tif (!err)\n\t\treturn 0;",
"\t/* Clean everything up if vma_adjust failed. */\n\tif (new->vm_ops && new->vm_ops->close)\n\t\tnew->vm_ops->close(new);\n\tif (new->vm_file)\n\t\tfput(new->vm_file);\n\tunlink_anon_vmas(new);\n out_free_mpol:\n\tmpol_put(vma_policy(new));\n out_free_vma:\n\tvm_area_free(new);\n\treturn err;\n}",
"/*\n * Split a vma into two pieces at address 'addr', a new vma is allocated\n * either for the first part or the tail.\n */\nint split_vma(struct mm_struct *mm, struct vm_area_struct *vma,\n\t unsigned long addr, int new_below)\n{\n\tif (mm->map_count >= sysctl_max_map_count)\n\t\treturn -ENOMEM;",
"\treturn __split_vma(mm, vma, addr, new_below);\n}",
"/* Munmap is split into 2 main parts -- this part which finds\n * what needs doing, and the areas themselves, which do the\n * work. This now handles partial unmappings.\n * Jeremy Fitzhardinge <jeremy@goop.org>\n */\nint __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,\n\t\tstruct list_head *uf, bool downgrade)\n{\n\tunsigned long end;\n\tstruct vm_area_struct *vma, *prev, *last;",
"\tif ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)\n\t\treturn -EINVAL;",
"\tlen = PAGE_ALIGN(len);\n\tif (len == 0)\n\t\treturn -EINVAL;",
"\t/* Find the first overlapping VMA */\n\tvma = find_vma(mm, start);\n\tif (!vma)\n\t\treturn 0;\n\tprev = vma->vm_prev;\n\t/* we have start < vma->vm_end */",
"\t/* if it doesn't overlap, we have nothing.. */\n\tend = start + len;\n\tif (vma->vm_start >= end)\n\t\treturn 0;",
"\t/*\n\t * If we need to split any vma, do it now to save pain later.\n\t *\n\t * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially\n\t * unmapped vm_area_struct will remain in use: so lower split_vma\n\t * places tmp vma above, and higher split_vma places tmp vma below.\n\t */\n\tif (start > vma->vm_start) {\n\t\tint error;",
"\t\t/*\n\t\t * Make sure that map_count on return from munmap() will\n\t\t * not exceed its limit; but let map_count go just above\n\t\t * its limit temporarily, to help free resources as expected.\n\t\t */\n\t\tif (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)\n\t\t\treturn -ENOMEM;",
"\t\terror = __split_vma(mm, vma, start, 0);\n\t\tif (error)\n\t\t\treturn error;\n\t\tprev = vma;\n\t}",
"\t/* Does it split the last one? */\n\tlast = find_vma(mm, end);\n\tif (last && end > last->vm_start) {\n\t\tint error = __split_vma(mm, last, end, 1);\n\t\tif (error)\n\t\t\treturn error;\n\t}\n\tvma = prev ? prev->vm_next : mm->mmap;",
"\tif (unlikely(uf)) {\n\t\t/*\n\t\t * If userfaultfd_unmap_prep returns an error the vmas\n\t\t * will remain splitted, but userland will get a\n\t\t * highly unexpected error anyway. This is no\n\t\t * different than the case where the first of the two\n\t\t * __split_vma fails, but we don't undo the first\n\t\t * split, despite we could. This is unlikely enough\n\t\t * failure that it's not worth optimizing it for.\n\t\t */\n\t\tint error = userfaultfd_unmap_prep(vma, start, end, uf);\n\t\tif (error)\n\t\t\treturn error;\n\t}",
"\t/*\n\t * unlock any mlock()ed ranges before detaching vmas\n\t */\n\tif (mm->locked_vm) {\n\t\tstruct vm_area_struct *tmp = vma;\n\t\twhile (tmp && tmp->vm_start < end) {\n\t\t\tif (tmp->vm_flags & VM_LOCKED) {\n\t\t\t\tmm->locked_vm -= vma_pages(tmp);\n\t\t\t\tmunlock_vma_pages_all(tmp);\n\t\t\t}",
"\t\t\ttmp = tmp->vm_next;\n\t\t}\n\t}",
"\t/* Detach vmas from rbtree */\n\tdetach_vmas_to_be_unmapped(mm, vma, prev, end);",
"\t/*\n\t * mpx unmap needs to be called with mmap_sem held for write.\n\t * It is safe to call it before unmap_region().\n\t */\n\tarch_unmap(mm, vma, start, end);",
"\tif (downgrade)\n\t\tdowngrade_write(&mm->mmap_sem);",
"\tunmap_region(mm, vma, prev, start, end);",
"\t/* Fix up all other VM information */\n\tremove_vma_list(mm, vma);",
"\treturn downgrade ? 1 : 0;\n}",
"int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,\n\t struct list_head *uf)\n{\n\treturn __do_munmap(mm, start, len, uf, false);\n}",
"static int __vm_munmap(unsigned long start, size_t len, bool downgrade)\n{\n\tint ret;\n\tstruct mm_struct *mm = current->mm;\n\tLIST_HEAD(uf);",
"\tif (down_write_killable(&mm->mmap_sem))\n\t\treturn -EINTR;",
"\tret = __do_munmap(mm, start, len, &uf, downgrade);\n\t/*\n\t * Returning 1 indicates mmap_sem is downgraded.\n\t * But 1 is not legal return value of vm_munmap() and munmap(), reset\n\t * it to 0 before return.\n\t */\n\tif (ret == 1) {\n\t\tup_read(&mm->mmap_sem);\n\t\tret = 0;\n\t} else\n\t\tup_write(&mm->mmap_sem);",
"\tuserfaultfd_unmap_complete(mm, &uf);\n\treturn ret;\n}",
"int vm_munmap(unsigned long start, size_t len)\n{\n\treturn __vm_munmap(start, len, false);\n}\nEXPORT_SYMBOL(vm_munmap);",
"SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)\n{\n\tprofile_munmap(addr);\n\treturn __vm_munmap(addr, len, true);\n}",
"\n/*\n * Emulation of deprecated remap_file_pages() syscall.\n */\nSYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,\n\t\tunsigned long, prot, unsigned long, pgoff, unsigned long, flags)\n{",
"\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tunsigned long populate = 0;\n\tunsigned long ret = -EINVAL;\n\tstruct file *file;",
"\tpr_warn_once(\"%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/vm/remap_file_pages.rst.\\n\",\n\t\t current->comm, current->pid);",
"\tif (prot)\n\t\treturn ret;\n\tstart = start & PAGE_MASK;\n\tsize = size & PAGE_MASK;",
"\tif (start + size <= start)\n\t\treturn ret;",
"\t/* Does pgoff wrap? */\n\tif (pgoff + (size >> PAGE_SHIFT) < pgoff)\n\t\treturn ret;",
"\tif (down_write_killable(&mm->mmap_sem))\n\t\treturn -EINTR;",
"\tvma = find_vma(mm, start);",
"\tif (!vma || !(vma->vm_flags & VM_SHARED))\n\t\tgoto out;",
"\tif (start < vma->vm_start)\n\t\tgoto out;",
"\tif (start + size > vma->vm_end) {\n\t\tstruct vm_area_struct *next;",
"\t\tfor (next = vma->vm_next; next; next = next->vm_next) {\n\t\t\t/* hole between vmas ? */\n\t\t\tif (next->vm_start != next->vm_prev->vm_end)\n\t\t\t\tgoto out;",
"\t\t\tif (next->vm_file != vma->vm_file)\n\t\t\t\tgoto out;",
"\t\t\tif (next->vm_flags != vma->vm_flags)\n\t\t\t\tgoto out;",
"\t\t\tif (start + size <= next->vm_end)\n\t\t\t\tbreak;\n\t\t}",
"\t\tif (!next)\n\t\t\tgoto out;\n\t}",
"\tprot |= vma->vm_flags & VM_READ ? PROT_READ : 0;\n\tprot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;\n\tprot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;",
"\tflags &= MAP_NONBLOCK;\n\tflags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;\n\tif (vma->vm_flags & VM_LOCKED) {\n\t\tstruct vm_area_struct *tmp;\n\t\tflags |= MAP_LOCKED;",
"\t\t/* drop PG_Mlocked flag for over-mapped range */\n\t\tfor (tmp = vma; tmp->vm_start >= start + size;\n\t\t\t\ttmp = tmp->vm_next) {\n\t\t\t/*\n\t\t\t * Split pmd and munlock page on the border\n\t\t\t * of the range.\n\t\t\t */\n\t\t\tvma_adjust_trans_huge(tmp, start, start + size, 0);",
"\t\t\tmunlock_vma_pages_range(tmp,\n\t\t\t\t\tmax(tmp->vm_start, start),\n\t\t\t\t\tmin(tmp->vm_end, start + size));\n\t\t}\n\t}",
"\tfile = get_file(vma->vm_file);\n\tret = do_mmap_pgoff(vma->vm_file, start, size,\n\t\t\tprot, flags, pgoff, &populate, NULL);\n\tfput(file);\nout:\n\tup_write(&mm->mmap_sem);\n\tif (populate)\n\t\tmm_populate(ret, populate);\n\tif (!IS_ERR_VALUE(ret))\n\t\tret = 0;\n\treturn ret;\n}",
"/*\n * this is really a simplified \"do_mmap\". it only handles\n * anonymous maps. eventually we may be able to do some\n * brk-specific accounting here.\n */\nstatic int do_brk_flags(unsigned long addr, unsigned long len, unsigned long flags, struct list_head *uf)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma, *prev;\n\tstruct rb_node **rb_link, *rb_parent;\n\tpgoff_t pgoff = addr >> PAGE_SHIFT;\n\tint error;",
"\t/* Until we need other flags, refuse anything except VM_EXEC. */\n\tif ((flags & (~VM_EXEC)) != 0)\n\t\treturn -EINVAL;\n\tflags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;",
"\terror = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);\n\tif (offset_in_page(error))\n\t\treturn error;",
"\terror = mlock_future_check(mm, mm->def_flags, len);\n\tif (error)\n\t\treturn error;",
"\t/*\n\t * Clear old maps. this also does some error checking for us\n\t */\n\twhile (find_vma_links(mm, addr, addr + len, &prev, &rb_link,\n\t\t\t &rb_parent)) {\n\t\tif (do_munmap(mm, addr, len, uf))\n\t\t\treturn -ENOMEM;\n\t}",
"\t/* Check against address space limits *after* clearing old maps... */\n\tif (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))\n\t\treturn -ENOMEM;",
"\tif (mm->map_count > sysctl_max_map_count)\n\t\treturn -ENOMEM;",
"\tif (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))\n\t\treturn -ENOMEM;",
"\t/* Can we just expand an old private anonymous mapping? */\n\tvma = vma_merge(mm, prev, addr, addr + len, flags,\n\t\t\tNULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX);\n\tif (vma)\n\t\tgoto out;",
"\t/*\n\t * create a vma struct for an anonymous mapping\n\t */\n\tvma = vm_area_alloc(mm);\n\tif (!vma) {\n\t\tvm_unacct_memory(len >> PAGE_SHIFT);\n\t\treturn -ENOMEM;\n\t}",
"\tvma_set_anonymous(vma);\n\tvma->vm_start = addr;\n\tvma->vm_end = addr + len;\n\tvma->vm_pgoff = pgoff;\n\tvma->vm_flags = flags;\n\tvma->vm_page_prot = vm_get_page_prot(flags);\n\tvma_link(mm, vma, prev, rb_link, rb_parent);\nout:\n\tperf_event_mmap(vma);\n\tmm->total_vm += len >> PAGE_SHIFT;\n\tmm->data_vm += len >> PAGE_SHIFT;\n\tif (flags & VM_LOCKED)\n\t\tmm->locked_vm += (len >> PAGE_SHIFT);\n\tvma->vm_flags |= VM_SOFTDIRTY;\n\treturn 0;\n}",
"int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)\n{\n\tstruct mm_struct *mm = current->mm;\n\tunsigned long len;\n\tint ret;\n\tbool populate;\n\tLIST_HEAD(uf);",
"\tlen = PAGE_ALIGN(request);\n\tif (len < request)\n\t\treturn -ENOMEM;\n\tif (!len)\n\t\treturn 0;",
"\tif (down_write_killable(&mm->mmap_sem))\n\t\treturn -EINTR;",
"\tret = do_brk_flags(addr, len, flags, &uf);\n\tpopulate = ((mm->def_flags & VM_LOCKED) != 0);\n\tup_write(&mm->mmap_sem);\n\tuserfaultfd_unmap_complete(mm, &uf);\n\tif (populate && !ret)\n\t\tmm_populate(addr, len);\n\treturn ret;\n}\nEXPORT_SYMBOL(vm_brk_flags);",
"int vm_brk(unsigned long addr, unsigned long len)\n{\n\treturn vm_brk_flags(addr, len, 0);\n}\nEXPORT_SYMBOL(vm_brk);",
"/* Release all mmaps. */\nvoid exit_mmap(struct mm_struct *mm)\n{\n\tstruct mmu_gather tlb;\n\tstruct vm_area_struct *vma;\n\tunsigned long nr_accounted = 0;",
"\t/* mm's last user has gone, and its about to be pulled down */\n\tmmu_notifier_release(mm);",
"\tif (unlikely(mm_is_oom_victim(mm))) {\n\t\t/*\n\t\t * Manually reap the mm to free as much memory as possible.\n\t\t * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard\n\t\t * this mm from further consideration. Taking mm->mmap_sem for\n\t\t * write after setting MMF_OOM_SKIP will guarantee that the oom\n\t\t * reaper will not run on this mm again after mmap_sem is\n\t\t * dropped.\n\t\t *\n\t\t * Nothing can be holding mm->mmap_sem here and the above call\n\t\t * to mmu_notifier_release(mm) ensures mmu notifier callbacks in\n\t\t * __oom_reap_task_mm() will not block.\n\t\t *\n\t\t * This needs to be done before calling munlock_vma_pages_all(),\n\t\t * which clears VM_LOCKED, otherwise the oom reaper cannot\n\t\t * reliably test it.\n\t\t */\n\t\t(void)__oom_reap_task_mm(mm);",
"\t\tset_bit(MMF_OOM_SKIP, &mm->flags);\n\t\tdown_write(&mm->mmap_sem);\n\t\tup_write(&mm->mmap_sem);\n\t}",
"\tif (mm->locked_vm) {\n\t\tvma = mm->mmap;\n\t\twhile (vma) {\n\t\t\tif (vma->vm_flags & VM_LOCKED)\n\t\t\t\tmunlock_vma_pages_all(vma);\n\t\t\tvma = vma->vm_next;\n\t\t}\n\t}",
"\tarch_exit_mmap(mm);",
"\tvma = mm->mmap;\n\tif (!vma)\t/* Can happen if dup_mmap() received an OOM */\n\t\treturn;",
"\tlru_add_drain();\n\tflush_cache_mm(mm);\n\ttlb_gather_mmu(&tlb, mm, 0, -1);\n\t/* update_hiwater_rss(mm) here? but nobody should be looking */\n\t/* Use -1 here to ensure all VMAs in the mm are unmapped */\n\tunmap_vmas(&tlb, vma, 0, -1);\n\tfree_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);\n\ttlb_finish_mmu(&tlb, 0, -1);",
"\t/*\n\t * Walk the list again, actually closing and freeing it,\n\t * with preemption enabled, without holding any MM locks.\n\t */\n\twhile (vma) {\n\t\tif (vma->vm_flags & VM_ACCOUNT)\n\t\t\tnr_accounted += vma_pages(vma);\n\t\tvma = remove_vma(vma);\n\t}\n\tvm_unacct_memory(nr_accounted);\n}",
"/* Insert vm structure into process list sorted by address\n * and into the inode's i_mmap tree. If vm_file is non-NULL\n * then i_mmap_rwsem is taken here.\n */\nint insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)\n{\n\tstruct vm_area_struct *prev;\n\tstruct rb_node **rb_link, *rb_parent;",
"\tif (find_vma_links(mm, vma->vm_start, vma->vm_end,\n\t\t\t &prev, &rb_link, &rb_parent))\n\t\treturn -ENOMEM;\n\tif ((vma->vm_flags & VM_ACCOUNT) &&\n\t security_vm_enough_memory_mm(mm, vma_pages(vma)))\n\t\treturn -ENOMEM;",
"\t/*\n\t * The vm_pgoff of a purely anonymous vma should be irrelevant\n\t * until its first write fault, when page's anon_vma and index\n\t * are set. But now set the vm_pgoff it will almost certainly\n\t * end up with (unless mremap moves it elsewhere before that\n\t * first wfault), so /proc/pid/maps tells a consistent story.\n\t *\n\t * By setting it to reflect the virtual start address of the\n\t * vma, merges and splits can happen in a seamless way, just\n\t * using the existing file pgoff checks and manipulations.\n\t * Similarly in do_mmap_pgoff and in do_brk.\n\t */\n\tif (vma_is_anonymous(vma)) {\n\t\tBUG_ON(vma->anon_vma);\n\t\tvma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;\n\t}",
"\tvma_link(mm, vma, prev, rb_link, rb_parent);\n\treturn 0;\n}",
"/*\n * Copy the vma structure to a new location in the same mm,\n * prior to moving page table entries, to effect an mremap move.\n */\nstruct vm_area_struct *copy_vma(struct vm_area_struct **vmap,\n\tunsigned long addr, unsigned long len, pgoff_t pgoff,\n\tbool *need_rmap_locks)\n{\n\tstruct vm_area_struct *vma = *vmap;\n\tunsigned long vma_start = vma->vm_start;\n\tstruct mm_struct *mm = vma->vm_mm;\n\tstruct vm_area_struct *new_vma, *prev;\n\tstruct rb_node **rb_link, *rb_parent;\n\tbool faulted_in_anon_vma = true;",
"\t/*\n\t * If anonymous vma has not yet been faulted, update new pgoff\n\t * to match new location, to increase its chance of merging.\n\t */\n\tif (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {\n\t\tpgoff = addr >> PAGE_SHIFT;\n\t\tfaulted_in_anon_vma = false;\n\t}",
"\tif (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))\n\t\treturn NULL;\t/* should never get here */\n\tnew_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,\n\t\t\t vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),\n\t\t\t vma->vm_userfaultfd_ctx);\n\tif (new_vma) {\n\t\t/*\n\t\t * Source vma may have been merged into new_vma\n\t\t */\n\t\tif (unlikely(vma_start >= new_vma->vm_start &&\n\t\t\t vma_start < new_vma->vm_end)) {\n\t\t\t/*\n\t\t\t * The only way we can get a vma_merge with\n\t\t\t * self during an mremap is if the vma hasn't\n\t\t\t * been faulted in yet and we were allowed to\n\t\t\t * reset the dst vma->vm_pgoff to the\n\t\t\t * destination address of the mremap to allow\n\t\t\t * the merge to happen. mremap must change the\n\t\t\t * vm_pgoff linearity between src and dst vmas\n\t\t\t * (in turn preventing a vma_merge) to be\n\t\t\t * safe. It is only safe to keep the vm_pgoff\n\t\t\t * linear if there are no pages mapped yet.\n\t\t\t */\n\t\t\tVM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);\n\t\t\t*vmap = vma = new_vma;\n\t\t}\n\t\t*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);\n\t} else {\n\t\tnew_vma = vm_area_dup(vma);\n\t\tif (!new_vma)\n\t\t\tgoto out;\n\t\tnew_vma->vm_start = addr;\n\t\tnew_vma->vm_end = addr + len;\n\t\tnew_vma->vm_pgoff = pgoff;\n\t\tif (vma_dup_policy(vma, new_vma))\n\t\t\tgoto out_free_vma;\n\t\tif (anon_vma_clone(new_vma, vma))\n\t\t\tgoto out_free_mempol;\n\t\tif (new_vma->vm_file)\n\t\t\tget_file(new_vma->vm_file);\n\t\tif (new_vma->vm_ops && new_vma->vm_ops->open)\n\t\t\tnew_vma->vm_ops->open(new_vma);\n\t\tvma_link(mm, new_vma, prev, rb_link, rb_parent);\n\t\t*need_rmap_locks = false;\n\t}\n\treturn new_vma;",
"out_free_mempol:\n\tmpol_put(vma_policy(new_vma));\nout_free_vma:\n\tvm_area_free(new_vma);\nout:\n\treturn NULL;\n}",
"/*\n * Return true if the calling process may expand its vm space by the passed\n * number of pages\n */\nbool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)\n{\n\tif (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)\n\t\treturn false;",
"\tif (is_data_mapping(flags) &&\n\t mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {\n\t\t/* Workaround for Valgrind */\n\t\tif (rlimit(RLIMIT_DATA) == 0 &&\n\t\t mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)\n\t\t\treturn true;",
"\t\tpr_warn_once(\"%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\\n\",\n\t\t\t current->comm, current->pid,\n\t\t\t (mm->data_vm + npages) << PAGE_SHIFT,\n\t\t\t rlimit(RLIMIT_DATA),\n\t\t\t ignore_rlimit_data ? \"\" : \" or use boot option ignore_rlimit_data\");",
"\t\tif (!ignore_rlimit_data)\n\t\t\treturn false;\n\t}",
"\treturn true;\n}",
"void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)\n{\n\tmm->total_vm += npages;",
"\tif (is_exec_mapping(flags))\n\t\tmm->exec_vm += npages;\n\telse if (is_stack_mapping(flags))\n\t\tmm->stack_vm += npages;\n\telse if (is_data_mapping(flags))\n\t\tmm->data_vm += npages;\n}",
"static vm_fault_t special_mapping_fault(struct vm_fault *vmf);",
"/*\n * Having a close hook prevents vma merging regardless of flags.\n */\nstatic void special_mapping_close(struct vm_area_struct *vma)\n{\n}",
"static const char *special_mapping_name(struct vm_area_struct *vma)\n{\n\treturn ((struct vm_special_mapping *)vma->vm_private_data)->name;\n}",
"static int special_mapping_mremap(struct vm_area_struct *new_vma)\n{\n\tstruct vm_special_mapping *sm = new_vma->vm_private_data;",
"\tif (WARN_ON_ONCE(current->mm != new_vma->vm_mm))\n\t\treturn -EFAULT;",
"\tif (sm->mremap)\n\t\treturn sm->mremap(sm, new_vma);",
"\treturn 0;\n}",
"static const struct vm_operations_struct special_mapping_vmops = {\n\t.close = special_mapping_close,\n\t.fault = special_mapping_fault,\n\t.mremap = special_mapping_mremap,\n\t.name = special_mapping_name,\n};",
"static const struct vm_operations_struct legacy_special_mapping_vmops = {\n\t.close = special_mapping_close,\n\t.fault = special_mapping_fault,\n};",
"static vm_fault_t special_mapping_fault(struct vm_fault *vmf)\n{\n\tstruct vm_area_struct *vma = vmf->vma;\n\tpgoff_t pgoff;\n\tstruct page **pages;",
"\tif (vma->vm_ops == &legacy_special_mapping_vmops) {\n\t\tpages = vma->vm_private_data;\n\t} else {\n\t\tstruct vm_special_mapping *sm = vma->vm_private_data;",
"\t\tif (sm->fault)\n\t\t\treturn sm->fault(sm, vmf->vma, vmf);",
"\t\tpages = sm->pages;\n\t}",
"\tfor (pgoff = vmf->pgoff; pgoff && *pages; ++pages)\n\t\tpgoff--;",
"\tif (*pages) {\n\t\tstruct page *page = *pages;\n\t\tget_page(page);\n\t\tvmf->page = page;\n\t\treturn 0;\n\t}",
"\treturn VM_FAULT_SIGBUS;\n}",
"static struct vm_area_struct *__install_special_mapping(\n\tstruct mm_struct *mm,\n\tunsigned long addr, unsigned long len,\n\tunsigned long vm_flags, void *priv,\n\tconst struct vm_operations_struct *ops)\n{\n\tint ret;\n\tstruct vm_area_struct *vma;",
"\tvma = vm_area_alloc(mm);\n\tif (unlikely(vma == NULL))\n\t\treturn ERR_PTR(-ENOMEM);",
"\tvma->vm_start = addr;\n\tvma->vm_end = addr + len;",
"\tvma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;\n\tvma->vm_page_prot = vm_get_page_prot(vma->vm_flags);",
"\tvma->vm_ops = ops;\n\tvma->vm_private_data = priv;",
"\tret = insert_vm_struct(mm, vma);\n\tif (ret)\n\t\tgoto out;",
"\tvm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);",
"\tperf_event_mmap(vma);",
"\treturn vma;",
"out:\n\tvm_area_free(vma);\n\treturn ERR_PTR(ret);\n}",
"bool vma_is_special_mapping(const struct vm_area_struct *vma,\n\tconst struct vm_special_mapping *sm)\n{\n\treturn vma->vm_private_data == sm &&\n\t\t(vma->vm_ops == &special_mapping_vmops ||\n\t\t vma->vm_ops == &legacy_special_mapping_vmops);\n}",
"/*\n * Called with mm->mmap_sem held for writing.\n * Insert a new vma covering the given region, with the given flags.\n * Its pages are supplied by the given array of struct page *.\n * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.\n * The region past the last page supplied will always produce SIGBUS.\n * The array pointer and the pages it points to are assumed to stay alive\n * for as long as this mapping might exist.\n */\nstruct vm_area_struct *_install_special_mapping(\n\tstruct mm_struct *mm,\n\tunsigned long addr, unsigned long len,\n\tunsigned long vm_flags, const struct vm_special_mapping *spec)\n{\n\treturn __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,\n\t\t\t\t\t&special_mapping_vmops);\n}",
"int install_special_mapping(struct mm_struct *mm,\n\t\t\t unsigned long addr, unsigned long len,\n\t\t\t unsigned long vm_flags, struct page **pages)\n{\n\tstruct vm_area_struct *vma = __install_special_mapping(\n\t\tmm, addr, len, vm_flags, (void *)pages,\n\t\t&legacy_special_mapping_vmops);",
"\treturn PTR_ERR_OR_ZERO(vma);\n}",
"static DEFINE_MUTEX(mm_all_locks_mutex);",
"static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)\n{\n\tif (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {\n\t\t/*\n\t\t * The LSB of head.next can't change from under us\n\t\t * because we hold the mm_all_locks_mutex.\n\t\t */\n\t\tdown_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_sem);\n\t\t/*\n\t\t * We can safely modify head.next after taking the\n\t\t * anon_vma->root->rwsem. If some other vma in this mm shares\n\t\t * the same anon_vma we won't take it again.\n\t\t *\n\t\t * No need of atomic instructions here, head.next\n\t\t * can't change from under us thanks to the\n\t\t * anon_vma->root->rwsem.\n\t\t */\n\t\tif (__test_and_set_bit(0, (unsigned long *)\n\t\t\t\t &anon_vma->root->rb_root.rb_root.rb_node))\n\t\t\tBUG();\n\t}\n}",
"static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)\n{\n\tif (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {\n\t\t/*\n\t\t * AS_MM_ALL_LOCKS can't change from under us because\n\t\t * we hold the mm_all_locks_mutex.\n\t\t *\n\t\t * Operations on ->flags have to be atomic because\n\t\t * even if AS_MM_ALL_LOCKS is stable thanks to the\n\t\t * mm_all_locks_mutex, there may be other cpus\n\t\t * changing other bitflags in parallel to us.\n\t\t */\n\t\tif (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))\n\t\t\tBUG();\n\t\tdown_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_sem);\n\t}\n}",
"/*\n * This operation locks against the VM for all pte/vma/mm related\n * operations that could ever happen on a certain mm. This includes\n * vmtruncate, try_to_unmap, and all page faults.\n *\n * The caller must take the mmap_sem in write mode before calling\n * mm_take_all_locks(). The caller isn't allowed to release the\n * mmap_sem until mm_drop_all_locks() returns.\n *\n * mmap_sem in write mode is required in order to block all operations\n * that could modify pagetables and free pages without need of\n * altering the vma layout. It's also needed in write mode to avoid new\n * anon_vmas to be associated with existing vmas.\n *\n * A single task can't take more than one mm_take_all_locks() in a row\n * or it would deadlock.\n *\n * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in\n * mapping->flags avoid to take the same lock twice, if more than one\n * vma in this mm is backed by the same anon_vma or address_space.\n *\n * We take locks in following order, accordingly to comment at beginning\n * of mm/rmap.c:\n * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for\n * hugetlb mapping);\n * - all i_mmap_rwsem locks;\n * - all anon_vma->rwseml\n *\n * We can take all locks within these types randomly because the VM code\n * doesn't nest them and we protected from parallel mm_take_all_locks() by\n * mm_all_locks_mutex.\n *\n * mm_take_all_locks() and mm_drop_all_locks are expensive operations\n * that may have to take thousand of locks.\n *\n * mm_take_all_locks() can fail if it's interrupted by signals.\n */\nint mm_take_all_locks(struct mm_struct *mm)\n{\n\tstruct vm_area_struct *vma;\n\tstruct anon_vma_chain *avc;",
"\tBUG_ON(down_read_trylock(&mm->mmap_sem));",
"\tmutex_lock(&mm_all_locks_mutex);",
"\tfor (vma = mm->mmap; vma; vma = vma->vm_next) {\n\t\tif (signal_pending(current))\n\t\t\tgoto out_unlock;\n\t\tif (vma->vm_file && vma->vm_file->f_mapping &&\n\t\t\t\tis_vm_hugetlb_page(vma))\n\t\t\tvm_lock_mapping(mm, vma->vm_file->f_mapping);\n\t}",
"\tfor (vma = mm->mmap; vma; vma = vma->vm_next) {\n\t\tif (signal_pending(current))\n\t\t\tgoto out_unlock;\n\t\tif (vma->vm_file && vma->vm_file->f_mapping &&\n\t\t\t\t!is_vm_hugetlb_page(vma))\n\t\t\tvm_lock_mapping(mm, vma->vm_file->f_mapping);\n\t}",
"\tfor (vma = mm->mmap; vma; vma = vma->vm_next) {\n\t\tif (signal_pending(current))\n\t\t\tgoto out_unlock;\n\t\tif (vma->anon_vma)\n\t\t\tlist_for_each_entry(avc, &vma->anon_vma_chain, same_vma)\n\t\t\t\tvm_lock_anon_vma(mm, avc->anon_vma);\n\t}",
"\treturn 0;",
"out_unlock:\n\tmm_drop_all_locks(mm);\n\treturn -EINTR;\n}",
"static void vm_unlock_anon_vma(struct anon_vma *anon_vma)\n{\n\tif (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {\n\t\t/*\n\t\t * The LSB of head.next can't change to 0 from under\n\t\t * us because we hold the mm_all_locks_mutex.\n\t\t *\n\t\t * We must however clear the bitflag before unlocking\n\t\t * the vma so the users using the anon_vma->rb_root will\n\t\t * never see our bitflag.\n\t\t *\n\t\t * No need of atomic instructions here, head.next\n\t\t * can't change from under us until we release the\n\t\t * anon_vma->root->rwsem.\n\t\t */\n\t\tif (!__test_and_clear_bit(0, (unsigned long *)\n\t\t\t\t\t &anon_vma->root->rb_root.rb_root.rb_node))\n\t\t\tBUG();\n\t\tanon_vma_unlock_write(anon_vma);\n\t}\n}",
"static void vm_unlock_mapping(struct address_space *mapping)\n{\n\tif (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {\n\t\t/*\n\t\t * AS_MM_ALL_LOCKS can't change to 0 from under us\n\t\t * because we hold the mm_all_locks_mutex.\n\t\t */\n\t\ti_mmap_unlock_write(mapping);\n\t\tif (!test_and_clear_bit(AS_MM_ALL_LOCKS,\n\t\t\t\t\t&mapping->flags))\n\t\t\tBUG();\n\t}\n}",
"/*\n * The mmap_sem cannot be released by the caller until\n * mm_drop_all_locks() returns.\n */\nvoid mm_drop_all_locks(struct mm_struct *mm)\n{\n\tstruct vm_area_struct *vma;\n\tstruct anon_vma_chain *avc;",
"\tBUG_ON(down_read_trylock(&mm->mmap_sem));\n\tBUG_ON(!mutex_is_locked(&mm_all_locks_mutex));",
"\tfor (vma = mm->mmap; vma; vma = vma->vm_next) {\n\t\tif (vma->anon_vma)\n\t\t\tlist_for_each_entry(avc, &vma->anon_vma_chain, same_vma)\n\t\t\t\tvm_unlock_anon_vma(avc->anon_vma);\n\t\tif (vma->vm_file && vma->vm_file->f_mapping)\n\t\t\tvm_unlock_mapping(vma->vm_file->f_mapping);\n\t}",
"\tmutex_unlock(&mm_all_locks_mutex);\n}",
"/*\n * initialise the percpu counter for VM\n */\nvoid __init mmap_init(void)\n{\n\tint ret;",
"\tret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);\n\tVM_BUG_ON(ret);\n}",
"/*\n * Initialise sysctl_user_reserve_kbytes.\n *\n * This is intended to prevent a user from starting a single memory hogging\n * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER\n * mode.\n *\n * The default value is min(3% of free memory, 128MB)\n * 128MB is enough to recover with sshd/login, bash, and top/kill.\n */\nstatic int init_user_reserve(void)\n{\n\tunsigned long free_kbytes;",
"\tfree_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);",
"\tsysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);\n\treturn 0;\n}\nsubsys_initcall(init_user_reserve);",
"/*\n * Initialise sysctl_admin_reserve_kbytes.\n *\n * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin\n * to log in and kill a memory hogging process.\n *\n * Systems with more than 256MB will reserve 8MB, enough to recover\n * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will\n * only reserve 3% of free pages by default.\n */\nstatic int init_admin_reserve(void)\n{\n\tunsigned long free_kbytes;",
"\tfree_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);",
"\tsysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);\n\treturn 0;\n}\nsubsys_initcall(init_admin_reserve);",
"/*\n * Reinititalise user and admin reserves if memory is added or removed.\n *\n * The default user reserve max is 128MB, and the default max for the\n * admin reserve is 8MB. These are usually, but not always, enough to\n * enable recovery from a memory hogging process using login/sshd, a shell,\n * and tools like top. It may make sense to increase or even disable the\n * reserve depending on the existence of swap or variations in the recovery\n * tools. So, the admin may have changed them.\n *\n * If memory is added and the reserves have been eliminated or increased above\n * the default max, then we'll trust the admin.\n *\n * If memory is removed and there isn't enough free memory, then we\n * need to reset the reserves.\n *\n * Otherwise keep the reserve set by the admin.\n */\nstatic int reserve_mem_notifier(struct notifier_block *nb,\n\t\t\t unsigned long action, void *data)\n{\n\tunsigned long tmp, free_kbytes;",
"\tswitch (action) {\n\tcase MEM_ONLINE:\n\t\t/* Default max is 128MB. Leave alone if modified by operator. */\n\t\ttmp = sysctl_user_reserve_kbytes;\n\t\tif (0 < tmp && tmp < (1UL << 17))\n\t\t\tinit_user_reserve();",
"\t\t/* Default max is 8MB. Leave alone if modified by operator. */\n\t\ttmp = sysctl_admin_reserve_kbytes;\n\t\tif (0 < tmp && tmp < (1UL << 13))\n\t\t\tinit_admin_reserve();",
"\t\tbreak;\n\tcase MEM_OFFLINE:\n\t\tfree_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);",
"\t\tif (sysctl_user_reserve_kbytes > free_kbytes) {\n\t\t\tinit_user_reserve();\n\t\t\tpr_info(\"vm.user_reserve_kbytes reset to %lu\\n\",\n\t\t\t\tsysctl_user_reserve_kbytes);\n\t\t}",
"\t\tif (sysctl_admin_reserve_kbytes > free_kbytes) {\n\t\t\tinit_admin_reserve();\n\t\t\tpr_info(\"vm.admin_reserve_kbytes reset to %lu\\n\",\n\t\t\t\tsysctl_admin_reserve_kbytes);\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\treturn NOTIFY_OK;\n}",
"static struct notifier_block reserve_mem_nb = {\n\t.notifier_call = reserve_mem_notifier,\n};",
"static int __meminit init_reserve_notifier(void)\n{\n\tif (register_hotmemory_notifier(&reserve_mem_nb))\n\t\tpr_err(\"Failed registering memory add/remove notifier for admin reserve\\n\");",
"\treturn 0;\n}\nsubsys_initcall(init_reserve_notifier);"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [2435], "buggy_code_start_loc": [2429], "filenames": ["mm/mmap.c"], "fixing_code_end_loc": [2434], "fixing_code_start_loc": [2429], "message": "In the Linux kernel before 4.20.14, expand_downwards in mm/mmap.c lacks a check for the mmap minimum address, which makes it easier for attackers to exploit kernel NULL pointer dereferences on non-SMAP platforms. This is related to a capability check for the wrong task.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "56A636A0-542A-457B-8557-CD70D9AD69C1", "versionEndExcluding": "4.9.162", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.9", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "6DC55135-E4DB-45B8-BF67-5139F750BF40", "versionEndExcluding": "4.14.105", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.14", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "03F65CBE-42FC-4C64-8189-9D1AA25C01A5", "versionEndExcluding": "4.19.27", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.19", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "816E4DD2-A3B9-47AD-AFD4-79A03297934E", "versionEndExcluding": "4.20.14", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.20", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:redhat:enterprise_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "142AD0DD-4CF3-4D74-9442-459CE3347E3A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "F4CFF558-3C47-480D-A2F0-BABF26042943", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "F1E78106-58E6-4D59-990F-75DA575BFAD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:leap:42.3:*:*:*:*:*:*:*", "matchCriteriaId": "5F65DAB0-3DAD-49FF-BC73-3581CC3D5BF3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:*:*:*:*", "matchCriteriaId": "1F3EFED2-F6BC-46D9-AB22-D5ED87EF4549", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:esm:*:*:*", "matchCriteriaId": "7A5301BF-1402-4BE0-A0F8-69FBE79BC6D6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.10:*:*:*:*:*:*:*", "matchCriteriaId": "07C312A0-CD2C-4B9C-B064-6409B25C278F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In the Linux kernel before 4.20.14, expand_downwards in mm/mmap.c lacks a check for the mmap minimum address, which makes it easier for attackers to exploit kernel NULL pointer dereferences on non-SMAP platforms. This is related to a capability check for the wrong task."}, {"lang": "es", "value": "En el kernel de Linux, en versiones anteriores a la 4.20.14, expand_downwards en mm/mmap.c carece de una comprobaci\u00f3n para la direcci\u00f3n m\u00ednima de mmap, lo que facilita que los atacantes exploten desreferencias de puntero NULL en el kernel en plataformas que no son SMAP. Esto esto est\u00e1 relacionado con una comprobaci\u00f3n de capacidades para la tarea equivocada."}], "evaluatorComment": null, "id": "CVE-2019-9213", "lastModified": "2022-10-12T15:56:12.443", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.9, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-03-05T22:29:00.240", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=0a1d52994d440e21def1c2174932410b4f2a98a1"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-03/msg00045.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-04/msg00052.html"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "http://packetstormsecurity.com/files/156053/Reliable-Datagram-Sockets-RDS-rds_atomic_free_op-Privilege-Escalation.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:0831"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1479"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1480"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Mailing List", "Third Party Advisory"], "url": "https://bugs.chromium.org/p/project-zero/issues/detail?id=1792"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.14.105"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.19.27"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.20.14"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.9.162"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://github.com/torvalds/linux/commit/0a1d52994d440e21def1c2174932410b4f2a98a1"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/03/msg00034.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/04/msg00004.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/05/msg00002.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3930-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3930-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3931-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3931-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3932-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3932-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3933-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3933-2/"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "https://www.exploit-db.com/exploits/46502/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/0a1d52994d440e21def1c2174932410b4f2a98a1"}, "type": "CWE-476"}
| 252
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * mm/mmap.c\n *\n * Written by obz.\n *\n * Address space accounting code\t<alan@lxorguk.ukuu.org.uk>\n */",
"#define pr_fmt(fmt) KBUILD_MODNAME \": \" fmt",
"#include <linux/kernel.h>\n#include <linux/slab.h>\n#include <linux/backing-dev.h>\n#include <linux/mm.h>\n#include <linux/vmacache.h>\n#include <linux/shm.h>\n#include <linux/mman.h>\n#include <linux/pagemap.h>\n#include <linux/swap.h>\n#include <linux/syscalls.h>\n#include <linux/capability.h>\n#include <linux/init.h>\n#include <linux/file.h>\n#include <linux/fs.h>\n#include <linux/personality.h>\n#include <linux/security.h>\n#include <linux/hugetlb.h>\n#include <linux/shmem_fs.h>\n#include <linux/profile.h>\n#include <linux/export.h>\n#include <linux/mount.h>\n#include <linux/mempolicy.h>\n#include <linux/rmap.h>\n#include <linux/mmu_notifier.h>\n#include <linux/mmdebug.h>\n#include <linux/perf_event.h>\n#include <linux/audit.h>\n#include <linux/khugepaged.h>\n#include <linux/uprobes.h>\n#include <linux/rbtree_augmented.h>\n#include <linux/notifier.h>\n#include <linux/memory.h>\n#include <linux/printk.h>\n#include <linux/userfaultfd_k.h>\n#include <linux/moduleparam.h>\n#include <linux/pkeys.h>\n#include <linux/oom.h>",
"#include <linux/uaccess.h>\n#include <asm/cacheflush.h>\n#include <asm/tlb.h>\n#include <asm/mmu_context.h>",
"#include \"internal.h\"",
"#ifndef arch_mmap_check\n#define arch_mmap_check(addr, len, flags)\t(0)\n#endif",
"#ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS\nconst int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;\nconst int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;\nint mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;\n#endif\n#ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS\nconst int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;\nconst int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;\nint mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;\n#endif",
"static bool ignore_rlimit_data;\ncore_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);",
"static void unmap_region(struct mm_struct *mm,\n\t\tstruct vm_area_struct *vma, struct vm_area_struct *prev,\n\t\tunsigned long start, unsigned long end);",
"/* description of effects of mapping type and prot in current implementation.\n * this is due to the limited x86 page protection hardware. The expected\n * behavior is in parens:\n *\n * map_type\tprot\n *\t\tPROT_NONE\tPROT_READ\tPROT_WRITE\tPROT_EXEC\n * MAP_SHARED\tr: (no) no\tr: (yes) yes\tr: (no) yes\tr: (no) yes\n *\t\tw: (no) no\tw: (no) no\tw: (yes) yes\tw: (no) no\n *\t\tx: (no) no\tx: (no) yes\tx: (no) yes\tx: (yes) yes\n *\n * MAP_PRIVATE\tr: (no) no\tr: (yes) yes\tr: (no) yes\tr: (no) yes\n *\t\tw: (no) no\tw: (no) no\tw: (copy) copy\tw: (no) no\n *\t\tx: (no) no\tx: (no) yes\tx: (no) yes\tx: (yes) yes\n *\n * On arm64, PROT_EXEC has the following behaviour for both MAP_SHARED and\n * MAP_PRIVATE:\n *\t\t\t\t\t\t\t\tr: (no) no\n *\t\t\t\t\t\t\t\tw: (no) no\n *\t\t\t\t\t\t\t\tx: (yes) yes\n */\npgprot_t protection_map[16] __ro_after_init = {\n\t__P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,\n\t__S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111\n};",
"#ifndef CONFIG_ARCH_HAS_FILTER_PGPROT\nstatic inline pgprot_t arch_filter_pgprot(pgprot_t prot)\n{\n\treturn prot;\n}\n#endif",
"pgprot_t vm_get_page_prot(unsigned long vm_flags)\n{\n\tpgprot_t ret = __pgprot(pgprot_val(protection_map[vm_flags &\n\t\t\t\t(VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)]) |\n\t\t\tpgprot_val(arch_vm_get_page_prot(vm_flags)));",
"\treturn arch_filter_pgprot(ret);\n}\nEXPORT_SYMBOL(vm_get_page_prot);",
"static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)\n{\n\treturn pgprot_modify(oldprot, vm_get_page_prot(vm_flags));\n}",
"/* Update vma->vm_page_prot to reflect vma->vm_flags. */\nvoid vma_set_page_prot(struct vm_area_struct *vma)\n{\n\tunsigned long vm_flags = vma->vm_flags;\n\tpgprot_t vm_page_prot;",
"\tvm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);\n\tif (vma_wants_writenotify(vma, vm_page_prot)) {\n\t\tvm_flags &= ~VM_SHARED;\n\t\tvm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);\n\t}\n\t/* remove_protection_ptes reads vma->vm_page_prot without mmap_sem */\n\tWRITE_ONCE(vma->vm_page_prot, vm_page_prot);\n}",
"/*\n * Requires inode->i_mapping->i_mmap_rwsem\n */\nstatic void __remove_shared_vm_struct(struct vm_area_struct *vma,\n\t\tstruct file *file, struct address_space *mapping)\n{\n\tif (vma->vm_flags & VM_DENYWRITE)\n\t\tatomic_inc(&file_inode(file)->i_writecount);\n\tif (vma->vm_flags & VM_SHARED)\n\t\tmapping_unmap_writable(mapping);",
"\tflush_dcache_mmap_lock(mapping);\n\tvma_interval_tree_remove(vma, &mapping->i_mmap);\n\tflush_dcache_mmap_unlock(mapping);\n}",
"/*\n * Unlink a file-based vm structure from its interval tree, to hide\n * vma from rmap and vmtruncate before freeing its page tables.\n */\nvoid unlink_file_vma(struct vm_area_struct *vma)\n{\n\tstruct file *file = vma->vm_file;",
"\tif (file) {\n\t\tstruct address_space *mapping = file->f_mapping;\n\t\ti_mmap_lock_write(mapping);\n\t\t__remove_shared_vm_struct(vma, file, mapping);\n\t\ti_mmap_unlock_write(mapping);\n\t}\n}",
"/*\n * Close a vm structure and free it, returning the next.\n */\nstatic struct vm_area_struct *remove_vma(struct vm_area_struct *vma)\n{\n\tstruct vm_area_struct *next = vma->vm_next;",
"\tmight_sleep();\n\tif (vma->vm_ops && vma->vm_ops->close)\n\t\tvma->vm_ops->close(vma);\n\tif (vma->vm_file)\n\t\tfput(vma->vm_file);\n\tmpol_put(vma_policy(vma));\n\tvm_area_free(vma);\n\treturn next;\n}",
"static int do_brk_flags(unsigned long addr, unsigned long request, unsigned long flags,\n\t\tstruct list_head *uf);\nSYSCALL_DEFINE1(brk, unsigned long, brk)\n{\n\tunsigned long retval;\n\tunsigned long newbrk, oldbrk, origbrk;\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *next;\n\tunsigned long min_brk;\n\tbool populate;\n\tbool downgraded = false;\n\tLIST_HEAD(uf);",
"\tif (down_write_killable(&mm->mmap_sem))\n\t\treturn -EINTR;",
"\torigbrk = mm->brk;",
"#ifdef CONFIG_COMPAT_BRK\n\t/*\n\t * CONFIG_COMPAT_BRK can still be overridden by setting\n\t * randomize_va_space to 2, which will still cause mm->start_brk\n\t * to be arbitrarily shifted\n\t */\n\tif (current->brk_randomized)\n\t\tmin_brk = mm->start_brk;\n\telse\n\t\tmin_brk = mm->end_data;\n#else\n\tmin_brk = mm->start_brk;\n#endif\n\tif (brk < min_brk)\n\t\tgoto out;",
"\t/*\n\t * Check against rlimit here. If this check is done later after the test\n\t * of oldbrk with newbrk then it can escape the test and let the data\n\t * segment grow beyond its set limit the in case where the limit is\n\t * not page aligned -Ram Gupta\n\t */\n\tif (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,\n\t\t\t mm->end_data, mm->start_data))\n\t\tgoto out;",
"\tnewbrk = PAGE_ALIGN(brk);\n\toldbrk = PAGE_ALIGN(mm->brk);\n\tif (oldbrk == newbrk) {\n\t\tmm->brk = brk;\n\t\tgoto success;\n\t}",
"\t/*\n\t * Always allow shrinking brk.\n\t * __do_munmap() may downgrade mmap_sem to read.\n\t */\n\tif (brk <= mm->brk) {\n\t\tint ret;",
"\t\t/*\n\t\t * mm->brk must to be protected by write mmap_sem so update it\n\t\t * before downgrading mmap_sem. When __do_munmap() fails,\n\t\t * mm->brk will be restored from origbrk.\n\t\t */\n\t\tmm->brk = brk;\n\t\tret = __do_munmap(mm, newbrk, oldbrk-newbrk, &uf, true);\n\t\tif (ret < 0) {\n\t\t\tmm->brk = origbrk;\n\t\t\tgoto out;\n\t\t} else if (ret == 1) {\n\t\t\tdowngraded = true;\n\t\t}\n\t\tgoto success;\n\t}",
"\t/* Check against existing mmap mappings. */\n\tnext = find_vma(mm, oldbrk);\n\tif (next && newbrk + PAGE_SIZE > vm_start_gap(next))\n\t\tgoto out;",
"\t/* Ok, looks good - let it rip. */\n\tif (do_brk_flags(oldbrk, newbrk-oldbrk, 0, &uf) < 0)\n\t\tgoto out;\n\tmm->brk = brk;",
"success:\n\tpopulate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;\n\tif (downgraded)\n\t\tup_read(&mm->mmap_sem);\n\telse\n\t\tup_write(&mm->mmap_sem);\n\tuserfaultfd_unmap_complete(mm, &uf);\n\tif (populate)\n\t\tmm_populate(oldbrk, newbrk - oldbrk);\n\treturn brk;",
"out:\n\tretval = origbrk;\n\tup_write(&mm->mmap_sem);\n\treturn retval;\n}",
"static long vma_compute_subtree_gap(struct vm_area_struct *vma)\n{\n\tunsigned long max, prev_end, subtree_gap;",
"\t/*\n\t * Note: in the rare case of a VM_GROWSDOWN above a VM_GROWSUP, we\n\t * allow two stack_guard_gaps between them here, and when choosing\n\t * an unmapped area; whereas when expanding we only require one.\n\t * That's a little inconsistent, but keeps the code here simpler.\n\t */\n\tmax = vm_start_gap(vma);\n\tif (vma->vm_prev) {\n\t\tprev_end = vm_end_gap(vma->vm_prev);\n\t\tif (max > prev_end)\n\t\t\tmax -= prev_end;\n\t\telse\n\t\t\tmax = 0;\n\t}\n\tif (vma->vm_rb.rb_left) {\n\t\tsubtree_gap = rb_entry(vma->vm_rb.rb_left,\n\t\t\t\tstruct vm_area_struct, vm_rb)->rb_subtree_gap;\n\t\tif (subtree_gap > max)\n\t\t\tmax = subtree_gap;\n\t}\n\tif (vma->vm_rb.rb_right) {\n\t\tsubtree_gap = rb_entry(vma->vm_rb.rb_right,\n\t\t\t\tstruct vm_area_struct, vm_rb)->rb_subtree_gap;\n\t\tif (subtree_gap > max)\n\t\t\tmax = subtree_gap;\n\t}\n\treturn max;\n}",
"#ifdef CONFIG_DEBUG_VM_RB\nstatic int browse_rb(struct mm_struct *mm)\n{\n\tstruct rb_root *root = &mm->mm_rb;\n\tint i = 0, j, bug = 0;\n\tstruct rb_node *nd, *pn = NULL;\n\tunsigned long prev = 0, pend = 0;",
"\tfor (nd = rb_first(root); nd; nd = rb_next(nd)) {\n\t\tstruct vm_area_struct *vma;\n\t\tvma = rb_entry(nd, struct vm_area_struct, vm_rb);\n\t\tif (vma->vm_start < prev) {\n\t\t\tpr_emerg(\"vm_start %lx < prev %lx\\n\",\n\t\t\t\t vma->vm_start, prev);\n\t\t\tbug = 1;\n\t\t}\n\t\tif (vma->vm_start < pend) {\n\t\t\tpr_emerg(\"vm_start %lx < pend %lx\\n\",\n\t\t\t\t vma->vm_start, pend);\n\t\t\tbug = 1;\n\t\t}\n\t\tif (vma->vm_start > vma->vm_end) {\n\t\t\tpr_emerg(\"vm_start %lx > vm_end %lx\\n\",\n\t\t\t\t vma->vm_start, vma->vm_end);\n\t\t\tbug = 1;\n\t\t}\n\t\tspin_lock(&mm->page_table_lock);\n\t\tif (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {\n\t\t\tpr_emerg(\"free gap %lx, correct %lx\\n\",\n\t\t\t vma->rb_subtree_gap,\n\t\t\t vma_compute_subtree_gap(vma));\n\t\t\tbug = 1;\n\t\t}\n\t\tspin_unlock(&mm->page_table_lock);\n\t\ti++;\n\t\tpn = nd;\n\t\tprev = vma->vm_start;\n\t\tpend = vma->vm_end;\n\t}\n\tj = 0;\n\tfor (nd = pn; nd; nd = rb_prev(nd))\n\t\tj++;\n\tif (i != j) {\n\t\tpr_emerg(\"backwards %d, forwards %d\\n\", j, i);\n\t\tbug = 1;\n\t}\n\treturn bug ? -1 : i;\n}",
"static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)\n{\n\tstruct rb_node *nd;",
"\tfor (nd = rb_first(root); nd; nd = rb_next(nd)) {\n\t\tstruct vm_area_struct *vma;\n\t\tvma = rb_entry(nd, struct vm_area_struct, vm_rb);\n\t\tVM_BUG_ON_VMA(vma != ignore &&\n\t\t\tvma->rb_subtree_gap != vma_compute_subtree_gap(vma),\n\t\t\tvma);\n\t}\n}",
"static void validate_mm(struct mm_struct *mm)\n{\n\tint bug = 0;\n\tint i = 0;\n\tunsigned long highest_address = 0;\n\tstruct vm_area_struct *vma = mm->mmap;",
"\twhile (vma) {\n\t\tstruct anon_vma *anon_vma = vma->anon_vma;\n\t\tstruct anon_vma_chain *avc;",
"\t\tif (anon_vma) {\n\t\t\tanon_vma_lock_read(anon_vma);\n\t\t\tlist_for_each_entry(avc, &vma->anon_vma_chain, same_vma)\n\t\t\t\tanon_vma_interval_tree_verify(avc);\n\t\t\tanon_vma_unlock_read(anon_vma);\n\t\t}",
"\t\thighest_address = vm_end_gap(vma);\n\t\tvma = vma->vm_next;\n\t\ti++;\n\t}\n\tif (i != mm->map_count) {\n\t\tpr_emerg(\"map_count %d vm_next %d\\n\", mm->map_count, i);\n\t\tbug = 1;\n\t}\n\tif (highest_address != mm->highest_vm_end) {\n\t\tpr_emerg(\"mm->highest_vm_end %lx, found %lx\\n\",\n\t\t\t mm->highest_vm_end, highest_address);\n\t\tbug = 1;\n\t}\n\ti = browse_rb(mm);\n\tif (i != mm->map_count) {\n\t\tif (i != -1)\n\t\t\tpr_emerg(\"map_count %d rb %d\\n\", mm->map_count, i);\n\t\tbug = 1;\n\t}\n\tVM_BUG_ON_MM(bug, mm);\n}\n#else\n#define validate_mm_rb(root, ignore) do { } while (0)\n#define validate_mm(mm) do { } while (0)\n#endif",
"RB_DECLARE_CALLBACKS(static, vma_gap_callbacks, struct vm_area_struct, vm_rb,\n\t\t unsigned long, rb_subtree_gap, vma_compute_subtree_gap)",
"/*\n * Update augmented rbtree rb_subtree_gap values after vma->vm_start or\n * vma->vm_prev->vm_end values changed, without modifying the vma's position\n * in the rbtree.\n */\nstatic void vma_gap_update(struct vm_area_struct *vma)\n{\n\t/*\n\t * As it turns out, RB_DECLARE_CALLBACKS() already created a callback\n\t * function that does exacltly what we want.\n\t */\n\tvma_gap_callbacks_propagate(&vma->vm_rb, NULL);\n}",
"static inline void vma_rb_insert(struct vm_area_struct *vma,\n\t\t\t\t struct rb_root *root)\n{\n\t/* All rb_subtree_gap values must be consistent prior to insertion */\n\tvalidate_mm_rb(root, NULL);",
"\trb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);\n}",
"static void __vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)\n{\n\t/*\n\t * Note rb_erase_augmented is a fairly large inline function,\n\t * so make sure we instantiate it only once with our desired\n\t * augmented rbtree callbacks.\n\t */\n\trb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);\n}",
"static __always_inline void vma_rb_erase_ignore(struct vm_area_struct *vma,\n\t\t\t\t\t\tstruct rb_root *root,\n\t\t\t\t\t\tstruct vm_area_struct *ignore)\n{\n\t/*\n\t * All rb_subtree_gap values must be consistent prior to erase,\n\t * with the possible exception of the \"next\" vma being erased if\n\t * next->vm_start was reduced.\n\t */\n\tvalidate_mm_rb(root, ignore);",
"\t__vma_rb_erase(vma, root);\n}",
"static __always_inline void vma_rb_erase(struct vm_area_struct *vma,\n\t\t\t\t\t struct rb_root *root)\n{\n\t/*\n\t * All rb_subtree_gap values must be consistent prior to erase,\n\t * with the possible exception of the vma being erased.\n\t */\n\tvalidate_mm_rb(root, vma);",
"\t__vma_rb_erase(vma, root);\n}",
"/*\n * vma has some anon_vma assigned, and is already inserted on that\n * anon_vma's interval trees.\n *\n * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the\n * vma must be removed from the anon_vma's interval trees using\n * anon_vma_interval_tree_pre_update_vma().\n *\n * After the update, the vma will be reinserted using\n * anon_vma_interval_tree_post_update_vma().\n *\n * The entire update must be protected by exclusive mmap_sem and by\n * the root anon_vma's mutex.\n */\nstatic inline void\nanon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)\n{\n\tstruct anon_vma_chain *avc;",
"\tlist_for_each_entry(avc, &vma->anon_vma_chain, same_vma)\n\t\tanon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);\n}",
"static inline void\nanon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)\n{\n\tstruct anon_vma_chain *avc;",
"\tlist_for_each_entry(avc, &vma->anon_vma_chain, same_vma)\n\t\tanon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);\n}",
"static int find_vma_links(struct mm_struct *mm, unsigned long addr,\n\t\tunsigned long end, struct vm_area_struct **pprev,\n\t\tstruct rb_node ***rb_link, struct rb_node **rb_parent)\n{\n\tstruct rb_node **__rb_link, *__rb_parent, *rb_prev;",
"\t__rb_link = &mm->mm_rb.rb_node;\n\trb_prev = __rb_parent = NULL;",
"\twhile (*__rb_link) {\n\t\tstruct vm_area_struct *vma_tmp;",
"\t\t__rb_parent = *__rb_link;\n\t\tvma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);",
"\t\tif (vma_tmp->vm_end > addr) {\n\t\t\t/* Fail if an existing vma overlaps the area */\n\t\t\tif (vma_tmp->vm_start < end)\n\t\t\t\treturn -ENOMEM;\n\t\t\t__rb_link = &__rb_parent->rb_left;\n\t\t} else {\n\t\t\trb_prev = __rb_parent;\n\t\t\t__rb_link = &__rb_parent->rb_right;\n\t\t}\n\t}",
"\t*pprev = NULL;\n\tif (rb_prev)\n\t\t*pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);\n\t*rb_link = __rb_link;\n\t*rb_parent = __rb_parent;\n\treturn 0;\n}",
"static unsigned long count_vma_pages_range(struct mm_struct *mm,\n\t\tunsigned long addr, unsigned long end)\n{\n\tunsigned long nr_pages = 0;\n\tstruct vm_area_struct *vma;",
"\t/* Find first overlaping mapping */\n\tvma = find_vma_intersection(mm, addr, end);\n\tif (!vma)\n\t\treturn 0;",
"\tnr_pages = (min(end, vma->vm_end) -\n\t\tmax(addr, vma->vm_start)) >> PAGE_SHIFT;",
"\t/* Iterate over the rest of the overlaps */\n\tfor (vma = vma->vm_next; vma; vma = vma->vm_next) {\n\t\tunsigned long overlap_len;",
"\t\tif (vma->vm_start > end)\n\t\t\tbreak;",
"\t\toverlap_len = min(end, vma->vm_end) - vma->vm_start;\n\t\tnr_pages += overlap_len >> PAGE_SHIFT;\n\t}",
"\treturn nr_pages;\n}",
"void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,\n\t\tstruct rb_node **rb_link, struct rb_node *rb_parent)\n{\n\t/* Update tracking information for the gap following the new vma. */\n\tif (vma->vm_next)\n\t\tvma_gap_update(vma->vm_next);\n\telse\n\t\tmm->highest_vm_end = vm_end_gap(vma);",
"\t/*\n\t * vma->vm_prev wasn't known when we followed the rbtree to find the\n\t * correct insertion point for that vma. As a result, we could not\n\t * update the vma vm_rb parents rb_subtree_gap values on the way down.\n\t * So, we first insert the vma with a zero rb_subtree_gap value\n\t * (to be consistent with what we did on the way down), and then\n\t * immediately update the gap to the correct value. Finally we\n\t * rebalance the rbtree after all augmented values have been set.\n\t */\n\trb_link_node(&vma->vm_rb, rb_parent, rb_link);\n\tvma->rb_subtree_gap = 0;\n\tvma_gap_update(vma);\n\tvma_rb_insert(vma, &mm->mm_rb);\n}",
"static void __vma_link_file(struct vm_area_struct *vma)\n{\n\tstruct file *file;",
"\tfile = vma->vm_file;\n\tif (file) {\n\t\tstruct address_space *mapping = file->f_mapping;",
"\t\tif (vma->vm_flags & VM_DENYWRITE)\n\t\t\tatomic_dec(&file_inode(file)->i_writecount);\n\t\tif (vma->vm_flags & VM_SHARED)\n\t\t\tatomic_inc(&mapping->i_mmap_writable);",
"\t\tflush_dcache_mmap_lock(mapping);\n\t\tvma_interval_tree_insert(vma, &mapping->i_mmap);\n\t\tflush_dcache_mmap_unlock(mapping);\n\t}\n}",
"static void\n__vma_link(struct mm_struct *mm, struct vm_area_struct *vma,\n\tstruct vm_area_struct *prev, struct rb_node **rb_link,\n\tstruct rb_node *rb_parent)\n{\n\t__vma_link_list(mm, vma, prev, rb_parent);\n\t__vma_link_rb(mm, vma, rb_link, rb_parent);\n}",
"static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,\n\t\t\tstruct vm_area_struct *prev, struct rb_node **rb_link,\n\t\t\tstruct rb_node *rb_parent)\n{\n\tstruct address_space *mapping = NULL;",
"\tif (vma->vm_file) {\n\t\tmapping = vma->vm_file->f_mapping;\n\t\ti_mmap_lock_write(mapping);\n\t}",
"\t__vma_link(mm, vma, prev, rb_link, rb_parent);\n\t__vma_link_file(vma);",
"\tif (mapping)\n\t\ti_mmap_unlock_write(mapping);",
"\tmm->map_count++;\n\tvalidate_mm(mm);\n}",
"/*\n * Helper for vma_adjust() in the split_vma insert case: insert a vma into the\n * mm's list and rbtree. It has already been inserted into the interval tree.\n */\nstatic void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)\n{\n\tstruct vm_area_struct *prev;\n\tstruct rb_node **rb_link, *rb_parent;",
"\tif (find_vma_links(mm, vma->vm_start, vma->vm_end,\n\t\t\t &prev, &rb_link, &rb_parent))\n\t\tBUG();\n\t__vma_link(mm, vma, prev, rb_link, rb_parent);\n\tmm->map_count++;\n}",
"static __always_inline void __vma_unlink_common(struct mm_struct *mm,\n\t\t\t\t\t\tstruct vm_area_struct *vma,\n\t\t\t\t\t\tstruct vm_area_struct *prev,\n\t\t\t\t\t\tbool has_prev,\n\t\t\t\t\t\tstruct vm_area_struct *ignore)\n{\n\tstruct vm_area_struct *next;",
"\tvma_rb_erase_ignore(vma, &mm->mm_rb, ignore);\n\tnext = vma->vm_next;\n\tif (has_prev)\n\t\tprev->vm_next = next;\n\telse {\n\t\tprev = vma->vm_prev;\n\t\tif (prev)\n\t\t\tprev->vm_next = next;\n\t\telse\n\t\t\tmm->mmap = next;\n\t}\n\tif (next)\n\t\tnext->vm_prev = prev;",
"\t/* Kill the cache */\n\tvmacache_invalidate(mm);\n}",
"static inline void __vma_unlink_prev(struct mm_struct *mm,\n\t\t\t\t struct vm_area_struct *vma,\n\t\t\t\t struct vm_area_struct *prev)\n{\n\t__vma_unlink_common(mm, vma, prev, true, vma);\n}",
"/*\n * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that\n * is already present in an i_mmap tree without adjusting the tree.\n * The following helper function should be used when such adjustments\n * are necessary. The \"insert\" vma (if any) is to be inserted\n * before we drop the necessary locks.\n */\nint __vma_adjust(struct vm_area_struct *vma, unsigned long start,\n\tunsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,\n\tstruct vm_area_struct *expand)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tstruct vm_area_struct *next = vma->vm_next, *orig_vma = vma;\n\tstruct address_space *mapping = NULL;\n\tstruct rb_root_cached *root = NULL;\n\tstruct anon_vma *anon_vma = NULL;\n\tstruct file *file = vma->vm_file;\n\tbool start_changed = false, end_changed = false;\n\tlong adjust_next = 0;\n\tint remove_next = 0;",
"\tif (next && !insert) {\n\t\tstruct vm_area_struct *exporter = NULL, *importer = NULL;",
"\t\tif (end >= next->vm_end) {\n\t\t\t/*\n\t\t\t * vma expands, overlapping all the next, and\n\t\t\t * perhaps the one after too (mprotect case 6).\n\t\t\t * The only other cases that gets here are\n\t\t\t * case 1, case 7 and case 8.\n\t\t\t */\n\t\t\tif (next == expand) {\n\t\t\t\t/*\n\t\t\t\t * The only case where we don't expand \"vma\"\n\t\t\t\t * and we expand \"next\" instead is case 8.\n\t\t\t\t */\n\t\t\t\tVM_WARN_ON(end != next->vm_end);\n\t\t\t\t/*\n\t\t\t\t * remove_next == 3 means we're\n\t\t\t\t * removing \"vma\" and that to do so we\n\t\t\t\t * swapped \"vma\" and \"next\".\n\t\t\t\t */\n\t\t\t\tremove_next = 3;\n\t\t\t\tVM_WARN_ON(file != next->vm_file);\n\t\t\t\tswap(vma, next);\n\t\t\t} else {\n\t\t\t\tVM_WARN_ON(expand != vma);\n\t\t\t\t/*\n\t\t\t\t * case 1, 6, 7, remove_next == 2 is case 6,\n\t\t\t\t * remove_next == 1 is case 1 or 7.\n\t\t\t\t */\n\t\t\t\tremove_next = 1 + (end > next->vm_end);\n\t\t\t\tVM_WARN_ON(remove_next == 2 &&\n\t\t\t\t\t end != next->vm_next->vm_end);\n\t\t\t\tVM_WARN_ON(remove_next == 1 &&\n\t\t\t\t\t end != next->vm_end);\n\t\t\t\t/* trim end to next, for case 6 first pass */\n\t\t\t\tend = next->vm_end;\n\t\t\t}",
"\t\t\texporter = next;\n\t\t\timporter = vma;",
"\t\t\t/*\n\t\t\t * If next doesn't have anon_vma, import from vma after\n\t\t\t * next, if the vma overlaps with it.\n\t\t\t */\n\t\t\tif (remove_next == 2 && !next->anon_vma)\n\t\t\t\texporter = next->vm_next;",
"\t\t} else if (end > next->vm_start) {\n\t\t\t/*\n\t\t\t * vma expands, overlapping part of the next:\n\t\t\t * mprotect case 5 shifting the boundary up.\n\t\t\t */\n\t\t\tadjust_next = (end - next->vm_start) >> PAGE_SHIFT;\n\t\t\texporter = next;\n\t\t\timporter = vma;\n\t\t\tVM_WARN_ON(expand != importer);\n\t\t} else if (end < vma->vm_end) {\n\t\t\t/*\n\t\t\t * vma shrinks, and !insert tells it's not\n\t\t\t * split_vma inserting another: so it must be\n\t\t\t * mprotect case 4 shifting the boundary down.\n\t\t\t */\n\t\t\tadjust_next = -((vma->vm_end - end) >> PAGE_SHIFT);\n\t\t\texporter = vma;\n\t\t\timporter = next;\n\t\t\tVM_WARN_ON(expand != importer);\n\t\t}",
"\t\t/*\n\t\t * Easily overlooked: when mprotect shifts the boundary,\n\t\t * make sure the expanding vma has anon_vma set if the\n\t\t * shrinking vma had, to cover any anon pages imported.\n\t\t */\n\t\tif (exporter && exporter->anon_vma && !importer->anon_vma) {\n\t\t\tint error;",
"\t\t\timporter->anon_vma = exporter->anon_vma;\n\t\t\terror = anon_vma_clone(importer, exporter);\n\t\t\tif (error)\n\t\t\t\treturn error;\n\t\t}\n\t}\nagain:\n\tvma_adjust_trans_huge(orig_vma, start, end, adjust_next);",
"\tif (file) {\n\t\tmapping = file->f_mapping;\n\t\troot = &mapping->i_mmap;\n\t\tuprobe_munmap(vma, vma->vm_start, vma->vm_end);",
"\t\tif (adjust_next)\n\t\t\tuprobe_munmap(next, next->vm_start, next->vm_end);",
"\t\ti_mmap_lock_write(mapping);\n\t\tif (insert) {\n\t\t\t/*\n\t\t\t * Put into interval tree now, so instantiated pages\n\t\t\t * are visible to arm/parisc __flush_dcache_page\n\t\t\t * throughout; but we cannot insert into address\n\t\t\t * space until vma start or end is updated.\n\t\t\t */\n\t\t\t__vma_link_file(insert);\n\t\t}\n\t}",
"\tanon_vma = vma->anon_vma;\n\tif (!anon_vma && adjust_next)\n\t\tanon_vma = next->anon_vma;\n\tif (anon_vma) {\n\t\tVM_WARN_ON(adjust_next && next->anon_vma &&\n\t\t\t anon_vma != next->anon_vma);\n\t\tanon_vma_lock_write(anon_vma);\n\t\tanon_vma_interval_tree_pre_update_vma(vma);\n\t\tif (adjust_next)\n\t\t\tanon_vma_interval_tree_pre_update_vma(next);\n\t}",
"\tif (root) {\n\t\tflush_dcache_mmap_lock(mapping);\n\t\tvma_interval_tree_remove(vma, root);\n\t\tif (adjust_next)\n\t\t\tvma_interval_tree_remove(next, root);\n\t}",
"\tif (start != vma->vm_start) {\n\t\tvma->vm_start = start;\n\t\tstart_changed = true;\n\t}\n\tif (end != vma->vm_end) {\n\t\tvma->vm_end = end;\n\t\tend_changed = true;\n\t}\n\tvma->vm_pgoff = pgoff;\n\tif (adjust_next) {\n\t\tnext->vm_start += adjust_next << PAGE_SHIFT;\n\t\tnext->vm_pgoff += adjust_next;\n\t}",
"\tif (root) {\n\t\tif (adjust_next)\n\t\t\tvma_interval_tree_insert(next, root);\n\t\tvma_interval_tree_insert(vma, root);\n\t\tflush_dcache_mmap_unlock(mapping);\n\t}",
"\tif (remove_next) {\n\t\t/*\n\t\t * vma_merge has merged next into vma, and needs\n\t\t * us to remove next before dropping the locks.\n\t\t */\n\t\tif (remove_next != 3)\n\t\t\t__vma_unlink_prev(mm, next, vma);\n\t\telse\n\t\t\t/*\n\t\t\t * vma is not before next if they've been\n\t\t\t * swapped.\n\t\t\t *\n\t\t\t * pre-swap() next->vm_start was reduced so\n\t\t\t * tell validate_mm_rb to ignore pre-swap()\n\t\t\t * \"next\" (which is stored in post-swap()\n\t\t\t * \"vma\").\n\t\t\t */\n\t\t\t__vma_unlink_common(mm, next, NULL, false, vma);\n\t\tif (file)\n\t\t\t__remove_shared_vm_struct(next, file, mapping);\n\t} else if (insert) {\n\t\t/*\n\t\t * split_vma has split insert from vma, and needs\n\t\t * us to insert it before dropping the locks\n\t\t * (it may either follow vma or precede it).\n\t\t */\n\t\t__insert_vm_struct(mm, insert);\n\t} else {\n\t\tif (start_changed)\n\t\t\tvma_gap_update(vma);\n\t\tif (end_changed) {\n\t\t\tif (!next)\n\t\t\t\tmm->highest_vm_end = vm_end_gap(vma);\n\t\t\telse if (!adjust_next)\n\t\t\t\tvma_gap_update(next);\n\t\t}\n\t}",
"\tif (anon_vma) {\n\t\tanon_vma_interval_tree_post_update_vma(vma);\n\t\tif (adjust_next)\n\t\t\tanon_vma_interval_tree_post_update_vma(next);\n\t\tanon_vma_unlock_write(anon_vma);\n\t}\n\tif (mapping)\n\t\ti_mmap_unlock_write(mapping);",
"\tif (root) {\n\t\tuprobe_mmap(vma);",
"\t\tif (adjust_next)\n\t\t\tuprobe_mmap(next);\n\t}",
"\tif (remove_next) {\n\t\tif (file) {\n\t\t\tuprobe_munmap(next, next->vm_start, next->vm_end);\n\t\t\tfput(file);\n\t\t}\n\t\tif (next->anon_vma)\n\t\t\tanon_vma_merge(vma, next);\n\t\tmm->map_count--;\n\t\tmpol_put(vma_policy(next));\n\t\tvm_area_free(next);\n\t\t/*\n\t\t * In mprotect's case 6 (see comments on vma_merge),\n\t\t * we must remove another next too. It would clutter\n\t\t * up the code too much to do both in one go.\n\t\t */\n\t\tif (remove_next != 3) {\n\t\t\t/*\n\t\t\t * If \"next\" was removed and vma->vm_end was\n\t\t\t * expanded (up) over it, in turn\n\t\t\t * \"next->vm_prev->vm_end\" changed and the\n\t\t\t * \"vma->vm_next\" gap must be updated.\n\t\t\t */\n\t\t\tnext = vma->vm_next;\n\t\t} else {\n\t\t\t/*\n\t\t\t * For the scope of the comment \"next\" and\n\t\t\t * \"vma\" considered pre-swap(): if \"vma\" was\n\t\t\t * removed, next->vm_start was expanded (down)\n\t\t\t * over it and the \"next\" gap must be updated.\n\t\t\t * Because of the swap() the post-swap() \"vma\"\n\t\t\t * actually points to pre-swap() \"next\"\n\t\t\t * (post-swap() \"next\" as opposed is now a\n\t\t\t * dangling pointer).\n\t\t\t */\n\t\t\tnext = vma;\n\t\t}\n\t\tif (remove_next == 2) {\n\t\t\tremove_next = 1;\n\t\t\tend = next->vm_end;\n\t\t\tgoto again;\n\t\t}\n\t\telse if (next)\n\t\t\tvma_gap_update(next);\n\t\telse {\n\t\t\t/*\n\t\t\t * If remove_next == 2 we obviously can't\n\t\t\t * reach this path.\n\t\t\t *\n\t\t\t * If remove_next == 3 we can't reach this\n\t\t\t * path because pre-swap() next is always not\n\t\t\t * NULL. pre-swap() \"next\" is not being\n\t\t\t * removed and its next->vm_end is not altered\n\t\t\t * (and furthermore \"end\" already matches\n\t\t\t * next->vm_end in remove_next == 3).\n\t\t\t *\n\t\t\t * We reach this only in the remove_next == 1\n\t\t\t * case if the \"next\" vma that was removed was\n\t\t\t * the highest vma of the mm. However in such\n\t\t\t * case next->vm_end == \"end\" and the extended\n\t\t\t * \"vma\" has vma->vm_end == next->vm_end so\n\t\t\t * mm->highest_vm_end doesn't need any update\n\t\t\t * in remove_next == 1 case.\n\t\t\t */\n\t\t\tVM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));\n\t\t}\n\t}\n\tif (insert && file)\n\t\tuprobe_mmap(insert);",
"\tvalidate_mm(mm);",
"\treturn 0;\n}",
"/*\n * If the vma has a ->close operation then the driver probably needs to release\n * per-vma resources, so we don't attempt to merge those.\n */\nstatic inline int is_mergeable_vma(struct vm_area_struct *vma,\n\t\t\t\tstruct file *file, unsigned long vm_flags,\n\t\t\t\tstruct vm_userfaultfd_ctx vm_userfaultfd_ctx)\n{\n\t/*\n\t * VM_SOFTDIRTY should not prevent from VMA merging, if we\n\t * match the flags but dirty bit -- the caller should mark\n\t * merged VMA as dirty. If dirty bit won't be excluded from\n\t * comparison, we increase pressue on the memory system forcing\n\t * the kernel to generate new VMAs when old one could be\n\t * extended instead.\n\t */\n\tif ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)\n\t\treturn 0;\n\tif (vma->vm_file != file)\n\t\treturn 0;\n\tif (vma->vm_ops && vma->vm_ops->close)\n\t\treturn 0;\n\tif (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))\n\t\treturn 0;\n\treturn 1;\n}",
"static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,\n\t\t\t\t\tstruct anon_vma *anon_vma2,\n\t\t\t\t\tstruct vm_area_struct *vma)\n{\n\t/*\n\t * The list_is_singular() test is to avoid merging VMA cloned from\n\t * parents. This can improve scalability caused by anon_vma lock.\n\t */\n\tif ((!anon_vma1 || !anon_vma2) && (!vma ||\n\t\tlist_is_singular(&vma->anon_vma_chain)))\n\t\treturn 1;\n\treturn anon_vma1 == anon_vma2;\n}",
"/*\n * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)\n * in front of (at a lower virtual address and file offset than) the vma.\n *\n * We cannot merge two vmas if they have differently assigned (non-NULL)\n * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.\n *\n * We don't check here for the merged mmap wrapping around the end of pagecache\n * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which\n * wrap, nor mmaps which cover the final page at index -1UL.\n */\nstatic int\ncan_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,\n\t\t struct anon_vma *anon_vma, struct file *file,\n\t\t pgoff_t vm_pgoff,\n\t\t struct vm_userfaultfd_ctx vm_userfaultfd_ctx)\n{\n\tif (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&\n\t is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {\n\t\tif (vma->vm_pgoff == vm_pgoff)\n\t\t\treturn 1;\n\t}\n\treturn 0;\n}",
"/*\n * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)\n * beyond (at a higher virtual address and file offset than) the vma.\n *\n * We cannot merge two vmas if they have differently assigned (non-NULL)\n * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.\n */\nstatic int\ncan_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,\n\t\t struct anon_vma *anon_vma, struct file *file,\n\t\t pgoff_t vm_pgoff,\n\t\t struct vm_userfaultfd_ctx vm_userfaultfd_ctx)\n{\n\tif (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&\n\t is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {\n\t\tpgoff_t vm_pglen;\n\t\tvm_pglen = vma_pages(vma);\n\t\tif (vma->vm_pgoff + vm_pglen == vm_pgoff)\n\t\t\treturn 1;\n\t}\n\treturn 0;\n}",
"/*\n * Given a mapping request (addr,end,vm_flags,file,pgoff), figure out\n * whether that can be merged with its predecessor or its successor.\n * Or both (it neatly fills a hole).\n *\n * In most cases - when called for mmap, brk or mremap - [addr,end) is\n * certain not to be mapped by the time vma_merge is called; but when\n * called for mprotect, it is certain to be already mapped (either at\n * an offset within prev, or at the start of next), and the flags of\n * this area are about to be changed to vm_flags - and the no-change\n * case has already been eliminated.\n *\n * The following mprotect cases have to be considered, where AAAA is\n * the area passed down from mprotect_fixup, never extending beyond one\n * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:\n *\n * AAAA AAAA AAAA AAAA\n * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN PPPPNNNNXXXX\n * cannot merge might become might become might become\n * PPNNNNNNNNNN PPPPPPPPPPNN PPPPPPPPPPPP 6 or\n * mmap, brk or case 4 below case 5 below PPPPPPPPXXXX 7 or\n * mremap move: PPPPXXXXXXXX 8\n * AAAA\n * PPPP NNNN PPPPPPPPPPPP PPPPPPPPNNNN PPPPNNNNNNNN\n * might become case 1 below case 2 below case 3 below\n *\n * It is important for case 8 that the the vma NNNN overlapping the\n * region AAAA is never going to extended over XXXX. Instead XXXX must\n * be extended in region AAAA and NNNN must be removed. This way in\n * all cases where vma_merge succeeds, the moment vma_adjust drops the\n * rmap_locks, the properties of the merged vma will be already\n * correct for the whole merged range. Some of those properties like\n * vm_page_prot/vm_flags may be accessed by rmap_walks and they must\n * be correct for the whole merged range immediately after the\n * rmap_locks are released. Otherwise if XXXX would be removed and\n * NNNN would be extended over the XXXX range, remove_migration_ptes\n * or other rmap walkers (if working on addresses beyond the \"end\"\n * parameter) may establish ptes with the wrong permissions of NNNN\n * instead of the right permissions of XXXX.\n */\nstruct vm_area_struct *vma_merge(struct mm_struct *mm,\n\t\t\tstruct vm_area_struct *prev, unsigned long addr,\n\t\t\tunsigned long end, unsigned long vm_flags,\n\t\t\tstruct anon_vma *anon_vma, struct file *file,\n\t\t\tpgoff_t pgoff, struct mempolicy *policy,\n\t\t\tstruct vm_userfaultfd_ctx vm_userfaultfd_ctx)\n{\n\tpgoff_t pglen = (end - addr) >> PAGE_SHIFT;\n\tstruct vm_area_struct *area, *next;\n\tint err;",
"\t/*\n\t * We later require that vma->vm_flags == vm_flags,\n\t * so this tests vma->vm_flags & VM_SPECIAL, too.\n\t */\n\tif (vm_flags & VM_SPECIAL)\n\t\treturn NULL;",
"\tif (prev)\n\t\tnext = prev->vm_next;\n\telse\n\t\tnext = mm->mmap;\n\tarea = next;\n\tif (area && area->vm_end == end)\t\t/* cases 6, 7, 8 */\n\t\tnext = next->vm_next;",
"\t/* verify some invariant that must be enforced by the caller */\n\tVM_WARN_ON(prev && addr <= prev->vm_start);\n\tVM_WARN_ON(area && end > area->vm_end);\n\tVM_WARN_ON(addr >= end);",
"\t/*\n\t * Can it merge with the predecessor?\n\t */\n\tif (prev && prev->vm_end == addr &&\n\t\t\tmpol_equal(vma_policy(prev), policy) &&\n\t\t\tcan_vma_merge_after(prev, vm_flags,\n\t\t\t\t\t anon_vma, file, pgoff,\n\t\t\t\t\t vm_userfaultfd_ctx)) {\n\t\t/*\n\t\t * OK, it can. Can we now merge in the successor as well?\n\t\t */\n\t\tif (next && end == next->vm_start &&\n\t\t\t\tmpol_equal(policy, vma_policy(next)) &&\n\t\t\t\tcan_vma_merge_before(next, vm_flags,\n\t\t\t\t\t\t anon_vma, file,\n\t\t\t\t\t\t pgoff+pglen,\n\t\t\t\t\t\t vm_userfaultfd_ctx) &&\n\t\t\t\tis_mergeable_anon_vma(prev->anon_vma,\n\t\t\t\t\t\t next->anon_vma, NULL)) {\n\t\t\t\t\t\t\t/* cases 1, 6 */\n\t\t\terr = __vma_adjust(prev, prev->vm_start,\n\t\t\t\t\t next->vm_end, prev->vm_pgoff, NULL,\n\t\t\t\t\t prev);\n\t\t} else\t\t\t\t\t/* cases 2, 5, 7 */\n\t\t\terr = __vma_adjust(prev, prev->vm_start,\n\t\t\t\t\t end, prev->vm_pgoff, NULL, prev);\n\t\tif (err)\n\t\t\treturn NULL;\n\t\tkhugepaged_enter_vma_merge(prev, vm_flags);\n\t\treturn prev;\n\t}",
"\t/*\n\t * Can this new request be merged in front of next?\n\t */\n\tif (next && end == next->vm_start &&\n\t\t\tmpol_equal(policy, vma_policy(next)) &&\n\t\t\tcan_vma_merge_before(next, vm_flags,\n\t\t\t\t\t anon_vma, file, pgoff+pglen,\n\t\t\t\t\t vm_userfaultfd_ctx)) {\n\t\tif (prev && addr < prev->vm_end)\t/* case 4 */\n\t\t\terr = __vma_adjust(prev, prev->vm_start,\n\t\t\t\t\t addr, prev->vm_pgoff, NULL, next);\n\t\telse {\t\t\t\t\t/* cases 3, 8 */\n\t\t\terr = __vma_adjust(area, addr, next->vm_end,\n\t\t\t\t\t next->vm_pgoff - pglen, NULL, next);\n\t\t\t/*\n\t\t\t * In case 3 area is already equal to next and\n\t\t\t * this is a noop, but in case 8 \"area\" has\n\t\t\t * been removed and next was expanded over it.\n\t\t\t */\n\t\t\tarea = next;\n\t\t}\n\t\tif (err)\n\t\t\treturn NULL;\n\t\tkhugepaged_enter_vma_merge(area, vm_flags);\n\t\treturn area;\n\t}",
"\treturn NULL;\n}",
"/*\n * Rough compatbility check to quickly see if it's even worth looking\n * at sharing an anon_vma.\n *\n * They need to have the same vm_file, and the flags can only differ\n * in things that mprotect may change.\n *\n * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that\n * we can merge the two vma's. For example, we refuse to merge a vma if\n * there is a vm_ops->close() function, because that indicates that the\n * driver is doing some kind of reference counting. But that doesn't\n * really matter for the anon_vma sharing case.\n */\nstatic int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)\n{\n\treturn a->vm_end == b->vm_start &&\n\t\tmpol_equal(vma_policy(a), vma_policy(b)) &&\n\t\ta->vm_file == b->vm_file &&\n\t\t!((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC|VM_SOFTDIRTY)) &&\n\t\tb->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);\n}",
"/*\n * Do some basic sanity checking to see if we can re-use the anon_vma\n * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be\n * the same as 'old', the other will be the new one that is trying\n * to share the anon_vma.\n *\n * NOTE! This runs with mm_sem held for reading, so it is possible that\n * the anon_vma of 'old' is concurrently in the process of being set up\n * by another page fault trying to merge _that_. But that's ok: if it\n * is being set up, that automatically means that it will be a singleton\n * acceptable for merging, so we can do all of this optimistically. But\n * we do that READ_ONCE() to make sure that we never re-load the pointer.\n *\n * IOW: that the \"list_is_singular()\" test on the anon_vma_chain only\n * matters for the 'stable anon_vma' case (ie the thing we want to avoid\n * is to return an anon_vma that is \"complex\" due to having gone through\n * a fork).\n *\n * We also make sure that the two vma's are compatible (adjacent,\n * and with the same memory policies). That's all stable, even with just\n * a read lock on the mm_sem.\n */\nstatic struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)\n{\n\tif (anon_vma_compatible(a, b)) {\n\t\tstruct anon_vma *anon_vma = READ_ONCE(old->anon_vma);",
"\t\tif (anon_vma && list_is_singular(&old->anon_vma_chain))\n\t\t\treturn anon_vma;\n\t}\n\treturn NULL;\n}",
"/*\n * find_mergeable_anon_vma is used by anon_vma_prepare, to check\n * neighbouring vmas for a suitable anon_vma, before it goes off\n * to allocate a new anon_vma. It checks because a repetitive\n * sequence of mprotects and faults may otherwise lead to distinct\n * anon_vmas being allocated, preventing vma merge in subsequent\n * mprotect.\n */\nstruct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)\n{\n\tstruct anon_vma *anon_vma;\n\tstruct vm_area_struct *near;",
"\tnear = vma->vm_next;\n\tif (!near)\n\t\tgoto try_prev;",
"\tanon_vma = reusable_anon_vma(near, vma, near);\n\tif (anon_vma)\n\t\treturn anon_vma;\ntry_prev:\n\tnear = vma->vm_prev;\n\tif (!near)\n\t\tgoto none;",
"\tanon_vma = reusable_anon_vma(near, near, vma);\n\tif (anon_vma)\n\t\treturn anon_vma;\nnone:\n\t/*\n\t * There's no absolute need to look only at touching neighbours:\n\t * we could search further afield for \"compatible\" anon_vmas.\n\t * But it would probably just be a waste of time searching,\n\t * or lead to too many vmas hanging off the same anon_vma.\n\t * We're trying to allow mprotect remerging later on,\n\t * not trying to minimize memory used for anon_vmas.\n\t */\n\treturn NULL;\n}",
"/*\n * If a hint addr is less than mmap_min_addr change hint to be as\n * low as possible but still greater than mmap_min_addr\n */\nstatic inline unsigned long round_hint_to_min(unsigned long hint)\n{\n\thint &= PAGE_MASK;\n\tif (((void *)hint != NULL) &&\n\t (hint < mmap_min_addr))\n\t\treturn PAGE_ALIGN(mmap_min_addr);\n\treturn hint;\n}",
"static inline int mlock_future_check(struct mm_struct *mm,\n\t\t\t\t unsigned long flags,\n\t\t\t\t unsigned long len)\n{\n\tunsigned long locked, lock_limit;",
"\t/* mlock MCL_FUTURE? */\n\tif (flags & VM_LOCKED) {\n\t\tlocked = len >> PAGE_SHIFT;\n\t\tlocked += mm->locked_vm;\n\t\tlock_limit = rlimit(RLIMIT_MEMLOCK);\n\t\tlock_limit >>= PAGE_SHIFT;\n\t\tif (locked > lock_limit && !capable(CAP_IPC_LOCK))\n\t\t\treturn -EAGAIN;\n\t}\n\treturn 0;\n}",
"static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)\n{\n\tif (S_ISREG(inode->i_mode))\n\t\treturn MAX_LFS_FILESIZE;",
"\tif (S_ISBLK(inode->i_mode))\n\t\treturn MAX_LFS_FILESIZE;",
"\t/* Special \"we do even unsigned file positions\" case */\n\tif (file->f_mode & FMODE_UNSIGNED_OFFSET)\n\t\treturn 0;",
"\t/* Yes, random drivers might want more. But I'm tired of buggy drivers */\n\treturn ULONG_MAX;\n}",
"static inline bool file_mmap_ok(struct file *file, struct inode *inode,\n\t\t\t\tunsigned long pgoff, unsigned long len)\n{\n\tu64 maxsize = file_mmap_size_max(file, inode);",
"\tif (maxsize && len > maxsize)\n\t\treturn false;\n\tmaxsize -= len;\n\tif (pgoff > maxsize >> PAGE_SHIFT)\n\t\treturn false;\n\treturn true;\n}",
"/*\n * The caller must hold down_write(¤t->mm->mmap_sem).\n */\nunsigned long do_mmap(struct file *file, unsigned long addr,\n\t\t\tunsigned long len, unsigned long prot,\n\t\t\tunsigned long flags, vm_flags_t vm_flags,\n\t\t\tunsigned long pgoff, unsigned long *populate,\n\t\t\tstruct list_head *uf)\n{\n\tstruct mm_struct *mm = current->mm;\n\tint pkey = 0;",
"\t*populate = 0;",
"\tif (!len)\n\t\treturn -EINVAL;",
"\t/*\n\t * Does the application expect PROT_READ to imply PROT_EXEC?\n\t *\n\t * (the exception is when the underlying filesystem is noexec\n\t * mounted, in which case we dont add PROT_EXEC.)\n\t */\n\tif ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))\n\t\tif (!(file && path_noexec(&file->f_path)))\n\t\t\tprot |= PROT_EXEC;",
"\t/* force arch specific MAP_FIXED handling in get_unmapped_area */\n\tif (flags & MAP_FIXED_NOREPLACE)\n\t\tflags |= MAP_FIXED;",
"\tif (!(flags & MAP_FIXED))\n\t\taddr = round_hint_to_min(addr);",
"\t/* Careful about overflows.. */\n\tlen = PAGE_ALIGN(len);\n\tif (!len)\n\t\treturn -ENOMEM;",
"\t/* offset overflow? */\n\tif ((pgoff + (len >> PAGE_SHIFT)) < pgoff)\n\t\treturn -EOVERFLOW;",
"\t/* Too many mappings? */\n\tif (mm->map_count > sysctl_max_map_count)\n\t\treturn -ENOMEM;",
"\t/* Obtain the address to map to. we verify (or select) it and ensure\n\t * that it represents a valid section of the address space.\n\t */\n\taddr = get_unmapped_area(file, addr, len, pgoff, flags);\n\tif (offset_in_page(addr))\n\t\treturn addr;",
"\tif (flags & MAP_FIXED_NOREPLACE) {\n\t\tstruct vm_area_struct *vma = find_vma(mm, addr);",
"\t\tif (vma && vma->vm_start < addr + len)\n\t\t\treturn -EEXIST;\n\t}",
"\tif (prot == PROT_EXEC) {\n\t\tpkey = execute_only_pkey(mm);\n\t\tif (pkey < 0)\n\t\t\tpkey = 0;\n\t}",
"\t/* Do simple checking here so the lower-level routines won't have\n\t * to. we assume access permissions have been handled by the open\n\t * of the memory object, so we don't do any here.\n\t */\n\tvm_flags |= calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |\n\t\t\tmm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;",
"\tif (flags & MAP_LOCKED)\n\t\tif (!can_do_mlock())\n\t\t\treturn -EPERM;",
"\tif (mlock_future_check(mm, vm_flags, len))\n\t\treturn -EAGAIN;",
"\tif (file) {\n\t\tstruct inode *inode = file_inode(file);\n\t\tunsigned long flags_mask;",
"\t\tif (!file_mmap_ok(file, inode, pgoff, len))\n\t\t\treturn -EOVERFLOW;",
"\t\tflags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;",
"\t\tswitch (flags & MAP_TYPE) {\n\t\tcase MAP_SHARED:\n\t\t\t/*\n\t\t\t * Force use of MAP_SHARED_VALIDATE with non-legacy\n\t\t\t * flags. E.g. MAP_SYNC is dangerous to use with\n\t\t\t * MAP_SHARED as you don't know which consistency model\n\t\t\t * you will get. We silently ignore unsupported flags\n\t\t\t * with MAP_SHARED to preserve backward compatibility.\n\t\t\t */\n\t\t\tflags &= LEGACY_MAP_MASK;\n\t\t\t/* fall through */\n\t\tcase MAP_SHARED_VALIDATE:\n\t\t\tif (flags & ~flags_mask)\n\t\t\t\treturn -EOPNOTSUPP;\n\t\t\tif ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))\n\t\t\t\treturn -EACCES;",
"\t\t\t/*\n\t\t\t * Make sure we don't allow writing to an append-only\n\t\t\t * file..\n\t\t\t */\n\t\t\tif (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))\n\t\t\t\treturn -EACCES;",
"\t\t\t/*\n\t\t\t * Make sure there are no mandatory locks on the file.\n\t\t\t */\n\t\t\tif (locks_verify_locked(file))\n\t\t\t\treturn -EAGAIN;",
"\t\t\tvm_flags |= VM_SHARED | VM_MAYSHARE;\n\t\t\tif (!(file->f_mode & FMODE_WRITE))\n\t\t\t\tvm_flags &= ~(VM_MAYWRITE | VM_SHARED);",
"\t\t\t/* fall through */\n\t\tcase MAP_PRIVATE:\n\t\t\tif (!(file->f_mode & FMODE_READ))\n\t\t\t\treturn -EACCES;\n\t\t\tif (path_noexec(&file->f_path)) {\n\t\t\t\tif (vm_flags & VM_EXEC)\n\t\t\t\t\treturn -EPERM;\n\t\t\t\tvm_flags &= ~VM_MAYEXEC;\n\t\t\t}",
"\t\t\tif (!file->f_op->mmap)\n\t\t\t\treturn -ENODEV;\n\t\t\tif (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))\n\t\t\t\treturn -EINVAL;\n\t\t\tbreak;",
"\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\t} else {\n\t\tswitch (flags & MAP_TYPE) {\n\t\tcase MAP_SHARED:\n\t\t\tif (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))\n\t\t\t\treturn -EINVAL;\n\t\t\t/*\n\t\t\t * Ignore pgoff.\n\t\t\t */\n\t\t\tpgoff = 0;\n\t\t\tvm_flags |= VM_SHARED | VM_MAYSHARE;\n\t\t\tbreak;\n\t\tcase MAP_PRIVATE:\n\t\t\t/*\n\t\t\t * Set pgoff according to addr for anon_vma.\n\t\t\t */\n\t\t\tpgoff = addr >> PAGE_SHIFT;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\t}",
"\t/*\n\t * Set 'VM_NORESERVE' if we should not account for the\n\t * memory use of this mapping.\n\t */\n\tif (flags & MAP_NORESERVE) {\n\t\t/* We honor MAP_NORESERVE if allowed to overcommit */\n\t\tif (sysctl_overcommit_memory != OVERCOMMIT_NEVER)\n\t\t\tvm_flags |= VM_NORESERVE;",
"\t\t/* hugetlb applies strict overcommit unless MAP_NORESERVE */\n\t\tif (file && is_file_hugepages(file))\n\t\t\tvm_flags |= VM_NORESERVE;\n\t}",
"\taddr = mmap_region(file, addr, len, vm_flags, pgoff, uf);\n\tif (!IS_ERR_VALUE(addr) &&\n\t ((vm_flags & VM_LOCKED) ||\n\t (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))\n\t\t*populate = len;\n\treturn addr;\n}",
"unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,\n\t\t\t unsigned long prot, unsigned long flags,\n\t\t\t unsigned long fd, unsigned long pgoff)\n{\n\tstruct file *file = NULL;\n\tunsigned long retval;",
"\tif (!(flags & MAP_ANONYMOUS)) {\n\t\taudit_mmap_fd(fd, flags);\n\t\tfile = fget(fd);\n\t\tif (!file)\n\t\t\treturn -EBADF;\n\t\tif (is_file_hugepages(file))\n\t\t\tlen = ALIGN(len, huge_page_size(hstate_file(file)));\n\t\tretval = -EINVAL;\n\t\tif (unlikely(flags & MAP_HUGETLB && !is_file_hugepages(file)))\n\t\t\tgoto out_fput;\n\t} else if (flags & MAP_HUGETLB) {\n\t\tstruct user_struct *user = NULL;\n\t\tstruct hstate *hs;",
"\t\ths = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);\n\t\tif (!hs)\n\t\t\treturn -EINVAL;",
"\t\tlen = ALIGN(len, huge_page_size(hs));\n\t\t/*\n\t\t * VM_NORESERVE is used because the reservations will be\n\t\t * taken when vm_ops->mmap() is called\n\t\t * A dummy user value is used because we are not locking\n\t\t * memory so no accounting is necessary\n\t\t */\n\t\tfile = hugetlb_file_setup(HUGETLB_ANON_FILE, len,\n\t\t\t\tVM_NORESERVE,\n\t\t\t\t&user, HUGETLB_ANONHUGE_INODE,\n\t\t\t\t(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);\n\t\tif (IS_ERR(file))\n\t\t\treturn PTR_ERR(file);\n\t}",
"\tflags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);",
"\tretval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);\nout_fput:\n\tif (file)\n\t\tfput(file);\n\treturn retval;\n}",
"SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,\n\t\tunsigned long, prot, unsigned long, flags,\n\t\tunsigned long, fd, unsigned long, pgoff)\n{\n\treturn ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);\n}",
"#ifdef __ARCH_WANT_SYS_OLD_MMAP\nstruct mmap_arg_struct {\n\tunsigned long addr;\n\tunsigned long len;\n\tunsigned long prot;\n\tunsigned long flags;\n\tunsigned long fd;\n\tunsigned long offset;\n};",
"SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)\n{\n\tstruct mmap_arg_struct a;",
"\tif (copy_from_user(&a, arg, sizeof(a)))\n\t\treturn -EFAULT;\n\tif (offset_in_page(a.offset))\n\t\treturn -EINVAL;",
"\treturn ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,\n\t\t\t a.offset >> PAGE_SHIFT);\n}\n#endif /* __ARCH_WANT_SYS_OLD_MMAP */",
"/*\n * Some shared mappigns will want the pages marked read-only\n * to track write events. If so, we'll downgrade vm_page_prot\n * to the private version (using protection_map[] without the\n * VM_SHARED bit).\n */\nint vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)\n{\n\tvm_flags_t vm_flags = vma->vm_flags;\n\tconst struct vm_operations_struct *vm_ops = vma->vm_ops;",
"\t/* If it was private or non-writable, the write bit is already clear */\n\tif ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))\n\t\treturn 0;",
"\t/* The backer wishes to know when pages are first written to? */\n\tif (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))\n\t\treturn 1;",
"\t/* The open routine did something to the protections that pgprot_modify\n\t * won't preserve? */\n\tif (pgprot_val(vm_page_prot) !=\n\t pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))\n\t\treturn 0;",
"\t/* Do we need to track softdirty? */\n\tif (IS_ENABLED(CONFIG_MEM_SOFT_DIRTY) && !(vm_flags & VM_SOFTDIRTY))\n\t\treturn 1;",
"\t/* Specialty mapping? */\n\tif (vm_flags & VM_PFNMAP)\n\t\treturn 0;",
"\t/* Can the mapping track the dirty pages? */\n\treturn vma->vm_file && vma->vm_file->f_mapping &&\n\t\tmapping_cap_account_dirty(vma->vm_file->f_mapping);\n}",
"/*\n * We account for memory if it's a private writeable mapping,\n * not hugepages and VM_NORESERVE wasn't set.\n */\nstatic inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)\n{\n\t/*\n\t * hugetlb has its own accounting separate from the core VM\n\t * VM_HUGETLB may not be set yet so we cannot check for that flag.\n\t */\n\tif (file && is_file_hugepages(file))\n\t\treturn 0;",
"\treturn (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;\n}",
"unsigned long mmap_region(struct file *file, unsigned long addr,\n\t\tunsigned long len, vm_flags_t vm_flags, unsigned long pgoff,\n\t\tstruct list_head *uf)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma, *prev;\n\tint error;\n\tstruct rb_node **rb_link, *rb_parent;\n\tunsigned long charged = 0;",
"\t/* Check against address space limit. */\n\tif (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {\n\t\tunsigned long nr_pages;",
"\t\t/*\n\t\t * MAP_FIXED may remove pages of mappings that intersects with\n\t\t * requested mapping. Account for the pages it would unmap.\n\t\t */\n\t\tnr_pages = count_vma_pages_range(mm, addr, addr + len);",
"\t\tif (!may_expand_vm(mm, vm_flags,\n\t\t\t\t\t(len >> PAGE_SHIFT) - nr_pages))\n\t\t\treturn -ENOMEM;\n\t}",
"\t/* Clear old maps */\n\twhile (find_vma_links(mm, addr, addr + len, &prev, &rb_link,\n\t\t\t &rb_parent)) {\n\t\tif (do_munmap(mm, addr, len, uf))\n\t\t\treturn -ENOMEM;\n\t}",
"\t/*\n\t * Private writable mapping: check memory availability\n\t */\n\tif (accountable_mapping(file, vm_flags)) {\n\t\tcharged = len >> PAGE_SHIFT;\n\t\tif (security_vm_enough_memory_mm(mm, charged))\n\t\t\treturn -ENOMEM;\n\t\tvm_flags |= VM_ACCOUNT;\n\t}",
"\t/*\n\t * Can we just expand an old mapping?\n\t */\n\tvma = vma_merge(mm, prev, addr, addr + len, vm_flags,\n\t\t\tNULL, file, pgoff, NULL, NULL_VM_UFFD_CTX);\n\tif (vma)\n\t\tgoto out;",
"\t/*\n\t * Determine the object being mapped and call the appropriate\n\t * specific mapper. the address has already been validated, but\n\t * not unmapped, but the maps are removed from the list.\n\t */\n\tvma = vm_area_alloc(mm);\n\tif (!vma) {\n\t\terror = -ENOMEM;\n\t\tgoto unacct_error;\n\t}",
"\tvma->vm_start = addr;\n\tvma->vm_end = addr + len;\n\tvma->vm_flags = vm_flags;\n\tvma->vm_page_prot = vm_get_page_prot(vm_flags);\n\tvma->vm_pgoff = pgoff;",
"\tif (file) {\n\t\tif (vm_flags & VM_DENYWRITE) {\n\t\t\terror = deny_write_access(file);\n\t\t\tif (error)\n\t\t\t\tgoto free_vma;\n\t\t}\n\t\tif (vm_flags & VM_SHARED) {\n\t\t\terror = mapping_map_writable(file->f_mapping);\n\t\t\tif (error)\n\t\t\t\tgoto allow_write_and_free_vma;\n\t\t}",
"\t\t/* ->mmap() can change vma->vm_file, but must guarantee that\n\t\t * vma_link() below can deny write-access if VM_DENYWRITE is set\n\t\t * and map writably if VM_SHARED is set. This usually means the\n\t\t * new file must not have been exposed to user-space, yet.\n\t\t */\n\t\tvma->vm_file = get_file(file);\n\t\terror = call_mmap(file, vma);\n\t\tif (error)\n\t\t\tgoto unmap_and_free_vma;",
"\t\t/* Can addr have changed??\n\t\t *\n\t\t * Answer: Yes, several device drivers can do it in their\n\t\t * f_op->mmap method. -DaveM\n\t\t * Bug: If addr is changed, prev, rb_link, rb_parent should\n\t\t * be updated for vma_link()\n\t\t */\n\t\tWARN_ON_ONCE(addr != vma->vm_start);",
"\t\taddr = vma->vm_start;\n\t\tvm_flags = vma->vm_flags;\n\t} else if (vm_flags & VM_SHARED) {\n\t\terror = shmem_zero_setup(vma);\n\t\tif (error)\n\t\t\tgoto free_vma;\n\t} else {\n\t\tvma_set_anonymous(vma);\n\t}",
"\tvma_link(mm, vma, prev, rb_link, rb_parent);\n\t/* Once vma denies write, undo our temporary denial count */\n\tif (file) {\n\t\tif (vm_flags & VM_SHARED)\n\t\t\tmapping_unmap_writable(file->f_mapping);\n\t\tif (vm_flags & VM_DENYWRITE)\n\t\t\tallow_write_access(file);\n\t}\n\tfile = vma->vm_file;\nout:\n\tperf_event_mmap(vma);",
"\tvm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);\n\tif (vm_flags & VM_LOCKED) {\n\t\tif ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||\n\t\t\t\t\tis_vm_hugetlb_page(vma) ||\n\t\t\t\t\tvma == get_gate_vma(current->mm))\n\t\t\tvma->vm_flags &= VM_LOCKED_CLEAR_MASK;\n\t\telse\n\t\t\tmm->locked_vm += (len >> PAGE_SHIFT);\n\t}",
"\tif (file)\n\t\tuprobe_mmap(vma);",
"\t/*\n\t * New (or expanded) vma always get soft dirty status.\n\t * Otherwise user-space soft-dirty page tracker won't\n\t * be able to distinguish situation when vma area unmapped,\n\t * then new mapped in-place (which must be aimed as\n\t * a completely new data area).\n\t */\n\tvma->vm_flags |= VM_SOFTDIRTY;",
"\tvma_set_page_prot(vma);",
"\treturn addr;",
"unmap_and_free_vma:\n\tvma->vm_file = NULL;\n\tfput(file);",
"\t/* Undo any partial mapping done by a device driver. */\n\tunmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);\n\tcharged = 0;\n\tif (vm_flags & VM_SHARED)\n\t\tmapping_unmap_writable(file->f_mapping);\nallow_write_and_free_vma:\n\tif (vm_flags & VM_DENYWRITE)\n\t\tallow_write_access(file);\nfree_vma:\n\tvm_area_free(vma);\nunacct_error:\n\tif (charged)\n\t\tvm_unacct_memory(charged);\n\treturn error;\n}",
"unsigned long unmapped_area(struct vm_unmapped_area_info *info)\n{\n\t/*\n\t * We implement the search by looking for an rbtree node that\n\t * immediately follows a suitable gap. That is,\n\t * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;\n\t * - gap_end = vma->vm_start >= info->low_limit + length;\n\t * - gap_end - gap_start >= length\n\t */",
"\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tunsigned long length, low_limit, high_limit, gap_start, gap_end;",
"\t/* Adjust search length to account for worst case alignment overhead */\n\tlength = info->length + info->align_mask;\n\tif (length < info->length)\n\t\treturn -ENOMEM;",
"\t/* Adjust search limits by the desired length */\n\tif (info->high_limit < length)\n\t\treturn -ENOMEM;\n\thigh_limit = info->high_limit - length;",
"\tif (info->low_limit > high_limit)\n\t\treturn -ENOMEM;\n\tlow_limit = info->low_limit + length;",
"\t/* Check if rbtree root looks promising */\n\tif (RB_EMPTY_ROOT(&mm->mm_rb))\n\t\tgoto check_highest;\n\tvma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);\n\tif (vma->rb_subtree_gap < length)\n\t\tgoto check_highest;",
"\twhile (true) {\n\t\t/* Visit left subtree if it looks promising */\n\t\tgap_end = vm_start_gap(vma);\n\t\tif (gap_end >= low_limit && vma->vm_rb.rb_left) {\n\t\t\tstruct vm_area_struct *left =\n\t\t\t\trb_entry(vma->vm_rb.rb_left,\n\t\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (left->rb_subtree_gap >= length) {\n\t\t\t\tvma = left;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}",
"\t\tgap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;\ncheck_current:\n\t\t/* Check if current node has a suitable gap */\n\t\tif (gap_start > high_limit)\n\t\t\treturn -ENOMEM;\n\t\tif (gap_end >= low_limit &&\n\t\t gap_end > gap_start && gap_end - gap_start >= length)\n\t\t\tgoto found;",
"\t\t/* Visit right subtree if it looks promising */\n\t\tif (vma->vm_rb.rb_right) {\n\t\t\tstruct vm_area_struct *right =\n\t\t\t\trb_entry(vma->vm_rb.rb_right,\n\t\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (right->rb_subtree_gap >= length) {\n\t\t\t\tvma = right;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}",
"\t\t/* Go back up the rbtree to find next candidate node */\n\t\twhile (true) {\n\t\t\tstruct rb_node *prev = &vma->vm_rb;\n\t\t\tif (!rb_parent(prev))\n\t\t\t\tgoto check_highest;\n\t\t\tvma = rb_entry(rb_parent(prev),\n\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (prev == vma->vm_rb.rb_left) {\n\t\t\t\tgap_start = vm_end_gap(vma->vm_prev);\n\t\t\t\tgap_end = vm_start_gap(vma);\n\t\t\t\tgoto check_current;\n\t\t\t}\n\t\t}\n\t}",
"check_highest:\n\t/* Check highest gap, which does not precede any rbtree node */\n\tgap_start = mm->highest_vm_end;\n\tgap_end = ULONG_MAX; /* Only for VM_BUG_ON below */\n\tif (gap_start > high_limit)\n\t\treturn -ENOMEM;",
"found:\n\t/* We found a suitable gap. Clip it with the original low_limit. */\n\tif (gap_start < info->low_limit)\n\t\tgap_start = info->low_limit;",
"\t/* Adjust gap address to the desired alignment */\n\tgap_start += (info->align_offset - gap_start) & info->align_mask;",
"\tVM_BUG_ON(gap_start + info->length > info->high_limit);\n\tVM_BUG_ON(gap_start + info->length > gap_end);\n\treturn gap_start;\n}",
"unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tunsigned long length, low_limit, high_limit, gap_start, gap_end;",
"\t/* Adjust search length to account for worst case alignment overhead */\n\tlength = info->length + info->align_mask;\n\tif (length < info->length)\n\t\treturn -ENOMEM;",
"\t/*\n\t * Adjust search limits by the desired length.\n\t * See implementation comment at top of unmapped_area().\n\t */\n\tgap_end = info->high_limit;\n\tif (gap_end < length)\n\t\treturn -ENOMEM;\n\thigh_limit = gap_end - length;",
"\tif (info->low_limit > high_limit)\n\t\treturn -ENOMEM;\n\tlow_limit = info->low_limit + length;",
"\t/* Check highest gap, which does not precede any rbtree node */\n\tgap_start = mm->highest_vm_end;\n\tif (gap_start <= high_limit)\n\t\tgoto found_highest;",
"\t/* Check if rbtree root looks promising */\n\tif (RB_EMPTY_ROOT(&mm->mm_rb))\n\t\treturn -ENOMEM;\n\tvma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);\n\tif (vma->rb_subtree_gap < length)\n\t\treturn -ENOMEM;",
"\twhile (true) {\n\t\t/* Visit right subtree if it looks promising */\n\t\tgap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;\n\t\tif (gap_start <= high_limit && vma->vm_rb.rb_right) {\n\t\t\tstruct vm_area_struct *right =\n\t\t\t\trb_entry(vma->vm_rb.rb_right,\n\t\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (right->rb_subtree_gap >= length) {\n\t\t\t\tvma = right;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}",
"check_current:\n\t\t/* Check if current node has a suitable gap */\n\t\tgap_end = vm_start_gap(vma);\n\t\tif (gap_end < low_limit)\n\t\t\treturn -ENOMEM;\n\t\tif (gap_start <= high_limit &&\n\t\t gap_end > gap_start && gap_end - gap_start >= length)\n\t\t\tgoto found;",
"\t\t/* Visit left subtree if it looks promising */\n\t\tif (vma->vm_rb.rb_left) {\n\t\t\tstruct vm_area_struct *left =\n\t\t\t\trb_entry(vma->vm_rb.rb_left,\n\t\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (left->rb_subtree_gap >= length) {\n\t\t\t\tvma = left;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}",
"\t\t/* Go back up the rbtree to find next candidate node */\n\t\twhile (true) {\n\t\t\tstruct rb_node *prev = &vma->vm_rb;\n\t\t\tif (!rb_parent(prev))\n\t\t\t\treturn -ENOMEM;\n\t\t\tvma = rb_entry(rb_parent(prev),\n\t\t\t\t struct vm_area_struct, vm_rb);\n\t\t\tif (prev == vma->vm_rb.rb_right) {\n\t\t\t\tgap_start = vma->vm_prev ?\n\t\t\t\t\tvm_end_gap(vma->vm_prev) : 0;\n\t\t\t\tgoto check_current;\n\t\t\t}\n\t\t}\n\t}",
"found:\n\t/* We found a suitable gap. Clip it with the original high_limit. */\n\tif (gap_end > info->high_limit)\n\t\tgap_end = info->high_limit;",
"found_highest:\n\t/* Compute highest gap address at the desired alignment */\n\tgap_end -= info->length;\n\tgap_end -= (gap_end - info->align_offset) & info->align_mask;",
"\tVM_BUG_ON(gap_end < info->low_limit);\n\tVM_BUG_ON(gap_end < gap_start);\n\treturn gap_end;\n}",
"\n#ifndef arch_get_mmap_end\n#define arch_get_mmap_end(addr)\t(TASK_SIZE)\n#endif",
"#ifndef arch_get_mmap_base\n#define arch_get_mmap_base(addr, base) (base)\n#endif",
"/* Get an address range which is currently unmapped.\n * For shmat() with addr=0.\n *\n * Ugly calling convention alert:\n * Return value with the low bits set means error value,\n * ie\n *\tif (ret & ~PAGE_MASK)\n *\t\terror = ret;\n *\n * This function \"knows\" that -ENOMEM has the bits set.\n */\n#ifndef HAVE_ARCH_UNMAPPED_AREA\nunsigned long\narch_get_unmapped_area(struct file *filp, unsigned long addr,\n\t\tunsigned long len, unsigned long pgoff, unsigned long flags)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma, *prev;\n\tstruct vm_unmapped_area_info info;\n\tconst unsigned long mmap_end = arch_get_mmap_end(addr);",
"\tif (len > mmap_end - mmap_min_addr)\n\t\treturn -ENOMEM;",
"\tif (flags & MAP_FIXED)\n\t\treturn addr;",
"\tif (addr) {\n\t\taddr = PAGE_ALIGN(addr);\n\t\tvma = find_vma_prev(mm, addr, &prev);\n\t\tif (mmap_end - len >= addr && addr >= mmap_min_addr &&\n\t\t (!vma || addr + len <= vm_start_gap(vma)) &&\n\t\t (!prev || addr >= vm_end_gap(prev)))\n\t\t\treturn addr;\n\t}",
"\tinfo.flags = 0;\n\tinfo.length = len;\n\tinfo.low_limit = mm->mmap_base;\n\tinfo.high_limit = mmap_end;\n\tinfo.align_mask = 0;\n\treturn vm_unmapped_area(&info);\n}\n#endif",
"/*\n * This mmap-allocator allocates new areas top-down from below the\n * stack's low limit (the base):\n */\n#ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN\nunsigned long\narch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,\n\t\t\t const unsigned long len, const unsigned long pgoff,\n\t\t\t const unsigned long flags)\n{\n\tstruct vm_area_struct *vma, *prev;\n\tstruct mm_struct *mm = current->mm;\n\tunsigned long addr = addr0;\n\tstruct vm_unmapped_area_info info;\n\tconst unsigned long mmap_end = arch_get_mmap_end(addr);",
"\t/* requested length too big for entire address space */\n\tif (len > mmap_end - mmap_min_addr)\n\t\treturn -ENOMEM;",
"\tif (flags & MAP_FIXED)\n\t\treturn addr;",
"\t/* requesting a specific address */\n\tif (addr) {\n\t\taddr = PAGE_ALIGN(addr);\n\t\tvma = find_vma_prev(mm, addr, &prev);\n\t\tif (mmap_end - len >= addr && addr >= mmap_min_addr &&\n\t\t\t\t(!vma || addr + len <= vm_start_gap(vma)) &&\n\t\t\t\t(!prev || addr >= vm_end_gap(prev)))\n\t\t\treturn addr;\n\t}",
"\tinfo.flags = VM_UNMAPPED_AREA_TOPDOWN;\n\tinfo.length = len;\n\tinfo.low_limit = max(PAGE_SIZE, mmap_min_addr);\n\tinfo.high_limit = arch_get_mmap_base(addr, mm->mmap_base);\n\tinfo.align_mask = 0;\n\taddr = vm_unmapped_area(&info);",
"\t/*\n\t * A failed mmap() very likely causes application failure,\n\t * so fall back to the bottom-up function here. This scenario\n\t * can happen with large stack limits and large mmap()\n\t * allocations.\n\t */\n\tif (offset_in_page(addr)) {\n\t\tVM_BUG_ON(addr != -ENOMEM);\n\t\tinfo.flags = 0;\n\t\tinfo.low_limit = TASK_UNMAPPED_BASE;\n\t\tinfo.high_limit = mmap_end;\n\t\taddr = vm_unmapped_area(&info);\n\t}",
"\treturn addr;\n}\n#endif",
"unsigned long\nget_unmapped_area(struct file *file, unsigned long addr, unsigned long len,\n\t\tunsigned long pgoff, unsigned long flags)\n{\n\tunsigned long (*get_area)(struct file *, unsigned long,\n\t\t\t\t unsigned long, unsigned long, unsigned long);",
"\tunsigned long error = arch_mmap_check(addr, len, flags);\n\tif (error)\n\t\treturn error;",
"\t/* Careful about overflows.. */\n\tif (len > TASK_SIZE)\n\t\treturn -ENOMEM;",
"\tget_area = current->mm->get_unmapped_area;\n\tif (file) {\n\t\tif (file->f_op->get_unmapped_area)\n\t\t\tget_area = file->f_op->get_unmapped_area;\n\t} else if (flags & MAP_SHARED) {\n\t\t/*\n\t\t * mmap_region() will call shmem_zero_setup() to create a file,\n\t\t * so use shmem's get_unmapped_area in case it can be huge.\n\t\t * do_mmap_pgoff() will clear pgoff, so match alignment.\n\t\t */\n\t\tpgoff = 0;\n\t\tget_area = shmem_get_unmapped_area;\n\t}",
"\taddr = get_area(file, addr, len, pgoff, flags);\n\tif (IS_ERR_VALUE(addr))\n\t\treturn addr;",
"\tif (addr > TASK_SIZE - len)\n\t\treturn -ENOMEM;\n\tif (offset_in_page(addr))\n\t\treturn -EINVAL;",
"\terror = security_mmap_addr(addr);\n\treturn error ? error : addr;\n}",
"EXPORT_SYMBOL(get_unmapped_area);",
"/* Look up the first VMA which satisfies addr < vm_end, NULL if none. */\nstruct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)\n{\n\tstruct rb_node *rb_node;\n\tstruct vm_area_struct *vma;",
"\t/* Check the cache first. */\n\tvma = vmacache_find(mm, addr);\n\tif (likely(vma))\n\t\treturn vma;",
"\trb_node = mm->mm_rb.rb_node;",
"\twhile (rb_node) {\n\t\tstruct vm_area_struct *tmp;",
"\t\ttmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);",
"\t\tif (tmp->vm_end > addr) {\n\t\t\tvma = tmp;\n\t\t\tif (tmp->vm_start <= addr)\n\t\t\t\tbreak;\n\t\t\trb_node = rb_node->rb_left;\n\t\t} else\n\t\t\trb_node = rb_node->rb_right;\n\t}",
"\tif (vma)\n\t\tvmacache_update(addr, vma);\n\treturn vma;\n}",
"EXPORT_SYMBOL(find_vma);",
"/*\n * Same as find_vma, but also return a pointer to the previous VMA in *pprev.\n */\nstruct vm_area_struct *\nfind_vma_prev(struct mm_struct *mm, unsigned long addr,\n\t\t\tstruct vm_area_struct **pprev)\n{\n\tstruct vm_area_struct *vma;",
"\tvma = find_vma(mm, addr);\n\tif (vma) {\n\t\t*pprev = vma->vm_prev;\n\t} else {\n\t\tstruct rb_node *rb_node = mm->mm_rb.rb_node;\n\t\t*pprev = NULL;\n\t\twhile (rb_node) {\n\t\t\t*pprev = rb_entry(rb_node, struct vm_area_struct, vm_rb);\n\t\t\trb_node = rb_node->rb_right;\n\t\t}\n\t}\n\treturn vma;\n}",
"/*\n * Verify that the stack growth is acceptable and\n * update accounting. This is shared with both the\n * grow-up and grow-down cases.\n */\nstatic int acct_stack_growth(struct vm_area_struct *vma,\n\t\t\t unsigned long size, unsigned long grow)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tunsigned long new_start;",
"\t/* address space limit tests */\n\tif (!may_expand_vm(mm, vma->vm_flags, grow))\n\t\treturn -ENOMEM;",
"\t/* Stack limit test */\n\tif (size > rlimit(RLIMIT_STACK))\n\t\treturn -ENOMEM;",
"\t/* mlock limit tests */\n\tif (vma->vm_flags & VM_LOCKED) {\n\t\tunsigned long locked;\n\t\tunsigned long limit;\n\t\tlocked = mm->locked_vm + grow;\n\t\tlimit = rlimit(RLIMIT_MEMLOCK);\n\t\tlimit >>= PAGE_SHIFT;\n\t\tif (locked > limit && !capable(CAP_IPC_LOCK))\n\t\t\treturn -ENOMEM;\n\t}",
"\t/* Check to ensure the stack will not grow into a hugetlb-only region */\n\tnew_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :\n\t\t\tvma->vm_end - size;\n\tif (is_hugepage_only_range(vma->vm_mm, new_start, size))\n\t\treturn -EFAULT;",
"\t/*\n\t * Overcommit.. This must be the final test, as it will\n\t * update security statistics.\n\t */\n\tif (security_vm_enough_memory_mm(mm, grow))\n\t\treturn -ENOMEM;",
"\treturn 0;\n}",
"#if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)\n/*\n * PA-RISC uses this for its stack; IA64 for its Register Backing Store.\n * vma is the last one with address > vma->vm_end. Have to extend vma.\n */\nint expand_upwards(struct vm_area_struct *vma, unsigned long address)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tstruct vm_area_struct *next;\n\tunsigned long gap_addr;\n\tint error = 0;",
"\tif (!(vma->vm_flags & VM_GROWSUP))\n\t\treturn -EFAULT;",
"\t/* Guard against exceeding limits of the address space. */\n\taddress &= PAGE_MASK;\n\tif (address >= (TASK_SIZE & PAGE_MASK))\n\t\treturn -ENOMEM;\n\taddress += PAGE_SIZE;",
"\t/* Enforce stack_guard_gap */\n\tgap_addr = address + stack_guard_gap;",
"\t/* Guard against overflow */\n\tif (gap_addr < address || gap_addr > TASK_SIZE)\n\t\tgap_addr = TASK_SIZE;",
"\tnext = vma->vm_next;\n\tif (next && next->vm_start < gap_addr &&\n\t\t\t(next->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {\n\t\tif (!(next->vm_flags & VM_GROWSUP))\n\t\t\treturn -ENOMEM;\n\t\t/* Check that both stack segments have the same anon_vma? */\n\t}",
"\t/* We must make sure the anon_vma is allocated. */\n\tif (unlikely(anon_vma_prepare(vma)))\n\t\treturn -ENOMEM;",
"\t/*\n\t * vma->vm_start/vm_end cannot change under us because the caller\n\t * is required to hold the mmap_sem in read mode. We need the\n\t * anon_vma lock to serialize against concurrent expand_stacks.\n\t */\n\tanon_vma_lock_write(vma->anon_vma);",
"\t/* Somebody else might have raced and expanded it already */\n\tif (address > vma->vm_end) {\n\t\tunsigned long size, grow;",
"\t\tsize = address - vma->vm_start;\n\t\tgrow = (address - vma->vm_end) >> PAGE_SHIFT;",
"\t\terror = -ENOMEM;\n\t\tif (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {\n\t\t\terror = acct_stack_growth(vma, size, grow);\n\t\t\tif (!error) {\n\t\t\t\t/*\n\t\t\t\t * vma_gap_update() doesn't support concurrent\n\t\t\t\t * updates, but we only hold a shared mmap_sem\n\t\t\t\t * lock here, so we need to protect against\n\t\t\t\t * concurrent vma expansions.\n\t\t\t\t * anon_vma_lock_write() doesn't help here, as\n\t\t\t\t * we don't guarantee that all growable vmas\n\t\t\t\t * in a mm share the same root anon vma.\n\t\t\t\t * So, we reuse mm->page_table_lock to guard\n\t\t\t\t * against concurrent vma expansions.\n\t\t\t\t */\n\t\t\t\tspin_lock(&mm->page_table_lock);\n\t\t\t\tif (vma->vm_flags & VM_LOCKED)\n\t\t\t\t\tmm->locked_vm += grow;\n\t\t\t\tvm_stat_account(mm, vma->vm_flags, grow);\n\t\t\t\tanon_vma_interval_tree_pre_update_vma(vma);\n\t\t\t\tvma->vm_end = address;\n\t\t\t\tanon_vma_interval_tree_post_update_vma(vma);\n\t\t\t\tif (vma->vm_next)\n\t\t\t\t\tvma_gap_update(vma->vm_next);\n\t\t\t\telse\n\t\t\t\t\tmm->highest_vm_end = vm_end_gap(vma);\n\t\t\t\tspin_unlock(&mm->page_table_lock);",
"\t\t\t\tperf_event_mmap(vma);\n\t\t\t}\n\t\t}\n\t}\n\tanon_vma_unlock_write(vma->anon_vma);\n\tkhugepaged_enter_vma_merge(vma, vma->vm_flags);\n\tvalidate_mm(mm);\n\treturn error;\n}\n#endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */",
"/*\n * vma is the first one with address < vma->vm_start. Have to extend vma.\n */\nint expand_downwards(struct vm_area_struct *vma,\n\t\t\t\t unsigned long address)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tstruct vm_area_struct *prev;",
"\tint error = 0;",
"\n\taddress &= PAGE_MASK;",
"\tif (address < mmap_min_addr)\n\t\treturn -EPERM;",
"\n\t/* Enforce stack_guard_gap */\n\tprev = vma->vm_prev;\n\t/* Check that both stack segments have the same anon_vma? */\n\tif (prev && !(prev->vm_flags & VM_GROWSDOWN) &&\n\t\t\t(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {\n\t\tif (address - prev->vm_end < stack_guard_gap)\n\t\t\treturn -ENOMEM;\n\t}",
"\t/* We must make sure the anon_vma is allocated. */\n\tif (unlikely(anon_vma_prepare(vma)))\n\t\treturn -ENOMEM;",
"\t/*\n\t * vma->vm_start/vm_end cannot change under us because the caller\n\t * is required to hold the mmap_sem in read mode. We need the\n\t * anon_vma lock to serialize against concurrent expand_stacks.\n\t */\n\tanon_vma_lock_write(vma->anon_vma);",
"\t/* Somebody else might have raced and expanded it already */\n\tif (address < vma->vm_start) {\n\t\tunsigned long size, grow;",
"\t\tsize = vma->vm_end - address;\n\t\tgrow = (vma->vm_start - address) >> PAGE_SHIFT;",
"\t\terror = -ENOMEM;\n\t\tif (grow <= vma->vm_pgoff) {\n\t\t\terror = acct_stack_growth(vma, size, grow);\n\t\t\tif (!error) {\n\t\t\t\t/*\n\t\t\t\t * vma_gap_update() doesn't support concurrent\n\t\t\t\t * updates, but we only hold a shared mmap_sem\n\t\t\t\t * lock here, so we need to protect against\n\t\t\t\t * concurrent vma expansions.\n\t\t\t\t * anon_vma_lock_write() doesn't help here, as\n\t\t\t\t * we don't guarantee that all growable vmas\n\t\t\t\t * in a mm share the same root anon vma.\n\t\t\t\t * So, we reuse mm->page_table_lock to guard\n\t\t\t\t * against concurrent vma expansions.\n\t\t\t\t */\n\t\t\t\tspin_lock(&mm->page_table_lock);\n\t\t\t\tif (vma->vm_flags & VM_LOCKED)\n\t\t\t\t\tmm->locked_vm += grow;\n\t\t\t\tvm_stat_account(mm, vma->vm_flags, grow);\n\t\t\t\tanon_vma_interval_tree_pre_update_vma(vma);\n\t\t\t\tvma->vm_start = address;\n\t\t\t\tvma->vm_pgoff -= grow;\n\t\t\t\tanon_vma_interval_tree_post_update_vma(vma);\n\t\t\t\tvma_gap_update(vma);\n\t\t\t\tspin_unlock(&mm->page_table_lock);",
"\t\t\t\tperf_event_mmap(vma);\n\t\t\t}\n\t\t}\n\t}\n\tanon_vma_unlock_write(vma->anon_vma);\n\tkhugepaged_enter_vma_merge(vma, vma->vm_flags);\n\tvalidate_mm(mm);\n\treturn error;\n}",
"/* enforced gap between the expanding stack and other mappings. */\nunsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;",
"static int __init cmdline_parse_stack_guard_gap(char *p)\n{\n\tunsigned long val;\n\tchar *endptr;",
"\tval = simple_strtoul(p, &endptr, 10);\n\tif (!*endptr)\n\t\tstack_guard_gap = val << PAGE_SHIFT;",
"\treturn 0;\n}\n__setup(\"stack_guard_gap=\", cmdline_parse_stack_guard_gap);",
"#ifdef CONFIG_STACK_GROWSUP\nint expand_stack(struct vm_area_struct *vma, unsigned long address)\n{\n\treturn expand_upwards(vma, address);\n}",
"struct vm_area_struct *\nfind_extend_vma(struct mm_struct *mm, unsigned long addr)\n{\n\tstruct vm_area_struct *vma, *prev;",
"\taddr &= PAGE_MASK;\n\tvma = find_vma_prev(mm, addr, &prev);\n\tif (vma && (vma->vm_start <= addr))\n\t\treturn vma;\n\tif (!prev || expand_stack(prev, addr))\n\t\treturn NULL;\n\tif (prev->vm_flags & VM_LOCKED)\n\t\tpopulate_vma_page_range(prev, addr, prev->vm_end, NULL);\n\treturn prev;\n}\n#else\nint expand_stack(struct vm_area_struct *vma, unsigned long address)\n{\n\treturn expand_downwards(vma, address);\n}",
"struct vm_area_struct *\nfind_extend_vma(struct mm_struct *mm, unsigned long addr)\n{\n\tstruct vm_area_struct *vma;\n\tunsigned long start;",
"\taddr &= PAGE_MASK;\n\tvma = find_vma(mm, addr);\n\tif (!vma)\n\t\treturn NULL;\n\tif (vma->vm_start <= addr)\n\t\treturn vma;\n\tif (!(vma->vm_flags & VM_GROWSDOWN))\n\t\treturn NULL;\n\tstart = vma->vm_start;\n\tif (expand_stack(vma, addr))\n\t\treturn NULL;\n\tif (vma->vm_flags & VM_LOCKED)\n\t\tpopulate_vma_page_range(vma, addr, start, NULL);\n\treturn vma;\n}\n#endif",
"EXPORT_SYMBOL_GPL(find_extend_vma);",
"/*\n * Ok - we have the memory areas we should free on the vma list,\n * so release them, and do the vma updates.\n *\n * Called with the mm semaphore held.\n */\nstatic void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)\n{\n\tunsigned long nr_accounted = 0;",
"\t/* Update high watermark before we lower total_vm */\n\tupdate_hiwater_vm(mm);\n\tdo {\n\t\tlong nrpages = vma_pages(vma);",
"\t\tif (vma->vm_flags & VM_ACCOUNT)\n\t\t\tnr_accounted += nrpages;\n\t\tvm_stat_account(mm, vma->vm_flags, -nrpages);\n\t\tvma = remove_vma(vma);\n\t} while (vma);\n\tvm_unacct_memory(nr_accounted);\n\tvalidate_mm(mm);\n}",
"/*\n * Get rid of page table information in the indicated region.\n *\n * Called with the mm semaphore held.\n */\nstatic void unmap_region(struct mm_struct *mm,\n\t\tstruct vm_area_struct *vma, struct vm_area_struct *prev,\n\t\tunsigned long start, unsigned long end)\n{\n\tstruct vm_area_struct *next = prev ? prev->vm_next : mm->mmap;\n\tstruct mmu_gather tlb;",
"\tlru_add_drain();\n\ttlb_gather_mmu(&tlb, mm, start, end);\n\tupdate_hiwater_rss(mm);\n\tunmap_vmas(&tlb, vma, start, end);\n\tfree_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,\n\t\t\t\t next ? next->vm_start : USER_PGTABLES_CEILING);\n\ttlb_finish_mmu(&tlb, start, end);\n}",
"/*\n * Create a list of vma's touched by the unmap, removing them from the mm's\n * vma list as we go..\n */\nstatic void\ndetach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,\n\tstruct vm_area_struct *prev, unsigned long end)\n{\n\tstruct vm_area_struct **insertion_point;\n\tstruct vm_area_struct *tail_vma = NULL;",
"\tinsertion_point = (prev ? &prev->vm_next : &mm->mmap);\n\tvma->vm_prev = NULL;\n\tdo {\n\t\tvma_rb_erase(vma, &mm->mm_rb);\n\t\tmm->map_count--;\n\t\ttail_vma = vma;\n\t\tvma = vma->vm_next;\n\t} while (vma && vma->vm_start < end);\n\t*insertion_point = vma;\n\tif (vma) {\n\t\tvma->vm_prev = prev;\n\t\tvma_gap_update(vma);\n\t} else\n\t\tmm->highest_vm_end = prev ? vm_end_gap(prev) : 0;\n\ttail_vma->vm_next = NULL;",
"\t/* Kill the cache */\n\tvmacache_invalidate(mm);\n}",
"/*\n * __split_vma() bypasses sysctl_max_map_count checking. We use this where it\n * has already been checked or doesn't make sense to fail.\n */\nint __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,\n\t\tunsigned long addr, int new_below)\n{\n\tstruct vm_area_struct *new;\n\tint err;",
"\tif (vma->vm_ops && vma->vm_ops->split) {\n\t\terr = vma->vm_ops->split(vma, addr);\n\t\tif (err)\n\t\t\treturn err;\n\t}",
"\tnew = vm_area_dup(vma);\n\tif (!new)\n\t\treturn -ENOMEM;",
"\tif (new_below)\n\t\tnew->vm_end = addr;\n\telse {\n\t\tnew->vm_start = addr;\n\t\tnew->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);\n\t}",
"\terr = vma_dup_policy(vma, new);\n\tif (err)\n\t\tgoto out_free_vma;",
"\terr = anon_vma_clone(new, vma);\n\tif (err)\n\t\tgoto out_free_mpol;",
"\tif (new->vm_file)\n\t\tget_file(new->vm_file);",
"\tif (new->vm_ops && new->vm_ops->open)\n\t\tnew->vm_ops->open(new);",
"\tif (new_below)\n\t\terr = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +\n\t\t\t((addr - new->vm_start) >> PAGE_SHIFT), new);\n\telse\n\t\terr = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);",
"\t/* Success. */\n\tif (!err)\n\t\treturn 0;",
"\t/* Clean everything up if vma_adjust failed. */\n\tif (new->vm_ops && new->vm_ops->close)\n\t\tnew->vm_ops->close(new);\n\tif (new->vm_file)\n\t\tfput(new->vm_file);\n\tunlink_anon_vmas(new);\n out_free_mpol:\n\tmpol_put(vma_policy(new));\n out_free_vma:\n\tvm_area_free(new);\n\treturn err;\n}",
"/*\n * Split a vma into two pieces at address 'addr', a new vma is allocated\n * either for the first part or the tail.\n */\nint split_vma(struct mm_struct *mm, struct vm_area_struct *vma,\n\t unsigned long addr, int new_below)\n{\n\tif (mm->map_count >= sysctl_max_map_count)\n\t\treturn -ENOMEM;",
"\treturn __split_vma(mm, vma, addr, new_below);\n}",
"/* Munmap is split into 2 main parts -- this part which finds\n * what needs doing, and the areas themselves, which do the\n * work. This now handles partial unmappings.\n * Jeremy Fitzhardinge <jeremy@goop.org>\n */\nint __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,\n\t\tstruct list_head *uf, bool downgrade)\n{\n\tunsigned long end;\n\tstruct vm_area_struct *vma, *prev, *last;",
"\tif ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)\n\t\treturn -EINVAL;",
"\tlen = PAGE_ALIGN(len);\n\tif (len == 0)\n\t\treturn -EINVAL;",
"\t/* Find the first overlapping VMA */\n\tvma = find_vma(mm, start);\n\tif (!vma)\n\t\treturn 0;\n\tprev = vma->vm_prev;\n\t/* we have start < vma->vm_end */",
"\t/* if it doesn't overlap, we have nothing.. */\n\tend = start + len;\n\tif (vma->vm_start >= end)\n\t\treturn 0;",
"\t/*\n\t * If we need to split any vma, do it now to save pain later.\n\t *\n\t * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially\n\t * unmapped vm_area_struct will remain in use: so lower split_vma\n\t * places tmp vma above, and higher split_vma places tmp vma below.\n\t */\n\tif (start > vma->vm_start) {\n\t\tint error;",
"\t\t/*\n\t\t * Make sure that map_count on return from munmap() will\n\t\t * not exceed its limit; but let map_count go just above\n\t\t * its limit temporarily, to help free resources as expected.\n\t\t */\n\t\tif (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)\n\t\t\treturn -ENOMEM;",
"\t\terror = __split_vma(mm, vma, start, 0);\n\t\tif (error)\n\t\t\treturn error;\n\t\tprev = vma;\n\t}",
"\t/* Does it split the last one? */\n\tlast = find_vma(mm, end);\n\tif (last && end > last->vm_start) {\n\t\tint error = __split_vma(mm, last, end, 1);\n\t\tif (error)\n\t\t\treturn error;\n\t}\n\tvma = prev ? prev->vm_next : mm->mmap;",
"\tif (unlikely(uf)) {\n\t\t/*\n\t\t * If userfaultfd_unmap_prep returns an error the vmas\n\t\t * will remain splitted, but userland will get a\n\t\t * highly unexpected error anyway. This is no\n\t\t * different than the case where the first of the two\n\t\t * __split_vma fails, but we don't undo the first\n\t\t * split, despite we could. This is unlikely enough\n\t\t * failure that it's not worth optimizing it for.\n\t\t */\n\t\tint error = userfaultfd_unmap_prep(vma, start, end, uf);\n\t\tif (error)\n\t\t\treturn error;\n\t}",
"\t/*\n\t * unlock any mlock()ed ranges before detaching vmas\n\t */\n\tif (mm->locked_vm) {\n\t\tstruct vm_area_struct *tmp = vma;\n\t\twhile (tmp && tmp->vm_start < end) {\n\t\t\tif (tmp->vm_flags & VM_LOCKED) {\n\t\t\t\tmm->locked_vm -= vma_pages(tmp);\n\t\t\t\tmunlock_vma_pages_all(tmp);\n\t\t\t}",
"\t\t\ttmp = tmp->vm_next;\n\t\t}\n\t}",
"\t/* Detach vmas from rbtree */\n\tdetach_vmas_to_be_unmapped(mm, vma, prev, end);",
"\t/*\n\t * mpx unmap needs to be called with mmap_sem held for write.\n\t * It is safe to call it before unmap_region().\n\t */\n\tarch_unmap(mm, vma, start, end);",
"\tif (downgrade)\n\t\tdowngrade_write(&mm->mmap_sem);",
"\tunmap_region(mm, vma, prev, start, end);",
"\t/* Fix up all other VM information */\n\tremove_vma_list(mm, vma);",
"\treturn downgrade ? 1 : 0;\n}",
"int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,\n\t struct list_head *uf)\n{\n\treturn __do_munmap(mm, start, len, uf, false);\n}",
"static int __vm_munmap(unsigned long start, size_t len, bool downgrade)\n{\n\tint ret;\n\tstruct mm_struct *mm = current->mm;\n\tLIST_HEAD(uf);",
"\tif (down_write_killable(&mm->mmap_sem))\n\t\treturn -EINTR;",
"\tret = __do_munmap(mm, start, len, &uf, downgrade);\n\t/*\n\t * Returning 1 indicates mmap_sem is downgraded.\n\t * But 1 is not legal return value of vm_munmap() and munmap(), reset\n\t * it to 0 before return.\n\t */\n\tif (ret == 1) {\n\t\tup_read(&mm->mmap_sem);\n\t\tret = 0;\n\t} else\n\t\tup_write(&mm->mmap_sem);",
"\tuserfaultfd_unmap_complete(mm, &uf);\n\treturn ret;\n}",
"int vm_munmap(unsigned long start, size_t len)\n{\n\treturn __vm_munmap(start, len, false);\n}\nEXPORT_SYMBOL(vm_munmap);",
"SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)\n{\n\tprofile_munmap(addr);\n\treturn __vm_munmap(addr, len, true);\n}",
"\n/*\n * Emulation of deprecated remap_file_pages() syscall.\n */\nSYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,\n\t\tunsigned long, prot, unsigned long, pgoff, unsigned long, flags)\n{",
"\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tunsigned long populate = 0;\n\tunsigned long ret = -EINVAL;\n\tstruct file *file;",
"\tpr_warn_once(\"%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/vm/remap_file_pages.rst.\\n\",\n\t\t current->comm, current->pid);",
"\tif (prot)\n\t\treturn ret;\n\tstart = start & PAGE_MASK;\n\tsize = size & PAGE_MASK;",
"\tif (start + size <= start)\n\t\treturn ret;",
"\t/* Does pgoff wrap? */\n\tif (pgoff + (size >> PAGE_SHIFT) < pgoff)\n\t\treturn ret;",
"\tif (down_write_killable(&mm->mmap_sem))\n\t\treturn -EINTR;",
"\tvma = find_vma(mm, start);",
"\tif (!vma || !(vma->vm_flags & VM_SHARED))\n\t\tgoto out;",
"\tif (start < vma->vm_start)\n\t\tgoto out;",
"\tif (start + size > vma->vm_end) {\n\t\tstruct vm_area_struct *next;",
"\t\tfor (next = vma->vm_next; next; next = next->vm_next) {\n\t\t\t/* hole between vmas ? */\n\t\t\tif (next->vm_start != next->vm_prev->vm_end)\n\t\t\t\tgoto out;",
"\t\t\tif (next->vm_file != vma->vm_file)\n\t\t\t\tgoto out;",
"\t\t\tif (next->vm_flags != vma->vm_flags)\n\t\t\t\tgoto out;",
"\t\t\tif (start + size <= next->vm_end)\n\t\t\t\tbreak;\n\t\t}",
"\t\tif (!next)\n\t\t\tgoto out;\n\t}",
"\tprot |= vma->vm_flags & VM_READ ? PROT_READ : 0;\n\tprot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;\n\tprot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;",
"\tflags &= MAP_NONBLOCK;\n\tflags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;\n\tif (vma->vm_flags & VM_LOCKED) {\n\t\tstruct vm_area_struct *tmp;\n\t\tflags |= MAP_LOCKED;",
"\t\t/* drop PG_Mlocked flag for over-mapped range */\n\t\tfor (tmp = vma; tmp->vm_start >= start + size;\n\t\t\t\ttmp = tmp->vm_next) {\n\t\t\t/*\n\t\t\t * Split pmd and munlock page on the border\n\t\t\t * of the range.\n\t\t\t */\n\t\t\tvma_adjust_trans_huge(tmp, start, start + size, 0);",
"\t\t\tmunlock_vma_pages_range(tmp,\n\t\t\t\t\tmax(tmp->vm_start, start),\n\t\t\t\t\tmin(tmp->vm_end, start + size));\n\t\t}\n\t}",
"\tfile = get_file(vma->vm_file);\n\tret = do_mmap_pgoff(vma->vm_file, start, size,\n\t\t\tprot, flags, pgoff, &populate, NULL);\n\tfput(file);\nout:\n\tup_write(&mm->mmap_sem);\n\tif (populate)\n\t\tmm_populate(ret, populate);\n\tif (!IS_ERR_VALUE(ret))\n\t\tret = 0;\n\treturn ret;\n}",
"/*\n * this is really a simplified \"do_mmap\". it only handles\n * anonymous maps. eventually we may be able to do some\n * brk-specific accounting here.\n */\nstatic int do_brk_flags(unsigned long addr, unsigned long len, unsigned long flags, struct list_head *uf)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma, *prev;\n\tstruct rb_node **rb_link, *rb_parent;\n\tpgoff_t pgoff = addr >> PAGE_SHIFT;\n\tint error;",
"\t/* Until we need other flags, refuse anything except VM_EXEC. */\n\tif ((flags & (~VM_EXEC)) != 0)\n\t\treturn -EINVAL;\n\tflags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;",
"\terror = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);\n\tif (offset_in_page(error))\n\t\treturn error;",
"\terror = mlock_future_check(mm, mm->def_flags, len);\n\tif (error)\n\t\treturn error;",
"\t/*\n\t * Clear old maps. this also does some error checking for us\n\t */\n\twhile (find_vma_links(mm, addr, addr + len, &prev, &rb_link,\n\t\t\t &rb_parent)) {\n\t\tif (do_munmap(mm, addr, len, uf))\n\t\t\treturn -ENOMEM;\n\t}",
"\t/* Check against address space limits *after* clearing old maps... */\n\tif (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))\n\t\treturn -ENOMEM;",
"\tif (mm->map_count > sysctl_max_map_count)\n\t\treturn -ENOMEM;",
"\tif (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))\n\t\treturn -ENOMEM;",
"\t/* Can we just expand an old private anonymous mapping? */\n\tvma = vma_merge(mm, prev, addr, addr + len, flags,\n\t\t\tNULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX);\n\tif (vma)\n\t\tgoto out;",
"\t/*\n\t * create a vma struct for an anonymous mapping\n\t */\n\tvma = vm_area_alloc(mm);\n\tif (!vma) {\n\t\tvm_unacct_memory(len >> PAGE_SHIFT);\n\t\treturn -ENOMEM;\n\t}",
"\tvma_set_anonymous(vma);\n\tvma->vm_start = addr;\n\tvma->vm_end = addr + len;\n\tvma->vm_pgoff = pgoff;\n\tvma->vm_flags = flags;\n\tvma->vm_page_prot = vm_get_page_prot(flags);\n\tvma_link(mm, vma, prev, rb_link, rb_parent);\nout:\n\tperf_event_mmap(vma);\n\tmm->total_vm += len >> PAGE_SHIFT;\n\tmm->data_vm += len >> PAGE_SHIFT;\n\tif (flags & VM_LOCKED)\n\t\tmm->locked_vm += (len >> PAGE_SHIFT);\n\tvma->vm_flags |= VM_SOFTDIRTY;\n\treturn 0;\n}",
"int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)\n{\n\tstruct mm_struct *mm = current->mm;\n\tunsigned long len;\n\tint ret;\n\tbool populate;\n\tLIST_HEAD(uf);",
"\tlen = PAGE_ALIGN(request);\n\tif (len < request)\n\t\treturn -ENOMEM;\n\tif (!len)\n\t\treturn 0;",
"\tif (down_write_killable(&mm->mmap_sem))\n\t\treturn -EINTR;",
"\tret = do_brk_flags(addr, len, flags, &uf);\n\tpopulate = ((mm->def_flags & VM_LOCKED) != 0);\n\tup_write(&mm->mmap_sem);\n\tuserfaultfd_unmap_complete(mm, &uf);\n\tif (populate && !ret)\n\t\tmm_populate(addr, len);\n\treturn ret;\n}\nEXPORT_SYMBOL(vm_brk_flags);",
"int vm_brk(unsigned long addr, unsigned long len)\n{\n\treturn vm_brk_flags(addr, len, 0);\n}\nEXPORT_SYMBOL(vm_brk);",
"/* Release all mmaps. */\nvoid exit_mmap(struct mm_struct *mm)\n{\n\tstruct mmu_gather tlb;\n\tstruct vm_area_struct *vma;\n\tunsigned long nr_accounted = 0;",
"\t/* mm's last user has gone, and its about to be pulled down */\n\tmmu_notifier_release(mm);",
"\tif (unlikely(mm_is_oom_victim(mm))) {\n\t\t/*\n\t\t * Manually reap the mm to free as much memory as possible.\n\t\t * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard\n\t\t * this mm from further consideration. Taking mm->mmap_sem for\n\t\t * write after setting MMF_OOM_SKIP will guarantee that the oom\n\t\t * reaper will not run on this mm again after mmap_sem is\n\t\t * dropped.\n\t\t *\n\t\t * Nothing can be holding mm->mmap_sem here and the above call\n\t\t * to mmu_notifier_release(mm) ensures mmu notifier callbacks in\n\t\t * __oom_reap_task_mm() will not block.\n\t\t *\n\t\t * This needs to be done before calling munlock_vma_pages_all(),\n\t\t * which clears VM_LOCKED, otherwise the oom reaper cannot\n\t\t * reliably test it.\n\t\t */\n\t\t(void)__oom_reap_task_mm(mm);",
"\t\tset_bit(MMF_OOM_SKIP, &mm->flags);\n\t\tdown_write(&mm->mmap_sem);\n\t\tup_write(&mm->mmap_sem);\n\t}",
"\tif (mm->locked_vm) {\n\t\tvma = mm->mmap;\n\t\twhile (vma) {\n\t\t\tif (vma->vm_flags & VM_LOCKED)\n\t\t\t\tmunlock_vma_pages_all(vma);\n\t\t\tvma = vma->vm_next;\n\t\t}\n\t}",
"\tarch_exit_mmap(mm);",
"\tvma = mm->mmap;\n\tif (!vma)\t/* Can happen if dup_mmap() received an OOM */\n\t\treturn;",
"\tlru_add_drain();\n\tflush_cache_mm(mm);\n\ttlb_gather_mmu(&tlb, mm, 0, -1);\n\t/* update_hiwater_rss(mm) here? but nobody should be looking */\n\t/* Use -1 here to ensure all VMAs in the mm are unmapped */\n\tunmap_vmas(&tlb, vma, 0, -1);\n\tfree_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);\n\ttlb_finish_mmu(&tlb, 0, -1);",
"\t/*\n\t * Walk the list again, actually closing and freeing it,\n\t * with preemption enabled, without holding any MM locks.\n\t */\n\twhile (vma) {\n\t\tif (vma->vm_flags & VM_ACCOUNT)\n\t\t\tnr_accounted += vma_pages(vma);\n\t\tvma = remove_vma(vma);\n\t}\n\tvm_unacct_memory(nr_accounted);\n}",
"/* Insert vm structure into process list sorted by address\n * and into the inode's i_mmap tree. If vm_file is non-NULL\n * then i_mmap_rwsem is taken here.\n */\nint insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)\n{\n\tstruct vm_area_struct *prev;\n\tstruct rb_node **rb_link, *rb_parent;",
"\tif (find_vma_links(mm, vma->vm_start, vma->vm_end,\n\t\t\t &prev, &rb_link, &rb_parent))\n\t\treturn -ENOMEM;\n\tif ((vma->vm_flags & VM_ACCOUNT) &&\n\t security_vm_enough_memory_mm(mm, vma_pages(vma)))\n\t\treturn -ENOMEM;",
"\t/*\n\t * The vm_pgoff of a purely anonymous vma should be irrelevant\n\t * until its first write fault, when page's anon_vma and index\n\t * are set. But now set the vm_pgoff it will almost certainly\n\t * end up with (unless mremap moves it elsewhere before that\n\t * first wfault), so /proc/pid/maps tells a consistent story.\n\t *\n\t * By setting it to reflect the virtual start address of the\n\t * vma, merges and splits can happen in a seamless way, just\n\t * using the existing file pgoff checks and manipulations.\n\t * Similarly in do_mmap_pgoff and in do_brk.\n\t */\n\tif (vma_is_anonymous(vma)) {\n\t\tBUG_ON(vma->anon_vma);\n\t\tvma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;\n\t}",
"\tvma_link(mm, vma, prev, rb_link, rb_parent);\n\treturn 0;\n}",
"/*\n * Copy the vma structure to a new location in the same mm,\n * prior to moving page table entries, to effect an mremap move.\n */\nstruct vm_area_struct *copy_vma(struct vm_area_struct **vmap,\n\tunsigned long addr, unsigned long len, pgoff_t pgoff,\n\tbool *need_rmap_locks)\n{\n\tstruct vm_area_struct *vma = *vmap;\n\tunsigned long vma_start = vma->vm_start;\n\tstruct mm_struct *mm = vma->vm_mm;\n\tstruct vm_area_struct *new_vma, *prev;\n\tstruct rb_node **rb_link, *rb_parent;\n\tbool faulted_in_anon_vma = true;",
"\t/*\n\t * If anonymous vma has not yet been faulted, update new pgoff\n\t * to match new location, to increase its chance of merging.\n\t */\n\tif (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {\n\t\tpgoff = addr >> PAGE_SHIFT;\n\t\tfaulted_in_anon_vma = false;\n\t}",
"\tif (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))\n\t\treturn NULL;\t/* should never get here */\n\tnew_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,\n\t\t\t vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),\n\t\t\t vma->vm_userfaultfd_ctx);\n\tif (new_vma) {\n\t\t/*\n\t\t * Source vma may have been merged into new_vma\n\t\t */\n\t\tif (unlikely(vma_start >= new_vma->vm_start &&\n\t\t\t vma_start < new_vma->vm_end)) {\n\t\t\t/*\n\t\t\t * The only way we can get a vma_merge with\n\t\t\t * self during an mremap is if the vma hasn't\n\t\t\t * been faulted in yet and we were allowed to\n\t\t\t * reset the dst vma->vm_pgoff to the\n\t\t\t * destination address of the mremap to allow\n\t\t\t * the merge to happen. mremap must change the\n\t\t\t * vm_pgoff linearity between src and dst vmas\n\t\t\t * (in turn preventing a vma_merge) to be\n\t\t\t * safe. It is only safe to keep the vm_pgoff\n\t\t\t * linear if there are no pages mapped yet.\n\t\t\t */\n\t\t\tVM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);\n\t\t\t*vmap = vma = new_vma;\n\t\t}\n\t\t*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);\n\t} else {\n\t\tnew_vma = vm_area_dup(vma);\n\t\tif (!new_vma)\n\t\t\tgoto out;\n\t\tnew_vma->vm_start = addr;\n\t\tnew_vma->vm_end = addr + len;\n\t\tnew_vma->vm_pgoff = pgoff;\n\t\tif (vma_dup_policy(vma, new_vma))\n\t\t\tgoto out_free_vma;\n\t\tif (anon_vma_clone(new_vma, vma))\n\t\t\tgoto out_free_mempol;\n\t\tif (new_vma->vm_file)\n\t\t\tget_file(new_vma->vm_file);\n\t\tif (new_vma->vm_ops && new_vma->vm_ops->open)\n\t\t\tnew_vma->vm_ops->open(new_vma);\n\t\tvma_link(mm, new_vma, prev, rb_link, rb_parent);\n\t\t*need_rmap_locks = false;\n\t}\n\treturn new_vma;",
"out_free_mempol:\n\tmpol_put(vma_policy(new_vma));\nout_free_vma:\n\tvm_area_free(new_vma);\nout:\n\treturn NULL;\n}",
"/*\n * Return true if the calling process may expand its vm space by the passed\n * number of pages\n */\nbool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)\n{\n\tif (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)\n\t\treturn false;",
"\tif (is_data_mapping(flags) &&\n\t mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {\n\t\t/* Workaround for Valgrind */\n\t\tif (rlimit(RLIMIT_DATA) == 0 &&\n\t\t mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)\n\t\t\treturn true;",
"\t\tpr_warn_once(\"%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\\n\",\n\t\t\t current->comm, current->pid,\n\t\t\t (mm->data_vm + npages) << PAGE_SHIFT,\n\t\t\t rlimit(RLIMIT_DATA),\n\t\t\t ignore_rlimit_data ? \"\" : \" or use boot option ignore_rlimit_data\");",
"\t\tif (!ignore_rlimit_data)\n\t\t\treturn false;\n\t}",
"\treturn true;\n}",
"void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)\n{\n\tmm->total_vm += npages;",
"\tif (is_exec_mapping(flags))\n\t\tmm->exec_vm += npages;\n\telse if (is_stack_mapping(flags))\n\t\tmm->stack_vm += npages;\n\telse if (is_data_mapping(flags))\n\t\tmm->data_vm += npages;\n}",
"static vm_fault_t special_mapping_fault(struct vm_fault *vmf);",
"/*\n * Having a close hook prevents vma merging regardless of flags.\n */\nstatic void special_mapping_close(struct vm_area_struct *vma)\n{\n}",
"static const char *special_mapping_name(struct vm_area_struct *vma)\n{\n\treturn ((struct vm_special_mapping *)vma->vm_private_data)->name;\n}",
"static int special_mapping_mremap(struct vm_area_struct *new_vma)\n{\n\tstruct vm_special_mapping *sm = new_vma->vm_private_data;",
"\tif (WARN_ON_ONCE(current->mm != new_vma->vm_mm))\n\t\treturn -EFAULT;",
"\tif (sm->mremap)\n\t\treturn sm->mremap(sm, new_vma);",
"\treturn 0;\n}",
"static const struct vm_operations_struct special_mapping_vmops = {\n\t.close = special_mapping_close,\n\t.fault = special_mapping_fault,\n\t.mremap = special_mapping_mremap,\n\t.name = special_mapping_name,\n};",
"static const struct vm_operations_struct legacy_special_mapping_vmops = {\n\t.close = special_mapping_close,\n\t.fault = special_mapping_fault,\n};",
"static vm_fault_t special_mapping_fault(struct vm_fault *vmf)\n{\n\tstruct vm_area_struct *vma = vmf->vma;\n\tpgoff_t pgoff;\n\tstruct page **pages;",
"\tif (vma->vm_ops == &legacy_special_mapping_vmops) {\n\t\tpages = vma->vm_private_data;\n\t} else {\n\t\tstruct vm_special_mapping *sm = vma->vm_private_data;",
"\t\tif (sm->fault)\n\t\t\treturn sm->fault(sm, vmf->vma, vmf);",
"\t\tpages = sm->pages;\n\t}",
"\tfor (pgoff = vmf->pgoff; pgoff && *pages; ++pages)\n\t\tpgoff--;",
"\tif (*pages) {\n\t\tstruct page *page = *pages;\n\t\tget_page(page);\n\t\tvmf->page = page;\n\t\treturn 0;\n\t}",
"\treturn VM_FAULT_SIGBUS;\n}",
"static struct vm_area_struct *__install_special_mapping(\n\tstruct mm_struct *mm,\n\tunsigned long addr, unsigned long len,\n\tunsigned long vm_flags, void *priv,\n\tconst struct vm_operations_struct *ops)\n{\n\tint ret;\n\tstruct vm_area_struct *vma;",
"\tvma = vm_area_alloc(mm);\n\tif (unlikely(vma == NULL))\n\t\treturn ERR_PTR(-ENOMEM);",
"\tvma->vm_start = addr;\n\tvma->vm_end = addr + len;",
"\tvma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;\n\tvma->vm_page_prot = vm_get_page_prot(vma->vm_flags);",
"\tvma->vm_ops = ops;\n\tvma->vm_private_data = priv;",
"\tret = insert_vm_struct(mm, vma);\n\tif (ret)\n\t\tgoto out;",
"\tvm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);",
"\tperf_event_mmap(vma);",
"\treturn vma;",
"out:\n\tvm_area_free(vma);\n\treturn ERR_PTR(ret);\n}",
"bool vma_is_special_mapping(const struct vm_area_struct *vma,\n\tconst struct vm_special_mapping *sm)\n{\n\treturn vma->vm_private_data == sm &&\n\t\t(vma->vm_ops == &special_mapping_vmops ||\n\t\t vma->vm_ops == &legacy_special_mapping_vmops);\n}",
"/*\n * Called with mm->mmap_sem held for writing.\n * Insert a new vma covering the given region, with the given flags.\n * Its pages are supplied by the given array of struct page *.\n * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.\n * The region past the last page supplied will always produce SIGBUS.\n * The array pointer and the pages it points to are assumed to stay alive\n * for as long as this mapping might exist.\n */\nstruct vm_area_struct *_install_special_mapping(\n\tstruct mm_struct *mm,\n\tunsigned long addr, unsigned long len,\n\tunsigned long vm_flags, const struct vm_special_mapping *spec)\n{\n\treturn __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,\n\t\t\t\t\t&special_mapping_vmops);\n}",
"int install_special_mapping(struct mm_struct *mm,\n\t\t\t unsigned long addr, unsigned long len,\n\t\t\t unsigned long vm_flags, struct page **pages)\n{\n\tstruct vm_area_struct *vma = __install_special_mapping(\n\t\tmm, addr, len, vm_flags, (void *)pages,\n\t\t&legacy_special_mapping_vmops);",
"\treturn PTR_ERR_OR_ZERO(vma);\n}",
"static DEFINE_MUTEX(mm_all_locks_mutex);",
"static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)\n{\n\tif (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {\n\t\t/*\n\t\t * The LSB of head.next can't change from under us\n\t\t * because we hold the mm_all_locks_mutex.\n\t\t */\n\t\tdown_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_sem);\n\t\t/*\n\t\t * We can safely modify head.next after taking the\n\t\t * anon_vma->root->rwsem. If some other vma in this mm shares\n\t\t * the same anon_vma we won't take it again.\n\t\t *\n\t\t * No need of atomic instructions here, head.next\n\t\t * can't change from under us thanks to the\n\t\t * anon_vma->root->rwsem.\n\t\t */\n\t\tif (__test_and_set_bit(0, (unsigned long *)\n\t\t\t\t &anon_vma->root->rb_root.rb_root.rb_node))\n\t\t\tBUG();\n\t}\n}",
"static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)\n{\n\tif (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {\n\t\t/*\n\t\t * AS_MM_ALL_LOCKS can't change from under us because\n\t\t * we hold the mm_all_locks_mutex.\n\t\t *\n\t\t * Operations on ->flags have to be atomic because\n\t\t * even if AS_MM_ALL_LOCKS is stable thanks to the\n\t\t * mm_all_locks_mutex, there may be other cpus\n\t\t * changing other bitflags in parallel to us.\n\t\t */\n\t\tif (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))\n\t\t\tBUG();\n\t\tdown_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_sem);\n\t}\n}",
"/*\n * This operation locks against the VM for all pte/vma/mm related\n * operations that could ever happen on a certain mm. This includes\n * vmtruncate, try_to_unmap, and all page faults.\n *\n * The caller must take the mmap_sem in write mode before calling\n * mm_take_all_locks(). The caller isn't allowed to release the\n * mmap_sem until mm_drop_all_locks() returns.\n *\n * mmap_sem in write mode is required in order to block all operations\n * that could modify pagetables and free pages without need of\n * altering the vma layout. It's also needed in write mode to avoid new\n * anon_vmas to be associated with existing vmas.\n *\n * A single task can't take more than one mm_take_all_locks() in a row\n * or it would deadlock.\n *\n * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in\n * mapping->flags avoid to take the same lock twice, if more than one\n * vma in this mm is backed by the same anon_vma or address_space.\n *\n * We take locks in following order, accordingly to comment at beginning\n * of mm/rmap.c:\n * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for\n * hugetlb mapping);\n * - all i_mmap_rwsem locks;\n * - all anon_vma->rwseml\n *\n * We can take all locks within these types randomly because the VM code\n * doesn't nest them and we protected from parallel mm_take_all_locks() by\n * mm_all_locks_mutex.\n *\n * mm_take_all_locks() and mm_drop_all_locks are expensive operations\n * that may have to take thousand of locks.\n *\n * mm_take_all_locks() can fail if it's interrupted by signals.\n */\nint mm_take_all_locks(struct mm_struct *mm)\n{\n\tstruct vm_area_struct *vma;\n\tstruct anon_vma_chain *avc;",
"\tBUG_ON(down_read_trylock(&mm->mmap_sem));",
"\tmutex_lock(&mm_all_locks_mutex);",
"\tfor (vma = mm->mmap; vma; vma = vma->vm_next) {\n\t\tif (signal_pending(current))\n\t\t\tgoto out_unlock;\n\t\tif (vma->vm_file && vma->vm_file->f_mapping &&\n\t\t\t\tis_vm_hugetlb_page(vma))\n\t\t\tvm_lock_mapping(mm, vma->vm_file->f_mapping);\n\t}",
"\tfor (vma = mm->mmap; vma; vma = vma->vm_next) {\n\t\tif (signal_pending(current))\n\t\t\tgoto out_unlock;\n\t\tif (vma->vm_file && vma->vm_file->f_mapping &&\n\t\t\t\t!is_vm_hugetlb_page(vma))\n\t\t\tvm_lock_mapping(mm, vma->vm_file->f_mapping);\n\t}",
"\tfor (vma = mm->mmap; vma; vma = vma->vm_next) {\n\t\tif (signal_pending(current))\n\t\t\tgoto out_unlock;\n\t\tif (vma->anon_vma)\n\t\t\tlist_for_each_entry(avc, &vma->anon_vma_chain, same_vma)\n\t\t\t\tvm_lock_anon_vma(mm, avc->anon_vma);\n\t}",
"\treturn 0;",
"out_unlock:\n\tmm_drop_all_locks(mm);\n\treturn -EINTR;\n}",
"static void vm_unlock_anon_vma(struct anon_vma *anon_vma)\n{\n\tif (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {\n\t\t/*\n\t\t * The LSB of head.next can't change to 0 from under\n\t\t * us because we hold the mm_all_locks_mutex.\n\t\t *\n\t\t * We must however clear the bitflag before unlocking\n\t\t * the vma so the users using the anon_vma->rb_root will\n\t\t * never see our bitflag.\n\t\t *\n\t\t * No need of atomic instructions here, head.next\n\t\t * can't change from under us until we release the\n\t\t * anon_vma->root->rwsem.\n\t\t */\n\t\tif (!__test_and_clear_bit(0, (unsigned long *)\n\t\t\t\t\t &anon_vma->root->rb_root.rb_root.rb_node))\n\t\t\tBUG();\n\t\tanon_vma_unlock_write(anon_vma);\n\t}\n}",
"static void vm_unlock_mapping(struct address_space *mapping)\n{\n\tif (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {\n\t\t/*\n\t\t * AS_MM_ALL_LOCKS can't change to 0 from under us\n\t\t * because we hold the mm_all_locks_mutex.\n\t\t */\n\t\ti_mmap_unlock_write(mapping);\n\t\tif (!test_and_clear_bit(AS_MM_ALL_LOCKS,\n\t\t\t\t\t&mapping->flags))\n\t\t\tBUG();\n\t}\n}",
"/*\n * The mmap_sem cannot be released by the caller until\n * mm_drop_all_locks() returns.\n */\nvoid mm_drop_all_locks(struct mm_struct *mm)\n{\n\tstruct vm_area_struct *vma;\n\tstruct anon_vma_chain *avc;",
"\tBUG_ON(down_read_trylock(&mm->mmap_sem));\n\tBUG_ON(!mutex_is_locked(&mm_all_locks_mutex));",
"\tfor (vma = mm->mmap; vma; vma = vma->vm_next) {\n\t\tif (vma->anon_vma)\n\t\t\tlist_for_each_entry(avc, &vma->anon_vma_chain, same_vma)\n\t\t\t\tvm_unlock_anon_vma(avc->anon_vma);\n\t\tif (vma->vm_file && vma->vm_file->f_mapping)\n\t\t\tvm_unlock_mapping(vma->vm_file->f_mapping);\n\t}",
"\tmutex_unlock(&mm_all_locks_mutex);\n}",
"/*\n * initialise the percpu counter for VM\n */\nvoid __init mmap_init(void)\n{\n\tint ret;",
"\tret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);\n\tVM_BUG_ON(ret);\n}",
"/*\n * Initialise sysctl_user_reserve_kbytes.\n *\n * This is intended to prevent a user from starting a single memory hogging\n * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER\n * mode.\n *\n * The default value is min(3% of free memory, 128MB)\n * 128MB is enough to recover with sshd/login, bash, and top/kill.\n */\nstatic int init_user_reserve(void)\n{\n\tunsigned long free_kbytes;",
"\tfree_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);",
"\tsysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);\n\treturn 0;\n}\nsubsys_initcall(init_user_reserve);",
"/*\n * Initialise sysctl_admin_reserve_kbytes.\n *\n * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin\n * to log in and kill a memory hogging process.\n *\n * Systems with more than 256MB will reserve 8MB, enough to recover\n * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will\n * only reserve 3% of free pages by default.\n */\nstatic int init_admin_reserve(void)\n{\n\tunsigned long free_kbytes;",
"\tfree_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);",
"\tsysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);\n\treturn 0;\n}\nsubsys_initcall(init_admin_reserve);",
"/*\n * Reinititalise user and admin reserves if memory is added or removed.\n *\n * The default user reserve max is 128MB, and the default max for the\n * admin reserve is 8MB. These are usually, but not always, enough to\n * enable recovery from a memory hogging process using login/sshd, a shell,\n * and tools like top. It may make sense to increase or even disable the\n * reserve depending on the existence of swap or variations in the recovery\n * tools. So, the admin may have changed them.\n *\n * If memory is added and the reserves have been eliminated or increased above\n * the default max, then we'll trust the admin.\n *\n * If memory is removed and there isn't enough free memory, then we\n * need to reset the reserves.\n *\n * Otherwise keep the reserve set by the admin.\n */\nstatic int reserve_mem_notifier(struct notifier_block *nb,\n\t\t\t unsigned long action, void *data)\n{\n\tunsigned long tmp, free_kbytes;",
"\tswitch (action) {\n\tcase MEM_ONLINE:\n\t\t/* Default max is 128MB. Leave alone if modified by operator. */\n\t\ttmp = sysctl_user_reserve_kbytes;\n\t\tif (0 < tmp && tmp < (1UL << 17))\n\t\t\tinit_user_reserve();",
"\t\t/* Default max is 8MB. Leave alone if modified by operator. */\n\t\ttmp = sysctl_admin_reserve_kbytes;\n\t\tif (0 < tmp && tmp < (1UL << 13))\n\t\t\tinit_admin_reserve();",
"\t\tbreak;\n\tcase MEM_OFFLINE:\n\t\tfree_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);",
"\t\tif (sysctl_user_reserve_kbytes > free_kbytes) {\n\t\t\tinit_user_reserve();\n\t\t\tpr_info(\"vm.user_reserve_kbytes reset to %lu\\n\",\n\t\t\t\tsysctl_user_reserve_kbytes);\n\t\t}",
"\t\tif (sysctl_admin_reserve_kbytes > free_kbytes) {\n\t\t\tinit_admin_reserve();\n\t\t\tpr_info(\"vm.admin_reserve_kbytes reset to %lu\\n\",\n\t\t\t\tsysctl_admin_reserve_kbytes);\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\treturn NOTIFY_OK;\n}",
"static struct notifier_block reserve_mem_nb = {\n\t.notifier_call = reserve_mem_notifier,\n};",
"static int __meminit init_reserve_notifier(void)\n{\n\tif (register_hotmemory_notifier(&reserve_mem_nb))\n\t\tpr_err(\"Failed registering memory add/remove notifier for admin reserve\\n\");",
"\treturn 0;\n}\nsubsys_initcall(init_reserve_notifier);"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [2435], "buggy_code_start_loc": [2429], "filenames": ["mm/mmap.c"], "fixing_code_end_loc": [2434], "fixing_code_start_loc": [2429], "message": "In the Linux kernel before 4.20.14, expand_downwards in mm/mmap.c lacks a check for the mmap minimum address, which makes it easier for attackers to exploit kernel NULL pointer dereferences on non-SMAP platforms. This is related to a capability check for the wrong task.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "56A636A0-542A-457B-8557-CD70D9AD69C1", "versionEndExcluding": "4.9.162", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.9", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "6DC55135-E4DB-45B8-BF67-5139F750BF40", "versionEndExcluding": "4.14.105", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.14", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "03F65CBE-42FC-4C64-8189-9D1AA25C01A5", "versionEndExcluding": "4.19.27", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.19", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "816E4DD2-A3B9-47AD-AFD4-79A03297934E", "versionEndExcluding": "4.20.14", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.20", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:redhat:enterprise_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "142AD0DD-4CF3-4D74-9442-459CE3347E3A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "F4CFF558-3C47-480D-A2F0-BABF26042943", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "F1E78106-58E6-4D59-990F-75DA575BFAD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:leap:42.3:*:*:*:*:*:*:*", "matchCriteriaId": "5F65DAB0-3DAD-49FF-BC73-3581CC3D5BF3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:*:*:*:*", "matchCriteriaId": "1F3EFED2-F6BC-46D9-AB22-D5ED87EF4549", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:esm:*:*:*", "matchCriteriaId": "7A5301BF-1402-4BE0-A0F8-69FBE79BC6D6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.10:*:*:*:*:*:*:*", "matchCriteriaId": "07C312A0-CD2C-4B9C-B064-6409B25C278F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In the Linux kernel before 4.20.14, expand_downwards in mm/mmap.c lacks a check for the mmap minimum address, which makes it easier for attackers to exploit kernel NULL pointer dereferences on non-SMAP platforms. This is related to a capability check for the wrong task."}, {"lang": "es", "value": "En el kernel de Linux, en versiones anteriores a la 4.20.14, expand_downwards en mm/mmap.c carece de una comprobaci\u00f3n para la direcci\u00f3n m\u00ednima de mmap, lo que facilita que los atacantes exploten desreferencias de puntero NULL en el kernel en plataformas que no son SMAP. Esto esto est\u00e1 relacionado con una comprobaci\u00f3n de capacidades para la tarea equivocada."}], "evaluatorComment": null, "id": "CVE-2019-9213", "lastModified": "2022-10-12T15:56:12.443", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.9, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-03-05T22:29:00.240", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=0a1d52994d440e21def1c2174932410b4f2a98a1"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-03/msg00045.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-04/msg00052.html"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "http://packetstormsecurity.com/files/156053/Reliable-Datagram-Sockets-RDS-rds_atomic_free_op-Privilege-Escalation.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:0831"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1479"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1480"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Mailing List", "Third Party Advisory"], "url": "https://bugs.chromium.org/p/project-zero/issues/detail?id=1792"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.14.105"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.19.27"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.20.14"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.9.162"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://github.com/torvalds/linux/commit/0a1d52994d440e21def1c2174932410b4f2a98a1"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/03/msg00034.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/04/msg00004.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/05/msg00002.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3930-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3930-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3931-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3931-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3932-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3932-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3933-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3933-2/"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "https://www.exploit-db.com/exploits/46502/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/0a1d52994d440e21def1c2174932410b4f2a98a1"}, "type": "CWE-476"}
| 252
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.api;",
"import java.util.Calendar;\nimport java.util.Date;\nimport java.util.Locale;",
"import java.util.Objects;",
"\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;",
"",
"import org.xwiki.model.reference.DocumentReference;\nimport org.xwiki.security.authorization.Right;",
"",
"\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.XWikiDeletedDocument;\nimport com.xpn.xwiki.doc.XWikiDocument;",
"",
"import com.xpn.xwiki.util.Programming;",
"",
"\n/**\n * Information about a deleted document in the recycle bin.\n *\n * @version $Id$\n */\npublic class DeletedDocument extends Api\n{\n private static final String ADMIN_RIGHT = \"admin\";",
" /** Logging helper object. */\n private static final Logger LOGGER = LoggerFactory.getLogger(DeletedDocument.class);",
" /**\n * The internal object wrapped by this API.\n */\n private final XWikiDeletedDocument deletedDoc;\n",
"",
" /**\n * Simple constructor, initializes a new API object with the current {@link com.xpn.xwiki.XWikiContext context} and\n * the specified protected {@link com.xpn.xwiki.doc.XWikiDeletedDocument deleted document} object.\n *\n * @param deletedDoc the internal object wrapped by this API\n * @param context the current request context\n */\n public DeletedDocument(XWikiDeletedDocument deletedDoc, XWikiContext context)\n {\n super(context);\n this.deletedDoc = deletedDoc;\n }",
" /**\n * @return full name of document (ie: Main.WebHome)\n */\n public String getFullName()\n {\n return this.deletedDoc.getFullName();\n }",
" /**\n * @return locale of document\n * @deprecated since 8.0M1, use {@link #getLocale()} instead\n */\n @Deprecated\n public String getLanguage()\n {\n return this.deletedDoc.getLanguage();\n }",
" /**\n * @return locale of document\n * @since 8.0M1\n */\n public Locale getLocale()\n {\n return this.deletedDoc.getLocale();\n }",
" /**\n * @return date of delete action\n */\n public Date getDate()\n {\n return this.deletedDoc.getDate();\n }",
" /**\n * @return user which delete document\n */\n public String getDeleter()\n {\n return this.deletedDoc.getDeleter();\n }",
" /**\n * @return the reference of the user who deleted this document\n * @since 11.5RC1\n */\n public DocumentReference getDeleterReference()\n {\n return this.deletedDoc.getDeleterReference();\n }",
" /**\n * @return id of deleted document. id is unique only for this document.\n */\n public long getId()\n {\n return this.deletedDoc.getId();\n }",
" /**\n * @return the id of the operation that deleted multiple documents at the same time, including this one\n * @since 9.4RC1\n */\n public String getBatchId()\n {\n return this.deletedDoc.getBatchId();\n }\n",
"",
" /**\n * Check if the current user has the right to restore the document.\n *\n * @return {@code true} if the current user can restore this document, {@code false} otherwise\n */\n public boolean canUndelete()\n {",
" try {\n return hasAccessLevel(ADMIN_RIGHT, getFullName()) || hasAccessLevel(\"undelete\", getFullName())\n || (Objects.equals(this.context.getUserReference(), getDeleterReference())\n && hasAccess(Right.EDIT, getDocumentReference()));\n } catch (XWikiException ex) {\n // Public APIs should not throw exceptions\n LOGGER.warn(\"Exception while checking if entry [{}] can be restored from the recycle bin\", getId(), ex);\n return false;\n }",
" }",
" /**\n * @return {@code true} if the current user can permanently delete this document, {@code false} otherwise\n * @xwiki.xwikicfg xwiki.store.recyclebin.adminWaitDays How many days should an administrator wait before being able\n * to permanently delete this document from the recycle bin. 0 by default.\n * @xwiki.xwikicfg xwiki.store.recyclebin.waitDays How many days should a normal user with \"delete\" right wait\n * before being able to permanently delete this document from the recycle bin. 7 by default.\n */\n public boolean canDelete()\n {\n try {\n XWikiDocument doc = new XWikiDocument();\n doc.setFullName(getFullName(), this.context);\n if (!hasAccessLevel(\"delete\", getFullName())) {\n return false;\n }\n String waitdays;\n if (hasAccessLevel(ADMIN_RIGHT, getFullName())) {\n waitdays = getXWikiContext().getWiki().Param(\"xwiki.store.recyclebin.adminWaitDays\", \"0\");\n } else {\n waitdays = getXWikiContext().getWiki().Param(\"xwiki.store.recyclebin.waitDays\", \"7\");\n }\n int seconds = (int) (Double.parseDouble(waitdays) * 24 * 60 * 60 + 0.5);\n Calendar cal = Calendar.getInstance();\n cal.setTime(getDate());\n cal.add(Calendar.SECOND, seconds);\n return cal.before(Calendar.getInstance());\n } catch (Exception ex) {\n // Public APIs should not throw exceptions\n LOGGER.warn(\"Exception while checking if entry [{}] can be removed from the recycle bin\", getId(), ex);\n return false;\n }\n }",
" /**\n * @return original deleted document if user has programming rights, else {@code null}.\n */\n @Programming\n public XWikiDeletedDocument getDeletedDocument()\n {\n if (hasProgrammingRights()) {\n return this.deletedDoc;\n } else {\n return null;\n }\n }",
" /**\n * @return the document as it is in the recycle bin if the user is allowed to restore it, {@code null} otherwise\n */\n public Document getDocument()\n {\n if (canUndelete()) {\n try {\n return new Document(this.deletedDoc.restoreDocument(null, this.context), this.context);\n } catch (XWikiException e) {\n LOGGER.warn(\"Failed to parse deleted document [{}]\", getFullName(), e);\n }\n }",
" return null;\n }",
" /**\n * @return the document reference for the deleted document, including any locale information\n * @since 9.4RC1\n */\n public DocumentReference getDocumentReference()\n {\n return this.deletedDoc.getDocumentReference();\n }\n}"
] |
[
1,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.api;",
"import java.util.Calendar;\nimport java.util.Date;\nimport java.util.Locale;",
"",
"\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;",
"import org.xwiki.component.util.DefaultParameterizedType;",
"import org.xwiki.model.reference.DocumentReference;\nimport org.xwiki.security.authorization.Right;",
"import org.xwiki.stability.Unstable;\nimport org.xwiki.user.UserReference;\nimport org.xwiki.user.UserReferenceResolver;",
"\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.XWikiDeletedDocument;\nimport com.xpn.xwiki.doc.XWikiDocument;",
"import com.xpn.xwiki.store.XWikiRecycleBinStoreInterface;",
"import com.xpn.xwiki.util.Programming;",
"import com.xpn.xwiki.web.Utils;",
"\n/**\n * Information about a deleted document in the recycle bin.\n *\n * @version $Id$\n */\npublic class DeletedDocument extends Api\n{\n private static final String ADMIN_RIGHT = \"admin\";",
" /** Logging helper object. */\n private static final Logger LOGGER = LoggerFactory.getLogger(DeletedDocument.class);",
" /**\n * The internal object wrapped by this API.\n */\n private final XWikiDeletedDocument deletedDoc;\n",
" private UserReferenceResolver<DocumentReference> userReferenceResolver;\n",
" /**\n * Simple constructor, initializes a new API object with the current {@link com.xpn.xwiki.XWikiContext context} and\n * the specified protected {@link com.xpn.xwiki.doc.XWikiDeletedDocument deleted document} object.\n *\n * @param deletedDoc the internal object wrapped by this API\n * @param context the current request context\n */\n public DeletedDocument(XWikiDeletedDocument deletedDoc, XWikiContext context)\n {\n super(context);\n this.deletedDoc = deletedDoc;\n }",
" /**\n * @return full name of document (ie: Main.WebHome)\n */\n public String getFullName()\n {\n return this.deletedDoc.getFullName();\n }",
" /**\n * @return locale of document\n * @deprecated since 8.0M1, use {@link #getLocale()} instead\n */\n @Deprecated\n public String getLanguage()\n {\n return this.deletedDoc.getLanguage();\n }",
" /**\n * @return locale of document\n * @since 8.0M1\n */\n public Locale getLocale()\n {\n return this.deletedDoc.getLocale();\n }",
" /**\n * @return date of delete action\n */\n public Date getDate()\n {\n return this.deletedDoc.getDate();\n }",
" /**\n * @return user which delete document\n */\n public String getDeleter()\n {\n return this.deletedDoc.getDeleter();\n }",
" /**\n * @return the reference of the user who deleted this document\n * @since 11.5RC1\n */\n public DocumentReference getDeleterReference()\n {\n return this.deletedDoc.getDeleterReference();\n }",
" /**\n * @return id of deleted document. id is unique only for this document.\n */\n public long getId()\n {\n return this.deletedDoc.getId();\n }",
" /**\n * @return the id of the operation that deleted multiple documents at the same time, including this one\n * @since 9.4RC1\n */\n public String getBatchId()\n {\n return this.deletedDoc.getBatchId();\n }\n",
" private UserReferenceResolver<DocumentReference> getUserReferenceResolver()\n {\n if (this.userReferenceResolver == null) {\n this.userReferenceResolver = Utils.getComponent(\n new DefaultParameterizedType(null, UserReferenceResolver.class, DocumentReference.class), \"document\");\n }\n return this.userReferenceResolver;\n }",
" private boolean hasAccess(Right right)\n {\n UserReference userReference = getUserReferenceResolver().resolve(this.context.getUserReference());\n XWikiRecycleBinStoreInterface recycleBinStore = this.context.getWiki().getRecycleBinStore();\n return recycleBinStore.hasAccess(right, userReference, this.deletedDoc);\n }\n",
" /**\n * Check if the current user has the right to restore the document.\n *\n * @return {@code true} if the current user can restore this document, {@code false} otherwise\n */\n public boolean canUndelete()\n {",
" return hasAccess(Right.EDIT);\n }",
" /**\n * Check if the current user has the right to view the deleted document.\n * This is allowed either if the user has admin right on the original reference of the doc, or if they were the\n * original user who deleted it.\n *\n * @return {code true} if the current user is allowed to view the deleted document.\n * @since 14.10RC1\n * @since 14.4.7\n * @since 13.10.11\n */\n @Unstable\n public boolean canView()\n {\n return hasAccess(Right.VIEW);",
" }",
" /**\n * @return {@code true} if the current user can permanently delete this document, {@code false} otherwise\n * @xwiki.xwikicfg xwiki.store.recyclebin.adminWaitDays How many days should an administrator wait before being able\n * to permanently delete this document from the recycle bin. 0 by default.\n * @xwiki.xwikicfg xwiki.store.recyclebin.waitDays How many days should a normal user with \"delete\" right wait\n * before being able to permanently delete this document from the recycle bin. 7 by default.\n */\n public boolean canDelete()\n {\n try {\n XWikiDocument doc = new XWikiDocument();\n doc.setFullName(getFullName(), this.context);\n if (!hasAccessLevel(\"delete\", getFullName())) {\n return false;\n }\n String waitdays;\n if (hasAccessLevel(ADMIN_RIGHT, getFullName())) {\n waitdays = getXWikiContext().getWiki().Param(\"xwiki.store.recyclebin.adminWaitDays\", \"0\");\n } else {\n waitdays = getXWikiContext().getWiki().Param(\"xwiki.store.recyclebin.waitDays\", \"7\");\n }\n int seconds = (int) (Double.parseDouble(waitdays) * 24 * 60 * 60 + 0.5);\n Calendar cal = Calendar.getInstance();\n cal.setTime(getDate());\n cal.add(Calendar.SECOND, seconds);\n return cal.before(Calendar.getInstance());\n } catch (Exception ex) {\n // Public APIs should not throw exceptions\n LOGGER.warn(\"Exception while checking if entry [{}] can be removed from the recycle bin\", getId(), ex);\n return false;\n }\n }",
" /**\n * @return original deleted document if user has programming rights, else {@code null}.\n */\n @Programming\n public XWikiDeletedDocument getDeletedDocument()\n {\n if (hasProgrammingRights()) {\n return this.deletedDoc;\n } else {\n return null;\n }\n }",
" /**\n * @return the document as it is in the recycle bin if the user is allowed to restore it, {@code null} otherwise\n */\n public Document getDocument()\n {\n if (canUndelete()) {\n try {\n return new Document(this.deletedDoc.restoreDocument(null, this.context), this.context);\n } catch (XWikiException e) {\n LOGGER.warn(\"Failed to parse deleted document [{}]\", getFullName(), e);\n }\n }",
" return null;\n }",
" /**\n * @return the document reference for the deleted document, including any locale information\n * @since 9.4RC1\n */\n public DocumentReference getDocumentReference()\n {\n return this.deletedDoc.getDocumentReference();\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.doc;",
"import org.xwiki.component.annotation.Role;\nimport org.xwiki.model.reference.DocumentReference;",
"",
"\nimport com.xpn.xwiki.XWikiException;",
"/**\n * Provide generic way of requesting a specific revision of a document from several sources (database, installed XAR\n * extension, etc.).\n * <p>\n * The revision syntax is {@code <provider hint>:<revision>}, default provide being database (the version of the\n * document in the history).\n * \n * @version $Id$\n * @since 9.4RC1\n */\n@Role\npublic interface DocumentRevisionProvider\n{\n /**\n * Load the document in the provided revision.\n * \n * @param reference the reference of the document\n * @param revision the revision of the document\n * @return the {@link XWikiDocument} instance or null if none existing\n * @throws XWikiException when failing to load the document revision\n */\n XWikiDocument getRevision(DocumentReference reference, String revision) throws XWikiException;",
" /**\n * Load the document in the provided revision.\n * \n * @param document the current document\n * @param revision the revision of the document\n * @return the {@link XWikiDocument} instance or null if none existing\n * @throws XWikiException when failing to load the document revision\n */\n XWikiDocument getRevision(XWikiDocument document, String revision) throws XWikiException;",
"",
"}"
] |
[
1,
1,
0,
1,
1,
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.doc;",
"import org.xwiki.component.annotation.Role;\nimport org.xwiki.model.reference.DocumentReference;",
"import org.xwiki.security.authorization.AccessDeniedException;\nimport org.xwiki.security.authorization.AuthorizationException;\nimport org.xwiki.security.authorization.Right;\nimport org.xwiki.stability.Unstable;\nimport org.xwiki.user.UserReference;",
"\nimport com.xpn.xwiki.XWikiException;",
"/**\n * Provide generic way of requesting a specific revision of a document from several sources (database, installed XAR\n * extension, etc.).\n * <p>\n * The revision syntax is {@code <provider hint>:<revision>}, default provide being database (the version of the\n * document in the history).\n * \n * @version $Id$\n * @since 9.4RC1\n */\n@Role\npublic interface DocumentRevisionProvider\n{\n /**\n * Load the document in the provided revision.\n * \n * @param reference the reference of the document\n * @param revision the revision of the document\n * @return the {@link XWikiDocument} instance or null if none existing\n * @throws XWikiException when failing to load the document revision\n */\n XWikiDocument getRevision(DocumentReference reference, String revision) throws XWikiException;",
" /**\n * Load the document in the provided revision.\n * \n * @param document the current document\n * @param revision the revision of the document\n * @return the {@link XWikiDocument} instance or null if none existing\n * @throws XWikiException when failing to load the document revision\n */\n XWikiDocument getRevision(XWikiDocument document, String revision) throws XWikiException;",
"\n /**\n * Check if access is granted on the given document revision, for the given user and right: if the access is not\n * granted this method will throw an {@link AccessDeniedException}.\n * This method allows each revision provider to have their own check depending on the type of revision.\n *\n * @param right the right for which to check if access is granted\n * @param userReference the user for whom to check access\n * @param documentReference the reference of the document\n * @param revision the revision of the document\n * @throws AuthorizationException if the access is denied\n * @throws XWikiException in case of problem when loading the revision\n * @since 14.10RC1\n * @since 14.4.7\n * @since 13.10.11\n */\n @Unstable\n default void checkAccess(Right right, UserReference userReference, DocumentReference documentReference,\n String revision) throws AuthorizationException, XWikiException\n {\n }",
"}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.doc;",
"import java.io.IOException;\nimport java.util.Date;\nimport java.util.Locale;",
"import org.apache.commons.lang3.StringUtils;",
"",
"import org.xwiki.localization.LocaleUtils;\nimport org.xwiki.model.reference.DocumentReference;\nimport org.xwiki.model.reference.DocumentReferenceResolver;",
"import com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.internal.store.hibernate.XWikiHibernateDeletedDocumentContent;\nimport com.xpn.xwiki.util.AbstractSimpleClass;\nimport com.xpn.xwiki.util.Util;\nimport com.xpn.xwiki.web.Utils;",
"/**\n * Archive of deleted document, stored in {@link com.xpn.xwiki.store.XWikiRecycleBinStoreInterface}. Immutable, because\n * we don't need modify deleted document.\n *\n * @version $Id$\n * @since 1.2M1\n */\npublic class XWikiDeletedDocument extends AbstractSimpleClass\n{\n /**\n * Synthetic id.\n */\n private long id;",
" /**\n * @see XWikiDocument#getFullName()\n */\n private String fullName;",
" /**\n * @see XWikiDocument#getLocale()\n */\n private Locale locale;",
" /**\n * date of delete action.\n */\n private Date date;",
" /**\n * @see XWikiDeletedDocument#getDeleter()\n */\n private String deleter;",
" private String xmlStore;",
" private XWikiDeletedDocumentContent content;",
" private String batchId;",
" /**\n * Default constructor. Used only in hibernate.\n */\n protected XWikiDeletedDocument()\n {\n }",
" /**\n * @param fullName the local reference of the document\n * @param locale the locale of the document\n * @param storeType - the way to store the document\n * @param deleter - user which delete document\n * @param deleteDate - date of delete action\n * @throws XWikiException if any error\n * @since 9.0RC1\n */\n private XWikiDeletedDocument(String fullName, Locale locale, String storeType, String deleter, Date deleteDate)\n throws XWikiException\n {\n this.fullName = fullName;\n this.locale = locale;\n this.deleter = deleter;\n this.date = deleteDate;\n this.xmlStore = storeType;\n }",
" /**\n * @param doc - deleted document\n * @param deleter - user which delete document\n * @param deleteDate - date of delete action\n * @param context - used for environment\n * @throws XWikiException if any error\n */\n public XWikiDeletedDocument(XWikiDocument doc, String deleter, Date deleteDate, XWikiContext context)\n throws XWikiException\n {\n this(doc.getFullName(), doc.getLocale(), null, deleter, deleteDate);",
" setDocument(doc, context);\n }",
" /**\n * @param fullName the local reference of the document\n * @param locale the locale of the document\n * @param storeType the way to store the document\n * @param deleter the user who delete document\n * @param deleteDate date of delete action\n * @param content the stored deleted document\n * @throws XWikiException if any error\n * @since 9.0RC1\n */\n public XWikiDeletedDocument(String fullName, Locale locale, String storeType, String deleter, Date deleteDate,\n XWikiDeletedDocumentContent content) throws XWikiException\n {\n this(fullName, locale, storeType, deleter, deleteDate);",
" this.content = content;\n }",
" /**\n * @param fullName the local reference of the document\n * @param locale the locale of the document\n * @param storeType the way to store the document\n * @param deleter the user who delete document\n * @param deleteDate date of delete action\n * @param content the stored deleted document\n * @param batchId the id of the batch deletion\n * @throws XWikiException if any error\n * @since 9.4RC1\n */\n public XWikiDeletedDocument(String fullName, Locale locale, String storeType, String deleter, Date deleteDate,\n XWikiDeletedDocumentContent content, String batchId) throws XWikiException\n {\n this(fullName, locale, storeType, deleter, deleteDate, content);",
" this.batchId = batchId;\n }",
" /**\n * @return the synthetic id of this deleted document. unique only for document.\n */\n public long getId()\n {\n return this.id;\n }",
" /**\n * @param id - the synthetic id to set. used only in Hibernate.\n */\n protected void setId(long id)\n {\n this.id = id;\n }",
" /**\n * @return {@link XWikiDocument#getFullName()}\n */\n public String getFullName()\n {\n return this.fullName;\n }",
" /**\n * @param docFullName - {@link XWikiDocument#getFullName()} to set\n */\n protected void setFullName(String docFullName)\n {\n this.fullName = docFullName;\n }",
" /**\n * @return the document reference for the deleted document, including any locale information\n * @since 9.4RC1\n */\n public DocumentReference getDocumentReference()\n {\n DocumentReference documentReference = getDocumentReferenceResolver().resolve(getFullName());",
" Locale localeValue = getLocale();\n if (localeValue != null) {\n documentReference = new DocumentReference(documentReference, localeValue);\n }",
" return documentReference;\n }",
" private static DocumentReferenceResolver<String> getDocumentReferenceResolver()\n {\n return Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, \"currentmixed\");\n }",
" /**\n * @return {@link XWikiDocument#getLanguage()}\n * @deprecated since 8.0M1, use {@link #getLocale()} instead\n */\n @Deprecated\n public String getLanguage()\n {\n return getLocale().toString();\n }",
" /**\n * @return {@link XWikiDocument#getLocale()}\n * @since 8.0M1\n */\n public Locale getLocale()\n {\n return this.locale != null ? this.locale : Locale.ROOT;\n }",
" /**\n * @param locale - {@link XWikiDocument#getLanguage()} to set\n * @deprecated since 8.0M1\n */\n @Deprecated\n protected void setLanguage(String locale)\n {\n this.locale = LocaleUtils.toLocale(Util.normalizeLanguage(locale), Locale.ROOT);\n }",
" /**\n * @return the date of delete action\n */\n public Date getDate()\n {\n return this.date;\n }",
" /**\n * @param date - the date of delete action to set\n */\n protected void setDate(Date date)\n {\n this.date = date;\n }",
" /**\n * @return the user which has removed the document\n */\n public String getDeleter()\n {\n return this.deleter;\n }",
" /**\n * @return the reference of the user who deleted this document\n * @since 11.5RC1\n */\n public DocumentReference getDeleterReference()\n {\n return getDocumentReferenceResolver().resolve(this.deleter);\n }",
" /**\n * @param deleter - the user which has removed the document to set\n */\n protected void setDeleter(String deleter)\n {\n this.deleter = deleter;\n }",
" /**\n * @return the type of the store used for the content\n * @since 9.0RC1\n */\n public String getXmlStore()\n {\n return this.xmlStore;\n }",
" /**\n * @param xmlStore the type of store (supported values are null/\"hibernate\" and \"file\")\n * @since 9.0RC1\n */\n protected void setXmlStore(String xmlStore)\n {\n this.xmlStore = xmlStore;\n }",
" /**\n * Only used in Hibernate.\n * \n * @return xml serialization of {@link XWikiDocument}\n */\n public String getXml()\n {\n if (this.content != null) {\n try {\n return this.content.getContentAsString();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
" // Return empty String instead of null because this field is configured as not null at database level\n return \"\";\n }",
" /**\n * Only used in Hibernate.\n * \n * @param xml - xml serialization of {@link XWikiDocument}\n */\n protected void setXml(String xml)\n {\n if (StringUtils.isNotEmpty(xml)) {\n try {\n this.content = new XWikiHibernateDeletedDocumentContent(xml);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }",
" /**\n * Export {@link XWikiDocument} to {@link XWikiDeletedDocument}.\n *\n * @param doc - the deleted document\n * @param context - used in {@link XWikiDocument#toXML(XWikiContext)}\n * @throws XWikiException in error in {@link XWikiDocument#toXML(XWikiContext)}\n * @deprecated since 9.0RC1, use\n * {@link XWikiDeletedDocument#XWikiDeletedDocument(String, Locale, String, String, Date, XWikiDeletedDocumentContent)\n * instead}\n */\n @Deprecated\n protected void setDocument(XWikiDocument doc, XWikiContext context) throws XWikiException\n {\n this.content = new XWikiHibernateDeletedDocumentContent(doc);\n }",
" /**\n * @return restored document\n * @param doc optional object where to put the document data, if not <code>null</code>\n * @param context the current {@link XWikiContext context}\n * @throws XWikiException if error in {@link XWikiDocument#fromXML(String)}\n */\n public XWikiDocument restoreDocument(XWikiDocument doc, XWikiContext context) throws XWikiException\n {\n if (this.content == null) {\n throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING,\n \"Cannot find any content for the deleted document [\" + this.fullName + \" (\" + this.locale + \")]\");\n }",
" try {\n return this.content.getXWikiDocument(doc);\n } catch (IOException e) {\n throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING,\n \"Error restoring document\", e, null);\n }\n }",
" /**\n * @return restored document\n * @param context the current {@link XWikiContext context}\n * @throws XWikiException if error in {@link XWikiDocument#fromXML(String)}\n * @since 9.0RC1\n */\n public XWikiDocument restoreDocument(XWikiContext context) throws XWikiException\n {\n return restoreDocument(null, context);\n }",
" /**\n * @param batchId batch operation ID to set\n * @since 9.4RC1\n */\n protected void setBatchId(String batchId)\n {\n this.batchId = batchId;\n }",
" /**\n * @return the id of the operation that deleted multiple documents at the same time, including this one\n * @since 9.4RC1\n */\n public String getBatchId()\n {\n return batchId;\n }",
"",
"}"
] |
[
1,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.doc;",
"import java.io.IOException;\nimport java.util.Date;\nimport java.util.Locale;",
"import org.apache.commons.lang3.StringUtils;",
"import org.apache.commons.lang3.builder.ToStringBuilder;",
"import org.xwiki.localization.LocaleUtils;\nimport org.xwiki.model.reference.DocumentReference;\nimport org.xwiki.model.reference.DocumentReferenceResolver;",
"import com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.internal.store.hibernate.XWikiHibernateDeletedDocumentContent;\nimport com.xpn.xwiki.util.AbstractSimpleClass;\nimport com.xpn.xwiki.util.Util;\nimport com.xpn.xwiki.web.Utils;",
"/**\n * Archive of deleted document, stored in {@link com.xpn.xwiki.store.XWikiRecycleBinStoreInterface}. Immutable, because\n * we don't need modify deleted document.\n *\n * @version $Id$\n * @since 1.2M1\n */\npublic class XWikiDeletedDocument extends AbstractSimpleClass\n{\n /**\n * Synthetic id.\n */\n private long id;",
" /**\n * @see XWikiDocument#getFullName()\n */\n private String fullName;",
" /**\n * @see XWikiDocument#getLocale()\n */\n private Locale locale;",
" /**\n * date of delete action.\n */\n private Date date;",
" /**\n * @see XWikiDeletedDocument#getDeleter()\n */\n private String deleter;",
" private String xmlStore;",
" private XWikiDeletedDocumentContent content;",
" private String batchId;",
" /**\n * Default constructor. Used only in hibernate.\n */\n protected XWikiDeletedDocument()\n {\n }",
" /**\n * @param fullName the local reference of the document\n * @param locale the locale of the document\n * @param storeType - the way to store the document\n * @param deleter - user which delete document\n * @param deleteDate - date of delete action\n * @throws XWikiException if any error\n * @since 9.0RC1\n */\n private XWikiDeletedDocument(String fullName, Locale locale, String storeType, String deleter, Date deleteDate)\n throws XWikiException\n {\n this.fullName = fullName;\n this.locale = locale;\n this.deleter = deleter;\n this.date = deleteDate;\n this.xmlStore = storeType;\n }",
" /**\n * @param doc - deleted document\n * @param deleter - user which delete document\n * @param deleteDate - date of delete action\n * @param context - used for environment\n * @throws XWikiException if any error\n */\n public XWikiDeletedDocument(XWikiDocument doc, String deleter, Date deleteDate, XWikiContext context)\n throws XWikiException\n {\n this(doc.getFullName(), doc.getLocale(), null, deleter, deleteDate);",
" setDocument(doc, context);\n }",
" /**\n * @param fullName the local reference of the document\n * @param locale the locale of the document\n * @param storeType the way to store the document\n * @param deleter the user who delete document\n * @param deleteDate date of delete action\n * @param content the stored deleted document\n * @throws XWikiException if any error\n * @since 9.0RC1\n */\n public XWikiDeletedDocument(String fullName, Locale locale, String storeType, String deleter, Date deleteDate,\n XWikiDeletedDocumentContent content) throws XWikiException\n {\n this(fullName, locale, storeType, deleter, deleteDate);",
" this.content = content;\n }",
" /**\n * @param fullName the local reference of the document\n * @param locale the locale of the document\n * @param storeType the way to store the document\n * @param deleter the user who delete document\n * @param deleteDate date of delete action\n * @param content the stored deleted document\n * @param batchId the id of the batch deletion\n * @throws XWikiException if any error\n * @since 9.4RC1\n */\n public XWikiDeletedDocument(String fullName, Locale locale, String storeType, String deleter, Date deleteDate,\n XWikiDeletedDocumentContent content, String batchId) throws XWikiException\n {\n this(fullName, locale, storeType, deleter, deleteDate, content);",
" this.batchId = batchId;\n }",
" /**\n * @return the synthetic id of this deleted document. unique only for document.\n */\n public long getId()\n {\n return this.id;\n }",
" /**\n * @param id - the synthetic id to set. used only in Hibernate.\n */\n protected void setId(long id)\n {\n this.id = id;\n }",
" /**\n * @return {@link XWikiDocument#getFullName()}\n */\n public String getFullName()\n {\n return this.fullName;\n }",
" /**\n * @param docFullName - {@link XWikiDocument#getFullName()} to set\n */\n protected void setFullName(String docFullName)\n {\n this.fullName = docFullName;\n }",
" /**\n * @return the document reference for the deleted document, including any locale information\n * @since 9.4RC1\n */\n public DocumentReference getDocumentReference()\n {\n DocumentReference documentReference = getDocumentReferenceResolver().resolve(getFullName());",
" Locale localeValue = getLocale();\n if (localeValue != null) {\n documentReference = new DocumentReference(documentReference, localeValue);\n }",
" return documentReference;\n }",
" private static DocumentReferenceResolver<String> getDocumentReferenceResolver()\n {\n return Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, \"currentmixed\");\n }",
" /**\n * @return {@link XWikiDocument#getLanguage()}\n * @deprecated since 8.0M1, use {@link #getLocale()} instead\n */\n @Deprecated\n public String getLanguage()\n {\n return getLocale().toString();\n }",
" /**\n * @return {@link XWikiDocument#getLocale()}\n * @since 8.0M1\n */\n public Locale getLocale()\n {\n return this.locale != null ? this.locale : Locale.ROOT;\n }",
" /**\n * @param locale - {@link XWikiDocument#getLanguage()} to set\n * @deprecated since 8.0M1\n */\n @Deprecated\n protected void setLanguage(String locale)\n {\n this.locale = LocaleUtils.toLocale(Util.normalizeLanguage(locale), Locale.ROOT);\n }",
" /**\n * @return the date of delete action\n */\n public Date getDate()\n {\n return this.date;\n }",
" /**\n * @param date - the date of delete action to set\n */\n protected void setDate(Date date)\n {\n this.date = date;\n }",
" /**\n * @return the user which has removed the document\n */\n public String getDeleter()\n {\n return this.deleter;\n }",
" /**\n * @return the reference of the user who deleted this document\n * @since 11.5RC1\n */\n public DocumentReference getDeleterReference()\n {\n return getDocumentReferenceResolver().resolve(this.deleter);\n }",
" /**\n * @param deleter - the user which has removed the document to set\n */\n protected void setDeleter(String deleter)\n {\n this.deleter = deleter;\n }",
" /**\n * @return the type of the store used for the content\n * @since 9.0RC1\n */\n public String getXmlStore()\n {\n return this.xmlStore;\n }",
" /**\n * @param xmlStore the type of store (supported values are null/\"hibernate\" and \"file\")\n * @since 9.0RC1\n */\n protected void setXmlStore(String xmlStore)\n {\n this.xmlStore = xmlStore;\n }",
" /**\n * Only used in Hibernate.\n * \n * @return xml serialization of {@link XWikiDocument}\n */\n public String getXml()\n {\n if (this.content != null) {\n try {\n return this.content.getContentAsString();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
" // Return empty String instead of null because this field is configured as not null at database level\n return \"\";\n }",
" /**\n * Only used in Hibernate.\n * \n * @param xml - xml serialization of {@link XWikiDocument}\n */\n protected void setXml(String xml)\n {\n if (StringUtils.isNotEmpty(xml)) {\n try {\n this.content = new XWikiHibernateDeletedDocumentContent(xml);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }",
" /**\n * Export {@link XWikiDocument} to {@link XWikiDeletedDocument}.\n *\n * @param doc - the deleted document\n * @param context - used in {@link XWikiDocument#toXML(XWikiContext)}\n * @throws XWikiException in error in {@link XWikiDocument#toXML(XWikiContext)}\n * @deprecated since 9.0RC1, use\n * {@link XWikiDeletedDocument#XWikiDeletedDocument(String, Locale, String, String, Date, XWikiDeletedDocumentContent)\n * instead}\n */\n @Deprecated\n protected void setDocument(XWikiDocument doc, XWikiContext context) throws XWikiException\n {\n this.content = new XWikiHibernateDeletedDocumentContent(doc);\n }",
" /**\n * @return restored document\n * @param doc optional object where to put the document data, if not <code>null</code>\n * @param context the current {@link XWikiContext context}\n * @throws XWikiException if error in {@link XWikiDocument#fromXML(String)}\n */\n public XWikiDocument restoreDocument(XWikiDocument doc, XWikiContext context) throws XWikiException\n {\n if (this.content == null) {\n throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING,\n \"Cannot find any content for the deleted document [\" + this.fullName + \" (\" + this.locale + \")]\");\n }",
" try {\n return this.content.getXWikiDocument(doc);\n } catch (IOException e) {\n throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING,\n \"Error restoring document\", e, null);\n }\n }",
" /**\n * @return restored document\n * @param context the current {@link XWikiContext context}\n * @throws XWikiException if error in {@link XWikiDocument#fromXML(String)}\n * @since 9.0RC1\n */\n public XWikiDocument restoreDocument(XWikiContext context) throws XWikiException\n {\n return restoreDocument(null, context);\n }",
" /**\n * @param batchId batch operation ID to set\n * @since 9.4RC1\n */\n protected void setBatchId(String batchId)\n {\n this.batchId = batchId;\n }",
" /**\n * @return the id of the operation that deleted multiple documents at the same time, including this one\n * @since 9.4RC1\n */\n public String getBatchId()\n {\n return batchId;\n }",
"\n @Override\n public String toString()\n {\n return new ToStringBuilder(this)\n .append(\"id\", id)\n .append(\"fullName\", fullName)\n .append(\"locale\", locale)\n .toString();\n }",
"}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.internal.doc;",
"import javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.inject.Provider;\nimport javax.inject.Singleton;\n",
"",
"import org.xwiki.component.annotation.Component;\nimport org.xwiki.component.manager.ComponentLookupException;\nimport org.xwiki.component.manager.ComponentManager;\nimport org.xwiki.model.reference.DocumentReference;",
"",
"\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.DocumentRevisionProvider;\nimport com.xpn.xwiki.doc.XWikiDocument;",
"/**\n * The default implementation of {@link DocumentRevisionProvider}.\n * <p>\n * The main job of {@link DefaultDocumentRevisionProvider} is to call the right {@link DocumentRevisionProvider}\n * depending on the revision prefix.\n * \n * @version $Id$\n * @since 9.3rc1\n */\n@Component\n@Singleton\npublic class DefaultDocumentRevisionProvider extends AbstractDocumentRevisionProvider\n{\n @Inject\n @Named(\"context\")\n private Provider<ComponentManager> componentManagerProvider;",
" @Inject\n @Named(\"database\")\n private DocumentRevisionProvider databaseDocumentRevisionProvider;\n",
" @Override\n public XWikiDocument getRevision(DocumentReference reference, String revision) throws XWikiException",
" {",
" // Parse the version",
" String revisionPrefix = null;\n if (revision != null) {\n int revisionPrefixIndex = revision.indexOf(':');\n if (revisionPrefixIndex > 0) {\n revisionPrefix = revision.substring(0, revisionPrefixIndex);\n }\n }\n String shortRevision;\n if (revisionPrefix != null) {\n shortRevision = revision.substring(revisionPrefix.length() + 1);\n } else {\n shortRevision = revision;\n }",
"",
"",
"",
" // Find the provider\n DocumentRevisionProvider provider = this.databaseDocumentRevisionProvider;\n if (revisionPrefix != null) {\n ComponentManager componentManager = this.componentManagerProvider.get();\n if (componentManager.hasComponent(DocumentRevisionProvider.class, revisionPrefix)) {\n try {\n provider = componentManager.getInstance(DocumentRevisionProvider.class, revisionPrefix);\n } catch (ComponentLookupException e) {",
" throw new XWikiException(\"Failed to get revision provider for revision [\" + revision + \"]\", e);",
" }\n }\n }",
"",
"\n // Load the document revision",
" return provider.getRevision(reference, shortRevision);",
" }\n}"
] |
[
1,
1,
0,
1,
0,
1,
1,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.internal.doc;",
"import javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.inject.Provider;\nimport javax.inject.Singleton;\n",
"import org.apache.commons.lang3.tuple.Pair;",
"import org.xwiki.component.annotation.Component;\nimport org.xwiki.component.manager.ComponentLookupException;\nimport org.xwiki.component.manager.ComponentManager;\nimport org.xwiki.model.reference.DocumentReference;",
"import org.xwiki.security.authorization.AuthorizationException;\nimport org.xwiki.security.authorization.Right;\nimport org.xwiki.user.UserReference;",
"\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.DocumentRevisionProvider;\nimport com.xpn.xwiki.doc.XWikiDocument;",
"/**\n * The default implementation of {@link DocumentRevisionProvider}.\n * <p>\n * The main job of {@link DefaultDocumentRevisionProvider} is to call the right {@link DocumentRevisionProvider}\n * depending on the revision prefix.\n * \n * @version $Id$\n * @since 9.3rc1\n */\n@Component\n@Singleton\npublic class DefaultDocumentRevisionProvider extends AbstractDocumentRevisionProvider\n{\n @Inject\n @Named(\"context\")\n private Provider<ComponentManager> componentManagerProvider;",
" @Inject\n @Named(\"database\")\n private DocumentRevisionProvider databaseDocumentRevisionProvider;\n",
" private Pair<String, String> parseRevision(String revision)",
" {",
"",
" String revisionPrefix = null;\n if (revision != null) {\n int revisionPrefixIndex = revision.indexOf(':');\n if (revisionPrefixIndex > 0) {\n revisionPrefix = revision.substring(0, revisionPrefixIndex);\n }\n }\n String shortRevision;\n if (revisionPrefix != null) {\n shortRevision = revision.substring(revisionPrefix.length() + 1);\n } else {\n shortRevision = revision;\n }",
" return Pair.of(revisionPrefix, shortRevision);\n }",
"",
" private DocumentRevisionProvider getProvider(String revisionPrefix) throws XWikiException\n {",
" // Find the provider\n DocumentRevisionProvider provider = this.databaseDocumentRevisionProvider;\n if (revisionPrefix != null) {\n ComponentManager componentManager = this.componentManagerProvider.get();\n if (componentManager.hasComponent(DocumentRevisionProvider.class, revisionPrefix)) {\n try {\n provider = componentManager.getInstance(DocumentRevisionProvider.class, revisionPrefix);\n } catch (ComponentLookupException e) {",
" throw new XWikiException(\"Failed to get revision provider for revision [\" + revisionPrefix + \"]\",\n e);",
" }\n }\n }",
" return provider;\n }",
" @Override\n public XWikiDocument getRevision(DocumentReference reference, String revision) throws XWikiException\n {\n Pair<String, String> parsedRevision = parseRevision(revision);",
"\n // Load the document revision",
" return getProvider(parsedRevision.getLeft()).getRevision(reference, parsedRevision.getRight());\n }",
" @Override\n public void checkAccess(Right right, UserReference userReference, DocumentReference documentReference,\n String revision) throws AuthorizationException, XWikiException\n {\n Pair<String, String> parsedRevision = parseRevision(revision);",
" getProvider(parsedRevision.getLeft())\n .checkAccess(right, userReference, documentReference, parsedRevision.getRight());",
" }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.internal.doc;",
"import javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.inject.Provider;\nimport javax.inject.Singleton;",
"import org.xwiki.component.annotation.Component;\nimport org.xwiki.model.reference.DocumentReference;",
"",
"\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.DocumentRevisionProvider;\nimport com.xpn.xwiki.doc.XWikiDeletedDocument;\nimport com.xpn.xwiki.doc.XWikiDocument;",
"/**\n * Get deleted document revisions from the database.\n * \n * @version $Id$\n * @since 9.4RC1\n */\n@Component\n@Named(\"deleted\")\n@Singleton\npublic class DeletedDocumentRevisionProvider implements DocumentRevisionProvider\n{\n @Inject\n private Provider<XWikiContext> xcontextProvider;",
" @Override\n public XWikiDocument getRevision(DocumentReference reference, String revision) throws XWikiException\n {\n XWikiContext xcontext = this.xcontextProvider.get();",
" XWikiDeletedDocument deletedDocument = xcontext.getWiki().getDeletedDocument(Long.valueOf(revision), xcontext);",
" // Only local the document if it matches the asked document reference\n if (deletedDocument != null\n && (reference == null || deletedDocument.getDocumentReference().equals(reference))) {\n return deletedDocument.restoreDocument(xcontext);\n }",
" return null;",
"",
" }",
" @Override\n public XWikiDocument getRevision(XWikiDocument document, String revision) throws XWikiException\n {\n return getRevision(document != null ? document.getDocumentReferenceWithLocale() : null, revision);\n }",
"",
"}"
] |
[
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
0,
1,
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.internal.doc;",
"import javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.inject.Provider;\nimport javax.inject.Singleton;",
"import org.xwiki.component.annotation.Component;\nimport org.xwiki.model.reference.DocumentReference;",
"import org.xwiki.security.authorization.AuthorizationException;\nimport org.xwiki.security.authorization.Right;\nimport org.xwiki.user.UserReference;",
"\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.DocumentRevisionProvider;\nimport com.xpn.xwiki.doc.XWikiDeletedDocument;\nimport com.xpn.xwiki.doc.XWikiDocument;",
"/**\n * Get deleted document revisions from the database.\n * \n * @version $Id$\n * @since 9.4RC1\n */\n@Component\n@Named(\"deleted\")\n@Singleton\npublic class DeletedDocumentRevisionProvider implements DocumentRevisionProvider\n{\n @Inject\n private Provider<XWikiContext> xcontextProvider;",
" @Override\n public XWikiDocument getRevision(DocumentReference reference, String revision) throws XWikiException\n {\n XWikiContext xcontext = this.xcontextProvider.get();",
" XWikiDeletedDocument deletedDocument = xcontext.getWiki().getDeletedDocument(Long.valueOf(revision), xcontext);",
" // Only local the document if it matches the asked document reference\n if (deletedDocument != null\n && (reference == null || deletedDocument.getDocumentReference().equals(reference))) {\n return deletedDocument.restoreDocument(xcontext);\n }",
" return null;",
"",
" }",
" @Override\n public XWikiDocument getRevision(XWikiDocument document, String revision) throws XWikiException\n {\n return getRevision(document != null ? document.getDocumentReferenceWithLocale() : null, revision);\n }",
"\n @Override\n public void checkAccess(Right right, UserReference userReference, DocumentReference documentReference,\n String revision) throws AuthorizationException, XWikiException\n {\n XWikiContext xcontext = this.xcontextProvider.get();",
" XWikiDeletedDocument deletedDocument = xcontext.getWiki().getDeletedDocument(Long.valueOf(revision), xcontext);\n if (deletedDocument != null) {\n xcontext.getWiki().getRecycleBinStore().checkAccess(right, userReference, deletedDocument);\n }\n }",
"}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.store;",
"import java.util.Date;\nimport java.util.List;\nimport java.util.Locale;",
"",
"\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.inject.Singleton;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Path;\nimport javax.persistence.criteria.Predicate;\nimport javax.persistence.criteria.Root;",
"import org.apache.commons.lang3.reflect.FieldUtils;\nimport org.hibernate.HibernateException;\nimport org.hibernate.Session;\nimport org.slf4j.Logger;\nimport org.xwiki.component.annotation.Component;\nimport org.xwiki.component.manager.ComponentLookupException;\nimport org.xwiki.component.manager.ComponentManager;",
"",
"\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.XWikiDeletedDocument;\nimport com.xpn.xwiki.doc.XWikiDeletedDocumentContent;\nimport com.xpn.xwiki.doc.XWikiDocument;\nimport com.xpn.xwiki.internal.store.StoreConfiguration;\nimport com.xpn.xwiki.internal.store.hibernate.XWikiHibernateDeletedDocumentContent;",
"/**\n * Realization of {@link XWikiRecycleBinStoreInterface} for Hibernate store.\n *\n * @version $Id$\n */\n@Component\n@Named(XWikiHibernateBaseStore.HINT)\n@Singleton\npublic class XWikiHibernateRecycleBinStore extends XWikiHibernateBaseStore implements XWikiRecycleBinStoreInterface\n{",
"",
" /**\n * {@link HibernateCallback} used to retrieve from the recycle bin store the deleted versions of a document.\n */\n private static class DeletedDocumentsHibernateCallback implements HibernateCallback<XWikiDeletedDocument[]>\n {\n /**\n * The document whose versions are retrieved from the recycle bin store.\n */\n private XWikiDocument document;",
" /**\n * Creates a new call-back for the given document.\n *\n * @param document the document whose deleted versions you want to retrieve from the recycle bin store\n */\n DeletedDocumentsHibernateCallback(XWikiDocument document)\n {\n this.document = document;\n }",
" @Override\n public XWikiDeletedDocument[] doInHibernate(Session session) throws HibernateException, XWikiException\n {\n CriteriaBuilder builder = session.getCriteriaBuilder();\n CriteriaQuery<XWikiDeletedDocument> query = builder.createQuery(XWikiDeletedDocument.class);\n Root<XWikiDeletedDocument> root = query.from(XWikiDeletedDocument.class);",
" query.select(root);",
" Predicate[] predicates = new Predicate[2];",
" predicates[0] = builder.equal(root.get(FULL_NAME_FIELD), this.document.getFullName());",
" // Note: We need to support databases who treats empty strings as NULL like Oracle. For those checking\n // for equality when the string is empty is not going to work and thus we need to handle the special\n // empty case separately.\n Locale language = this.document.getLocale();\n Path<String> languageProperty = root.get(LANGUAGE_PROPERTY_NAME);\n if (language.equals(Locale.ROOT)) {\n predicates[1] = builder.or(builder.equal(languageProperty, \"\"), builder.isNull(languageProperty));\n } else {\n predicates[1] = builder.equal(languageProperty, language);\n }",
" query.where(predicates);",
" query.orderBy(builder.desc(root.get(\"date\")));",
" List<XWikiDeletedDocument> deletedVersions = session.createQuery(query).getResultList();",
" return deletedVersions.toArray(new XWikiDeletedDocument[deletedVersions.size()]);\n }\n }",
" /**\n * {@link HibernateCallback} used to retrieve from the recycle bin store the deleted document versions from a given\n * batch.\n */\n private static class DeletedDocumentsBatchHibernateCallback implements HibernateCallback<XWikiDeletedDocument[]>\n {\n private String batchId;",
" /**\n * Creates a new call-back for the given batch.\n *\n * @param batchId the ID of the batch of deleted documents you want to retrieve from the recycle bin store\n */\n DeletedDocumentsBatchHibernateCallback(String batchId)\n {\n this.batchId = batchId;\n }",
" @Override\n public XWikiDeletedDocument[] doInHibernate(Session session) throws HibernateException, XWikiException\n {\n CriteriaBuilder builder = session.getCriteriaBuilder();\n CriteriaQuery<XWikiDeletedDocument> query = builder.createQuery(XWikiDeletedDocument.class);\n Root<XWikiDeletedDocument> root = query.from(XWikiDeletedDocument.class);",
" query.select(root);",
" query.where(builder.equal(root.get(\"batchId\"), batchId));",
" query.orderBy(builder.asc(root.get(FULL_NAME_FIELD)));",
" List<XWikiDeletedDocument> deletedVersions = session.createQuery(query).getResultList();",
" return deletedVersions.toArray(new XWikiDeletedDocument[deletedVersions.size()]);\n }\n }",
" private static final String FULL_NAME_FIELD = \"fullName\";",
" /**\n * Name of the language property in the Hibernate mapping.\n */\n private static final String LANGUAGE_PROPERTY_NAME = \"language\";",
" @Inject\n private StoreConfiguration storeConfiguration;",
" @Inject\n private ComponentManager componentManager;",
" @Inject\n private Logger logger;",
" /**\n * @param context used for environment\n * @deprecated 1.6M1. Use ComponentManager#getInstance(XWikiRecycleBinStoreInterface.class) instead.\n */\n @Deprecated\n public XWikiHibernateRecycleBinStore(XWikiContext context)\n {\n super(context.getWiki(), context);\n }",
" /**\n * Empty constructor needed for component manager.\n */\n public XWikiHibernateRecycleBinStore()\n {\n }",
" private XWikiRecycleBinContentStoreInterface getDefaultXWikiRecycleBinContentStore() throws XWikiException\n {\n try {\n return this.storeConfiguration.getXWikiRecycleBinContentStore();\n } catch (ComponentLookupException e) {\n throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_UNKNOWN,\n \"Failed to lookup recycle bin content store\", e);\n }\n }",
" private XWikiRecycleBinContentStoreInterface getXWikiRecycleBinContentStore(String storeType)\n {\n if (storeType != null && !storeType.equals(HINT)) {\n try {\n return this.componentManager.getInstance(XWikiRecycleBinContentStoreInterface.class, storeType);\n } catch (ComponentLookupException e) {\n this.logger.warn(\"Can't find recycle bin content store for type [{}]\", storeType, e);\n }\n }",
" return null;\n }",
" private XWikiDeletedDocument resolveDeletedDocumentContent(XWikiDeletedDocument deletedDocument,\n boolean bTransaction) throws XWikiException\n {\n XWikiRecycleBinContentStoreInterface contentStore =\n getXWikiRecycleBinContentStore(deletedDocument.getXmlStore());",
" if (contentStore != null) {\n XWikiDeletedDocumentContent content =\n contentStore.get(deletedDocument.getDocumentReference(), deletedDocument.getId(), bTransaction);",
" try {\n FieldUtils.writeDeclaredField(deletedDocument, \"content\", content, true);\n } catch (IllegalAccessException e) {\n throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_UNKNOWN,\n \"Failed to set deleted document content\", e);\n }\n }",
" return deletedDocument;\n }",
" private XWikiDeletedDocument createXWikiDeletedDocument(XWikiDocument doc, String deleter, Date date,\n XWikiRecycleBinContentStoreInterface contentStore, String batchId) throws XWikiException\n {\n XWikiDeletedDocument trashdoc;",
" String storeType = null;\n XWikiDeletedDocumentContent deletedDocumentContent = null;",
" if (contentStore != null) {\n storeType = contentStore.getHint();\n } else {\n deletedDocumentContent = new XWikiHibernateDeletedDocumentContent(doc);\n }",
" trashdoc = new XWikiDeletedDocument(doc.getFullName(), doc.getLocale(), storeType, deleter, date,\n deletedDocumentContent, batchId);",
" return trashdoc;\n }",
" private void deleteDeletedDocumentContent(XWikiDeletedDocument deletedDocument, boolean bTransaction)\n throws XWikiException\n {\n XWikiRecycleBinContentStoreInterface contentStore =\n getXWikiRecycleBinContentStore(deletedDocument.getXmlStore());",
" if (contentStore != null) {\n contentStore.delete(deletedDocument.getDocumentReference(), deletedDocument.getId(), bTransaction);\n }\n }",
" @Override\n public void saveToRecycleBin(XWikiDocument doc, String deleter, Date date, XWikiContext inputxcontext,\n boolean bTransaction) throws XWikiException\n {\n saveToRecycleBin(doc, deleter, date, null, inputxcontext, bTransaction);\n }",
" @Override\n public void saveToRecycleBin(XWikiDocument doc, String deleter, Date date, String batchId,\n XWikiContext inputxcontext, boolean bTransaction) throws XWikiException\n {\n XWikiContext context = getExecutionXContext(inputxcontext, true);",
" try {\n executeWrite(context, session -> {\n XWikiRecycleBinContentStoreInterface contentStore = getDefaultXWikiRecycleBinContentStore();",
" XWikiDeletedDocument trashdoc = createXWikiDeletedDocument(doc, deleter, date, contentStore, batchId);",
" // Hibernate store.\n long index = ((Number) session.save(trashdoc)).longValue();",
" // External store\n if (contentStore != null) {\n contentStore.save(doc, index, bTransaction);\n }",
" return null;\n });\n } finally {\n restoreExecutionXContext();\n }\n }",
" @Override\n public XWikiDocument restoreFromRecycleBin(final XWikiDocument doc, final long index,\n final XWikiContext inputxcontext, boolean bTransaction) throws XWikiException\n {\n return restoreFromRecycleBin(index, inputxcontext, bTransaction);\n }",
" @Override\n public XWikiDocument restoreFromRecycleBin(long index, XWikiContext inputxcontext, boolean bTransaction)\n throws XWikiException\n {\n XWikiContext context = getExecutionXContext(inputxcontext, true);",
" try {\n XWikiDeletedDocument deletedDocument = getDeletedDocument(index, context, bTransaction);\n return deletedDocument.restoreDocument(context);\n } finally {\n restoreExecutionXContext();\n }\n }",
" @Override\n public XWikiDeletedDocument getDeletedDocument(XWikiDocument doc, final long index, XWikiContext context,\n boolean bTransaction) throws XWikiException\n {\n return getDeletedDocument(index, context, bTransaction);\n }",
" @Override\n public XWikiDeletedDocument getDeletedDocument(long index, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n return getDeletedDocument(index, context, true, bTransaction);\n }",
" private XWikiDeletedDocument getDeletedDocument(final long index, XWikiContext context, boolean resolve,\n boolean bTransaction) throws XWikiException\n {\n return executeRead(context, session -> {\n XWikiDeletedDocument deletedDocument = session.get(XWikiDeletedDocument.class, Long.valueOf(index));",
" if (deletedDocument != null && resolve) {\n deletedDocument = resolveDeletedDocumentContent(deletedDocument, false);\n }",
" return deletedDocument;\n });\n }",
" @Override\n public XWikiDeletedDocument[] getAllDeletedDocuments(XWikiDocument doc, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n XWikiDeletedDocument[] deletedDocuments = executeRead(context, new DeletedDocumentsHibernateCallback(doc));",
" // Resolve deleted document content if needed\n for (int i = 0; i < deletedDocuments.length; ++i) {\n deletedDocuments[i] = resolveDeletedDocumentContent(deletedDocuments[i], bTransaction);\n }",
" return deletedDocuments;\n }",
" @Override\n public Long[] getAllDeletedDocumentsIds(XWikiContext context, int limit) throws XWikiException\n {\n return executeRead(context, session -> {\n org.hibernate.query.Query<Long> query =\n session.createQuery(\"SELECT id FROM XWikiDeletedDocument ORDER BY date DESC\", Long.class);",
" if (limit > 0) {\n query.setMaxResults(limit);\n }",
" List<Long> deletedDocIds = query.list();\n Long[] result = new Long[deletedDocIds.size()];\n return deletedDocIds.toArray(result);\n });\n }",
" @Override\n public Long getNumberOfDeletedDocuments(XWikiContext context) throws XWikiException\n {",
" return executeRead(context, session -> {\n org.hibernate.query.Query<Long> query =\n session.createQuery(\"SELECT count(id) FROM XWikiDeletedDocument\", Long.class);",
" return query.uniqueResult();\n });\n }",
" @Override\n public XWikiDeletedDocument[] getAllDeletedDocuments(String batchId, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n return getAllDeletedDocuments(batchId, true, context, bTransaction);\n }",
" @Override\n public XWikiDeletedDocument[] getAllDeletedDocuments(String batchId, boolean withContent, XWikiContext context,\n boolean bTransaction) throws XWikiException\n {\n XWikiDeletedDocument[] deletedDocuments =\n executeRead(context, new DeletedDocumentsBatchHibernateCallback(batchId));",
" // Resolve deleted document content if needed\n if (withContent) {\n for (int i = 0; i < deletedDocuments.length; ++i) {\n XWikiDeletedDocument deletedDocument = deletedDocuments[i];\n deletedDocuments[i] = resolveDeletedDocumentContent(deletedDocument, bTransaction);\n }\n }",
" return deletedDocuments;\n }",
" @Override\n public void deleteFromRecycleBin(XWikiDocument doc, final long index, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n deleteFromRecycleBin(index, context, bTransaction);\n }",
" @Override\n public void deleteFromRecycleBin(final long index, XWikiContext context, boolean bTransaction) throws XWikiException\n {\n executeWrite(context, session -> {\n XWikiDeletedDocument deletedDocument = getDeletedDocument(index, context, false, bTransaction);",
" // Delete metadata\n session.delete(deletedDocument);",
" // Delete content\n deleteDeletedDocumentContent(deletedDocument, bTransaction);",
" return null;\n });\n }",
"",
"}"
] |
[
1,
1,
0,
1,
1,
0,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.store;",
"import java.util.Date;\nimport java.util.List;\nimport java.util.Locale;",
"import java.util.Objects;",
"\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.inject.Singleton;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Path;\nimport javax.persistence.criteria.Predicate;\nimport javax.persistence.criteria.Root;",
"import org.apache.commons.lang3.reflect.FieldUtils;\nimport org.hibernate.HibernateException;\nimport org.hibernate.Session;\nimport org.slf4j.Logger;\nimport org.xwiki.component.annotation.Component;\nimport org.xwiki.component.manager.ComponentLookupException;\nimport org.xwiki.component.manager.ComponentManager;",
"import org.xwiki.model.reference.DocumentReference;\nimport org.xwiki.security.authorization.AuthorizationException;\nimport org.xwiki.security.authorization.AuthorizationManager;\nimport org.xwiki.security.authorization.Right;\nimport org.xwiki.user.UserReference;\nimport org.xwiki.user.UserReferenceSerializer;",
"\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.XWikiDeletedDocument;\nimport com.xpn.xwiki.doc.XWikiDeletedDocumentContent;\nimport com.xpn.xwiki.doc.XWikiDocument;\nimport com.xpn.xwiki.internal.store.StoreConfiguration;\nimport com.xpn.xwiki.internal.store.hibernate.XWikiHibernateDeletedDocumentContent;",
"/**\n * Realization of {@link XWikiRecycleBinStoreInterface} for Hibernate store.\n *\n * @version $Id$\n */\n@Component\n@Named(XWikiHibernateBaseStore.HINT)\n@Singleton\npublic class XWikiHibernateRecycleBinStore extends XWikiHibernateBaseStore implements XWikiRecycleBinStoreInterface\n{",
" @Inject\n private AuthorizationManager authorizationManager;",
" @Inject\n @Named(\"document\")\n private UserReferenceSerializer<DocumentReference> userReferenceSerializer;\n",
" /**\n * {@link HibernateCallback} used to retrieve from the recycle bin store the deleted versions of a document.\n */\n private static class DeletedDocumentsHibernateCallback implements HibernateCallback<XWikiDeletedDocument[]>\n {\n /**\n * The document whose versions are retrieved from the recycle bin store.\n */\n private XWikiDocument document;",
" /**\n * Creates a new call-back for the given document.\n *\n * @param document the document whose deleted versions you want to retrieve from the recycle bin store\n */\n DeletedDocumentsHibernateCallback(XWikiDocument document)\n {\n this.document = document;\n }",
" @Override\n public XWikiDeletedDocument[] doInHibernate(Session session) throws HibernateException, XWikiException\n {\n CriteriaBuilder builder = session.getCriteriaBuilder();\n CriteriaQuery<XWikiDeletedDocument> query = builder.createQuery(XWikiDeletedDocument.class);\n Root<XWikiDeletedDocument> root = query.from(XWikiDeletedDocument.class);",
" query.select(root);",
" Predicate[] predicates = new Predicate[2];",
" predicates[0] = builder.equal(root.get(FULL_NAME_FIELD), this.document.getFullName());",
" // Note: We need to support databases who treats empty strings as NULL like Oracle. For those checking\n // for equality when the string is empty is not going to work and thus we need to handle the special\n // empty case separately.\n Locale language = this.document.getLocale();\n Path<String> languageProperty = root.get(LANGUAGE_PROPERTY_NAME);\n if (language.equals(Locale.ROOT)) {\n predicates[1] = builder.or(builder.equal(languageProperty, \"\"), builder.isNull(languageProperty));\n } else {\n predicates[1] = builder.equal(languageProperty, language);\n }",
" query.where(predicates);",
" query.orderBy(builder.desc(root.get(\"date\")));",
" List<XWikiDeletedDocument> deletedVersions = session.createQuery(query).getResultList();",
" return deletedVersions.toArray(new XWikiDeletedDocument[deletedVersions.size()]);\n }\n }",
" /**\n * {@link HibernateCallback} used to retrieve from the recycle bin store the deleted document versions from a given\n * batch.\n */\n private static class DeletedDocumentsBatchHibernateCallback implements HibernateCallback<XWikiDeletedDocument[]>\n {\n private String batchId;",
" /**\n * Creates a new call-back for the given batch.\n *\n * @param batchId the ID of the batch of deleted documents you want to retrieve from the recycle bin store\n */\n DeletedDocumentsBatchHibernateCallback(String batchId)\n {\n this.batchId = batchId;\n }",
" @Override\n public XWikiDeletedDocument[] doInHibernate(Session session) throws HibernateException, XWikiException\n {\n CriteriaBuilder builder = session.getCriteriaBuilder();\n CriteriaQuery<XWikiDeletedDocument> query = builder.createQuery(XWikiDeletedDocument.class);\n Root<XWikiDeletedDocument> root = query.from(XWikiDeletedDocument.class);",
" query.select(root);",
" query.where(builder.equal(root.get(\"batchId\"), batchId));",
" query.orderBy(builder.asc(root.get(FULL_NAME_FIELD)));",
" List<XWikiDeletedDocument> deletedVersions = session.createQuery(query).getResultList();",
" return deletedVersions.toArray(new XWikiDeletedDocument[deletedVersions.size()]);\n }\n }",
" private static final String FULL_NAME_FIELD = \"fullName\";",
" /**\n * Name of the language property in the Hibernate mapping.\n */\n private static final String LANGUAGE_PROPERTY_NAME = \"language\";",
" @Inject\n private StoreConfiguration storeConfiguration;",
" @Inject\n private ComponentManager componentManager;",
" @Inject\n private Logger logger;",
" /**\n * @param context used for environment\n * @deprecated 1.6M1. Use ComponentManager#getInstance(XWikiRecycleBinStoreInterface.class) instead.\n */\n @Deprecated\n public XWikiHibernateRecycleBinStore(XWikiContext context)\n {\n super(context.getWiki(), context);\n }",
" /**\n * Empty constructor needed for component manager.\n */\n public XWikiHibernateRecycleBinStore()\n {\n }",
" private XWikiRecycleBinContentStoreInterface getDefaultXWikiRecycleBinContentStore() throws XWikiException\n {\n try {\n return this.storeConfiguration.getXWikiRecycleBinContentStore();\n } catch (ComponentLookupException e) {\n throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_UNKNOWN,\n \"Failed to lookup recycle bin content store\", e);\n }\n }",
" private XWikiRecycleBinContentStoreInterface getXWikiRecycleBinContentStore(String storeType)\n {\n if (storeType != null && !storeType.equals(HINT)) {\n try {\n return this.componentManager.getInstance(XWikiRecycleBinContentStoreInterface.class, storeType);\n } catch (ComponentLookupException e) {\n this.logger.warn(\"Can't find recycle bin content store for type [{}]\", storeType, e);\n }\n }",
" return null;\n }",
" private XWikiDeletedDocument resolveDeletedDocumentContent(XWikiDeletedDocument deletedDocument,\n boolean bTransaction) throws XWikiException\n {\n XWikiRecycleBinContentStoreInterface contentStore =\n getXWikiRecycleBinContentStore(deletedDocument.getXmlStore());",
" if (contentStore != null) {\n XWikiDeletedDocumentContent content =\n contentStore.get(deletedDocument.getDocumentReference(), deletedDocument.getId(), bTransaction);",
" try {\n FieldUtils.writeDeclaredField(deletedDocument, \"content\", content, true);\n } catch (IllegalAccessException e) {\n throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_UNKNOWN,\n \"Failed to set deleted document content\", e);\n }\n }",
" return deletedDocument;\n }",
" private XWikiDeletedDocument createXWikiDeletedDocument(XWikiDocument doc, String deleter, Date date,\n XWikiRecycleBinContentStoreInterface contentStore, String batchId) throws XWikiException\n {\n XWikiDeletedDocument trashdoc;",
" String storeType = null;\n XWikiDeletedDocumentContent deletedDocumentContent = null;",
" if (contentStore != null) {\n storeType = contentStore.getHint();\n } else {\n deletedDocumentContent = new XWikiHibernateDeletedDocumentContent(doc);\n }",
" trashdoc = new XWikiDeletedDocument(doc.getFullName(), doc.getLocale(), storeType, deleter, date,\n deletedDocumentContent, batchId);",
" return trashdoc;\n }",
" private void deleteDeletedDocumentContent(XWikiDeletedDocument deletedDocument, boolean bTransaction)\n throws XWikiException\n {\n XWikiRecycleBinContentStoreInterface contentStore =\n getXWikiRecycleBinContentStore(deletedDocument.getXmlStore());",
" if (contentStore != null) {\n contentStore.delete(deletedDocument.getDocumentReference(), deletedDocument.getId(), bTransaction);\n }\n }",
" @Override\n public void saveToRecycleBin(XWikiDocument doc, String deleter, Date date, XWikiContext inputxcontext,\n boolean bTransaction) throws XWikiException\n {\n saveToRecycleBin(doc, deleter, date, null, inputxcontext, bTransaction);\n }",
" @Override\n public void saveToRecycleBin(XWikiDocument doc, String deleter, Date date, String batchId,\n XWikiContext inputxcontext, boolean bTransaction) throws XWikiException\n {\n XWikiContext context = getExecutionXContext(inputxcontext, true);",
" try {\n executeWrite(context, session -> {\n XWikiRecycleBinContentStoreInterface contentStore = getDefaultXWikiRecycleBinContentStore();",
" XWikiDeletedDocument trashdoc = createXWikiDeletedDocument(doc, deleter, date, contentStore, batchId);",
" // Hibernate store.\n long index = ((Number) session.save(trashdoc)).longValue();",
" // External store\n if (contentStore != null) {\n contentStore.save(doc, index, bTransaction);\n }",
" return null;\n });\n } finally {\n restoreExecutionXContext();\n }\n }",
" @Override\n public XWikiDocument restoreFromRecycleBin(final XWikiDocument doc, final long index,\n final XWikiContext inputxcontext, boolean bTransaction) throws XWikiException\n {\n return restoreFromRecycleBin(index, inputxcontext, bTransaction);\n }",
" @Override\n public XWikiDocument restoreFromRecycleBin(long index, XWikiContext inputxcontext, boolean bTransaction)\n throws XWikiException\n {\n XWikiContext context = getExecutionXContext(inputxcontext, true);",
" try {\n XWikiDeletedDocument deletedDocument = getDeletedDocument(index, context, bTransaction);\n return deletedDocument.restoreDocument(context);\n } finally {\n restoreExecutionXContext();\n }\n }",
" @Override\n public XWikiDeletedDocument getDeletedDocument(XWikiDocument doc, final long index, XWikiContext context,\n boolean bTransaction) throws XWikiException\n {\n return getDeletedDocument(index, context, bTransaction);\n }",
" @Override\n public XWikiDeletedDocument getDeletedDocument(long index, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n return getDeletedDocument(index, context, true, bTransaction);\n }",
" private XWikiDeletedDocument getDeletedDocument(final long index, XWikiContext context, boolean resolve,\n boolean bTransaction) throws XWikiException\n {\n return executeRead(context, session -> {\n XWikiDeletedDocument deletedDocument = session.get(XWikiDeletedDocument.class, Long.valueOf(index));",
" if (deletedDocument != null && resolve) {\n deletedDocument = resolveDeletedDocumentContent(deletedDocument, false);\n }",
" return deletedDocument;\n });\n }",
" @Override\n public XWikiDeletedDocument[] getAllDeletedDocuments(XWikiDocument doc, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n XWikiDeletedDocument[] deletedDocuments = executeRead(context, new DeletedDocumentsHibernateCallback(doc));",
" // Resolve deleted document content if needed\n for (int i = 0; i < deletedDocuments.length; ++i) {\n deletedDocuments[i] = resolveDeletedDocumentContent(deletedDocuments[i], bTransaction);\n }",
" return deletedDocuments;\n }",
" @Override\n public Long[] getAllDeletedDocumentsIds(XWikiContext context, int limit) throws XWikiException\n {\n return executeRead(context, session -> {\n org.hibernate.query.Query<Long> query =\n session.createQuery(\"SELECT id FROM XWikiDeletedDocument ORDER BY date DESC\", Long.class);",
" if (limit > 0) {\n query.setMaxResults(limit);\n }",
" List<Long> deletedDocIds = query.list();\n Long[] result = new Long[deletedDocIds.size()];\n return deletedDocIds.toArray(result);\n });\n }",
" @Override\n public Long getNumberOfDeletedDocuments(XWikiContext context) throws XWikiException\n {",
" return executeRead(context, session -> {\n org.hibernate.query.Query<Long> query =\n session.createQuery(\"SELECT count(id) FROM XWikiDeletedDocument\", Long.class);",
" return query.uniqueResult();\n });\n }",
" @Override\n public XWikiDeletedDocument[] getAllDeletedDocuments(String batchId, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n return getAllDeletedDocuments(batchId, true, context, bTransaction);\n }",
" @Override\n public XWikiDeletedDocument[] getAllDeletedDocuments(String batchId, boolean withContent, XWikiContext context,\n boolean bTransaction) throws XWikiException\n {\n XWikiDeletedDocument[] deletedDocuments =\n executeRead(context, new DeletedDocumentsBatchHibernateCallback(batchId));",
" // Resolve deleted document content if needed\n if (withContent) {\n for (int i = 0; i < deletedDocuments.length; ++i) {\n XWikiDeletedDocument deletedDocument = deletedDocuments[i];\n deletedDocuments[i] = resolveDeletedDocumentContent(deletedDocument, bTransaction);\n }\n }",
" return deletedDocuments;\n }",
" @Override\n public void deleteFromRecycleBin(XWikiDocument doc, final long index, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n deleteFromRecycleBin(index, context, bTransaction);\n }",
" @Override\n public void deleteFromRecycleBin(final long index, XWikiContext context, boolean bTransaction) throws XWikiException\n {\n executeWrite(context, session -> {\n XWikiDeletedDocument deletedDocument = getDeletedDocument(index, context, false, bTransaction);",
" // Delete metadata\n session.delete(deletedDocument);",
" // Delete content\n deleteDeletedDocumentContent(deletedDocument, bTransaction);",
" return null;\n });\n }",
"\n @Override\n public void checkAccess(Right right, UserReference userReference, XWikiDeletedDocument deletedDocument)\n throws AuthorizationException\n {\n if (!this.hasAccess(right, userReference, deletedDocument)) {\n throw new AuthorizationException(\n String.format(\"[%s] cannot access deleted document [%s] for right [%s]: \"\n + \"only admin or deleter of the document are authorized\",\n userReference, deletedDocument, right));\n }\n }",
" @Override\n public boolean hasAccess(Right right, UserReference userReference, XWikiDeletedDocument deletedDocument)\n {\n DocumentReference documentReference = deletedDocument.getDocumentReference();\n DocumentReference userDocReference = this.userReferenceSerializer.serialize(userReference);",
" boolean result = false;\n if (this.authorizationManager.hasAccess(Right.ADMIN, userDocReference, documentReference)\n || (Objects.equals(deletedDocument.getDeleterReference(), userDocReference)\n && this.authorizationManager.hasAccess(right, userDocReference, documentReference))) {\n result = true;\n }\n return result;\n }",
"}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.store;",
"import java.util.Date;",
"import org.xwiki.component.annotation.Role;",
"",
"\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.XWikiDeletedDocument;\nimport com.xpn.xwiki.doc.XWikiDocument;",
"/**\n * Interface for RecycleBin feature (XWIKI-543) store system.\n *\n * @version $Id$\n * @since 1.2M1\n */\n@Role\npublic interface XWikiRecycleBinStoreInterface\n{\n /**\n * Save document to recycle bin.\n *\n * @param doc - document to save\n * @param deleter - the user which delete document\n * @param date - date of delete action\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @param context - used while saving\n * @throws XWikiException if error in saving\n */\n void saveToRecycleBin(XWikiDocument doc, String deleter, Date date, XWikiContext context, boolean bTransaction)\n throws XWikiException;",
" /**\n * Save document to recycle bin.\n *\n * @param doc - document to save\n * @param deleter - the user which delete document\n * @param date - date of delete action\n * @param batchId - id of the operation that deleted multiple documents at the same time, useful when trying to\n * revert the operation. {@code null} or empty values are ignored\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @param context - used while saving\n * @throws XWikiException if error in saving\n * @since 9.4RC1\n */\n default void saveToRecycleBin(XWikiDocument doc, String deleter, Date date, String batchId, XWikiContext context,\n boolean bTransaction) throws XWikiException\n {\n // XXX: The current signature does not return the saved document index so we have no way of setting the batchId\n // to the save document. This means we can`t completely respect the method`s contract, but at least the most\n // important part of the work is done and the document can be individually restored.\n saveToRecycleBin(doc, deleter, date, context, bTransaction);\n }",
" /**\n * @return restored document from recycle bin\n * @param doc - document to restore\n * @param index - what deleted document to restore. see {@link XWikiDeletedDocument#getId()}\n * @param context - used while loading\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException if error while loading\n * @deprecated since 9.4RC1. The document parameter is useless and gets in the way. Use\n * {@link #restoreFromRecycleBin(long, XWikiContext, boolean)} instead.\n */\n @Deprecated\n XWikiDocument restoreFromRecycleBin(XWikiDocument doc, long index, XWikiContext context, boolean bTransaction)\n throws XWikiException;",
" /**\n * @param index - what deleted document to restore. see {@link XWikiDeletedDocument#getId()}\n * @param context - used while loading\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @return the restored document from recycle bin\n * @throws XWikiException if error while loading\n * @since 9.4RC1\n */\n default XWikiDocument restoreFromRecycleBin(long index, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n // XXX: Depending on how an older implementation handled the XWikiDocument argument, it's relatively safer to\n // pass an empty document than null. However, if the document's reference is actually used, the result might be\n // unpredictable.\n return restoreFromRecycleBin(new XWikiDocument(), index, context, bTransaction);\n }",
" /**\n * @return specified deleted document from recycle bin. null if not found.\n * @param doc - deleted document\n * @param index - what deleted document to restore. see {@link XWikiDeletedDocument#getId()}\n * @param context - used while loading\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException if error while loading\n * @deprecated since 9.4RC1. The document parameter is useless and gets in the way. Use\n * {@link #getDeletedDocument(long, XWikiContext, boolean)} instead.\n */\n @Deprecated\n XWikiDeletedDocument getDeletedDocument(XWikiDocument doc, long index, XWikiContext context, boolean bTransaction)\n throws XWikiException;",
" /**\n * @param index - what deleted document to restore. See {@link XWikiDeletedDocument#getId()}\n * @param context - used while loading\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @return specified deleted document from recycle bin or {@code null} if not found.\n * @throws XWikiException if error while loading\n * @since 9.4RC1\n */\n default XWikiDeletedDocument getDeletedDocument(long index, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n // XXX: Depending on how an older implementation handled the XWikiDocument argument, it's relatively safer to\n // pass an empty document than null. However, if the document's reference is actually used, the result might be\n // unpredictable.\n return getDeletedDocument(new XWikiDocument(), index, context, bTransaction);\n }",
" /**\n * @return info about all delete actions of specific document. sorted by date.\n * @param doc - the deleted document\n * @param context - used to load\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException - if error in loading\n */\n XWikiDeletedDocument[] getAllDeletedDocuments(XWikiDocument doc, XWikiContext context, boolean bTransaction)\n throws XWikiException;",
" /**\n * Get all the deleted documents ID or a specified number. Sorted by date.\n * @param context - used to load the deleted documents id.\n * @param limit - if > 0 then all deleted documents id are returned. Else the specified number.\n * @return an array of IDs of deleted documents.\n * @throws XWikiException - if error in loading\n * @since 10.10RC1\n */\n default Long[] getAllDeletedDocumentsIds(XWikiContext context, int limit) throws XWikiException\n {\n return new Long[0];\n }",
" /**\n * @param context - used to realize the query.\n * @return the number of deleted documents in the recycle bin.\n * @throws XWikiException - if error in loading.\n * @since 10.10RC1\n */\n default Long getNumberOfDeletedDocuments(XWikiContext context) throws XWikiException\n {\n return -1L;\n }",
" /**\n * @return info about all documents that were deleted in the same batch, as part of the same operation\n * @param batchId - id of the operation that deleted multiple documents at the same time; useful when trying to\n * revert the operation\n * @param context - used to load\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException - if error in loading\n * @since 9.4RC1\n */\n default XWikiDeletedDocument[] getAllDeletedDocuments(String batchId, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n // Return no results as default implementation.\n return new XWikiDeletedDocument[0];\n }",
" /**\n * @param batchId - id of the operation that deleted multiple documents at the same time; useful when trying to\n * revert the operation\n * @param withContent - {@code true} if the deleted document's content should also be loaded; {@code false} if\n * @param context - used to load\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @return info about all documents that were deleted in the same batch, as part of the same operation\n * @throws XWikiException - if error in loading\n * @since 9.4RC1\n */\n default XWikiDeletedDocument[] getAllDeletedDocuments(String batchId, boolean withContent, XWikiContext context,\n boolean bTransaction) throws XWikiException\n {\n // Return no results as default implementation.\n return new XWikiDeletedDocument[0];\n }",
" /**\n * Permanently delete document from recycle bin.\n *\n * @param doc - document to delete\n * @param index - which instance document in recycle bin to delete\n * @param context - used for environment\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException if any error\n * @deprecated since 9.4RC1. The document parameter is useless and gets in the way. Use\n * {@link #deleteFromRecycleBin(long, XWikiContext, boolean)} instead.\n */\n @Deprecated\n void deleteFromRecycleBin(XWikiDocument doc, long index, XWikiContext context, boolean bTransaction)\n throws XWikiException;",
" /**\n * Permanently delete document from recycle bin.\n *\n * @param index - which instance document in recycle bin to delete\n * @param context - used for environment\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException if any error\n * @since 9.4RC1\n */\n default void deleteFromRecycleBin(long index, XWikiContext context, boolean bTransaction) throws XWikiException\n {\n // XXX: Depending on how an older implementation handled the XWikiDocument argument, it's relatively safer to\n // pass an empty document than null. However, if the document's reference is actually used, the result might be\n // unpredictable.\n deleteFromRecycleBin(new XWikiDocument(), index, context, bTransaction);\n }",
"",
"}"
] |
[
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.store;",
"import java.util.Date;",
"import org.xwiki.component.annotation.Role;",
"import org.xwiki.security.authorization.AuthorizationException;\nimport org.xwiki.security.authorization.Right;\nimport org.xwiki.stability.Unstable;\nimport org.xwiki.user.UserReference;",
"\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;\nimport com.xpn.xwiki.doc.XWikiDeletedDocument;\nimport com.xpn.xwiki.doc.XWikiDocument;",
"/**\n * Interface for RecycleBin feature (XWIKI-543) store system.\n *\n * @version $Id$\n * @since 1.2M1\n */\n@Role\npublic interface XWikiRecycleBinStoreInterface\n{\n /**\n * Save document to recycle bin.\n *\n * @param doc - document to save\n * @param deleter - the user which delete document\n * @param date - date of delete action\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @param context - used while saving\n * @throws XWikiException if error in saving\n */\n void saveToRecycleBin(XWikiDocument doc, String deleter, Date date, XWikiContext context, boolean bTransaction)\n throws XWikiException;",
" /**\n * Save document to recycle bin.\n *\n * @param doc - document to save\n * @param deleter - the user which delete document\n * @param date - date of delete action\n * @param batchId - id of the operation that deleted multiple documents at the same time, useful when trying to\n * revert the operation. {@code null} or empty values are ignored\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @param context - used while saving\n * @throws XWikiException if error in saving\n * @since 9.4RC1\n */\n default void saveToRecycleBin(XWikiDocument doc, String deleter, Date date, String batchId, XWikiContext context,\n boolean bTransaction) throws XWikiException\n {\n // XXX: The current signature does not return the saved document index so we have no way of setting the batchId\n // to the save document. This means we can`t completely respect the method`s contract, but at least the most\n // important part of the work is done and the document can be individually restored.\n saveToRecycleBin(doc, deleter, date, context, bTransaction);\n }",
" /**\n * @return restored document from recycle bin\n * @param doc - document to restore\n * @param index - what deleted document to restore. see {@link XWikiDeletedDocument#getId()}\n * @param context - used while loading\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException if error while loading\n * @deprecated since 9.4RC1. The document parameter is useless and gets in the way. Use\n * {@link #restoreFromRecycleBin(long, XWikiContext, boolean)} instead.\n */\n @Deprecated\n XWikiDocument restoreFromRecycleBin(XWikiDocument doc, long index, XWikiContext context, boolean bTransaction)\n throws XWikiException;",
" /**\n * @param index - what deleted document to restore. see {@link XWikiDeletedDocument#getId()}\n * @param context - used while loading\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @return the restored document from recycle bin\n * @throws XWikiException if error while loading\n * @since 9.4RC1\n */\n default XWikiDocument restoreFromRecycleBin(long index, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n // XXX: Depending on how an older implementation handled the XWikiDocument argument, it's relatively safer to\n // pass an empty document than null. However, if the document's reference is actually used, the result might be\n // unpredictable.\n return restoreFromRecycleBin(new XWikiDocument(), index, context, bTransaction);\n }",
" /**\n * @return specified deleted document from recycle bin. null if not found.\n * @param doc - deleted document\n * @param index - what deleted document to restore. see {@link XWikiDeletedDocument#getId()}\n * @param context - used while loading\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException if error while loading\n * @deprecated since 9.4RC1. The document parameter is useless and gets in the way. Use\n * {@link #getDeletedDocument(long, XWikiContext, boolean)} instead.\n */\n @Deprecated\n XWikiDeletedDocument getDeletedDocument(XWikiDocument doc, long index, XWikiContext context, boolean bTransaction)\n throws XWikiException;",
" /**\n * @param index - what deleted document to restore. See {@link XWikiDeletedDocument#getId()}\n * @param context - used while loading\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @return specified deleted document from recycle bin or {@code null} if not found.\n * @throws XWikiException if error while loading\n * @since 9.4RC1\n */\n default XWikiDeletedDocument getDeletedDocument(long index, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n // XXX: Depending on how an older implementation handled the XWikiDocument argument, it's relatively safer to\n // pass an empty document than null. However, if the document's reference is actually used, the result might be\n // unpredictable.\n return getDeletedDocument(new XWikiDocument(), index, context, bTransaction);\n }",
" /**\n * @return info about all delete actions of specific document. sorted by date.\n * @param doc - the deleted document\n * @param context - used to load\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException - if error in loading\n */\n XWikiDeletedDocument[] getAllDeletedDocuments(XWikiDocument doc, XWikiContext context, boolean bTransaction)\n throws XWikiException;",
" /**\n * Get all the deleted documents ID or a specified number. Sorted by date.\n * @param context - used to load the deleted documents id.\n * @param limit - if > 0 then all deleted documents id are returned. Else the specified number.\n * @return an array of IDs of deleted documents.\n * @throws XWikiException - if error in loading\n * @since 10.10RC1\n */\n default Long[] getAllDeletedDocumentsIds(XWikiContext context, int limit) throws XWikiException\n {\n return new Long[0];\n }",
" /**\n * @param context - used to realize the query.\n * @return the number of deleted documents in the recycle bin.\n * @throws XWikiException - if error in loading.\n * @since 10.10RC1\n */\n default Long getNumberOfDeletedDocuments(XWikiContext context) throws XWikiException\n {\n return -1L;\n }",
" /**\n * @return info about all documents that were deleted in the same batch, as part of the same operation\n * @param batchId - id of the operation that deleted multiple documents at the same time; useful when trying to\n * revert the operation\n * @param context - used to load\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException - if error in loading\n * @since 9.4RC1\n */\n default XWikiDeletedDocument[] getAllDeletedDocuments(String batchId, XWikiContext context, boolean bTransaction)\n throws XWikiException\n {\n // Return no results as default implementation.\n return new XWikiDeletedDocument[0];\n }",
" /**\n * @param batchId - id of the operation that deleted multiple documents at the same time; useful when trying to\n * revert the operation\n * @param withContent - {@code true} if the deleted document's content should also be loaded; {@code false} if\n * @param context - used to load\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @return info about all documents that were deleted in the same batch, as part of the same operation\n * @throws XWikiException - if error in loading\n * @since 9.4RC1\n */\n default XWikiDeletedDocument[] getAllDeletedDocuments(String batchId, boolean withContent, XWikiContext context,\n boolean bTransaction) throws XWikiException\n {\n // Return no results as default implementation.\n return new XWikiDeletedDocument[0];\n }",
" /**\n * Permanently delete document from recycle bin.\n *\n * @param doc - document to delete\n * @param index - which instance document in recycle bin to delete\n * @param context - used for environment\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException if any error\n * @deprecated since 9.4RC1. The document parameter is useless and gets in the way. Use\n * {@link #deleteFromRecycleBin(long, XWikiContext, boolean)} instead.\n */\n @Deprecated\n void deleteFromRecycleBin(XWikiDocument doc, long index, XWikiContext context, boolean bTransaction)\n throws XWikiException;",
" /**\n * Permanently delete document from recycle bin.\n *\n * @param index - which instance document in recycle bin to delete\n * @param context - used for environment\n * @param bTransaction - should use old transaction(false) or create new (true)\n * @throws XWikiException if any error\n * @since 9.4RC1\n */\n default void deleteFromRecycleBin(long index, XWikiContext context, boolean bTransaction) throws XWikiException\n {\n // XXX: Depending on how an older implementation handled the XWikiDocument argument, it's relatively safer to\n // pass an empty document than null. However, if the document's reference is actually used, the result might be\n // unpredictable.\n deleteFromRecycleBin(new XWikiDocument(), index, context, bTransaction);\n }",
"\n /**\n * Check if the given deleted document can be accessed for the given right by the given user.\n * This method only throw the {@link AuthorizationException} if the right is not granted.\n *\n * @param right the right to check access for\n * @param userReference the user for whom to check access\n * @param deletedDocument the document to be accessed\n * @throws AuthorizationException if the user doesn't have appropriate right\n * @since 14.10RC1\n * @since 14.4.7\n * @since 13.10.11\n */\n @Unstable\n default void checkAccess(Right right, UserReference userReference, XWikiDeletedDocument deletedDocument) throws\n AuthorizationException\n {\n }",
" /**\n * Check if the given deleted document can be accessed for the given right by the given user.\n *\n * @param right the right to check access for\n * @param userReference the user for whom to check access\n * @param deletedDocument the document to be accessed\n * @return {@code true} if the user have appropriate right\n * @since 14.10RC1\n * @since 14.4.7\n * @since 13.10.11\n */\n @Unstable\n default boolean hasAccess(Right right, UserReference userReference, XWikiDeletedDocument deletedDocument)\n {\n return false;\n }",
"}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.web;",
"import java.io.IOException;\nimport java.net.URL;\nimport java.util.Arrays;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Vector;",
"import javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.script.ScriptContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;",
"import org.apache.commons.lang3.StringUtils;\nimport org.apache.commons.lang3.exception.ExceptionUtils;\nimport org.apache.velocity.VelocityContext;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.xwiki.bridge.event.ActionExecutedEvent;\nimport org.xwiki.bridge.event.ActionExecutingEvent;\nimport org.xwiki.component.descriptor.ComponentDescriptor;\nimport org.xwiki.component.manager.ComponentLookupException;\nimport org.xwiki.component.manager.ComponentManager;\nimport org.xwiki.component.util.DefaultParameterizedType;\nimport org.xwiki.container.Container;\nimport org.xwiki.container.Request;\nimport org.xwiki.container.servlet.ServletContainerException;\nimport org.xwiki.container.servlet.ServletContainerInitializer;\nimport org.xwiki.container.servlet.ServletRequest;\nimport org.xwiki.context.Execution;\nimport org.xwiki.context.ExecutionContext;\nimport org.xwiki.csrf.CSRFToken;\nimport org.xwiki.internal.web.DocExistValidator;\nimport org.xwiki.job.event.status.JobProgressManager;\nimport org.xwiki.job.internal.DefaultJobProgress;\nimport org.xwiki.localization.ContextualLocalizationManager;\nimport org.xwiki.localization.LocaleUtils;\nimport org.xwiki.model.EntityType;\nimport org.xwiki.model.reference.DocumentReference;\nimport org.xwiki.model.reference.DocumentReferenceResolver;\nimport org.xwiki.model.reference.EntityReference;\nimport org.xwiki.model.reference.EntityReferenceProvider;\nimport org.xwiki.model.reference.EntityReferenceSerializer;\nimport org.xwiki.model.reference.EntityReferenceValueProvider;\nimport org.xwiki.model.reference.SpaceReference;\nimport org.xwiki.model.validation.EntityNameValidationConfiguration;\nimport org.xwiki.model.validation.EntityNameValidationManager;\nimport org.xwiki.observation.ObservationManager;\nimport org.xwiki.observation.WrappedThreadEventListener;\nimport org.xwiki.rendering.async.AsyncContext;\nimport org.xwiki.rendering.internal.transformation.MutableRenderingContext;\nimport org.xwiki.rendering.syntax.Syntax;\nimport org.xwiki.rendering.transformation.RenderingContext;\nimport org.xwiki.resource.NotFoundResourceHandlerException;\nimport org.xwiki.resource.ResourceReferenceHandler;\nimport org.xwiki.resource.ResourceReferenceManager;\nimport org.xwiki.resource.ResourceType;\nimport org.xwiki.resource.entity.EntityResourceReference;\nimport org.xwiki.resource.internal.DefaultResourceReferenceHandlerChain;\nimport org.xwiki.script.ScriptContextManager;",
"",
"import org.xwiki.security.authorization.ContextualAuthorizationManager;\nimport org.xwiki.security.authorization.Right;\nimport org.xwiki.stability.Unstable;\nimport org.xwiki.template.TemplateManager;",
"",
"import org.xwiki.velocity.VelocityManager;",
"import com.fasterxml.jackson.databind.ObjectMapper;\nimport com.xpn.xwiki.XWiki;\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;",
"",
"import com.xpn.xwiki.doc.XWikiDocument;\nimport com.xpn.xwiki.internal.web.LegacyAction;\nimport com.xpn.xwiki.monitor.api.MonitorPlugin;\nimport com.xpn.xwiki.objects.BaseObject;\nimport com.xpn.xwiki.plugin.fileupload.FileUploadPlugin;\nimport com.xpn.xwiki.redirection.RedirectionFilter;",
"/**\n * <p>\n * Root class for most XWiki actions. It provides a common framework that allows actions to execute just the specific\n * action code, handling the extra activities, such as preparing the context and retrieving the document corresponding\n * to the URL.\n * </p>\n * <p>\n * It defines two methods, {@link #action(XWikiContext)} and {@link #render(XWikiContext)}, that should be overridden by\n * specific actions. {@link #action(XWikiContext)} should contain the processing part of the action.\n * {@link #render(XWikiContext)} should return the name of a template that should be rendered, or manually write to the\n * {@link XWikiResponse response} stream.\n * </p>\n * <p>\n * Serving a request goes through the following phases:\n * </p>\n * <ul>\n * <li>Wrapping the request and response object in XWiki specific wrappers</li>\n * <li>Prepare the request {@link XWikiContext XWiki-specific context}</li>\n * <li>Initialize/retrieve the XWiki object corresponding to the requested wiki</li>\n * <li>Handle file uploads</li>\n * <li>Prepare the velocity context</li>\n * <li>Prepare the document objects corresponding to the requested URL</li>\n * <li>Send action pre-notifications to listeners</li>\n * <li>Run the overridden {@link #action(XWikiContext)}</li>\n * <li>If {@link #action(XWikiContext)} returns true, run the overridden {@link #render(XWikiContext)}</li>\n * <li>If {@link #render(XWikiContext)} returned a string (template name), render the template with that name</li>\n * <li>Send action post-notifications to listeners</li>\n * </ul>\n * <p>\n * During this process, also handle specific errors, like when a document does not exist, or the user does not have the\n * right to perform the current action.\n * </p>\n */\npublic abstract class XWikiAction implements LegacyAction\n{\n public static final String ACTION_PROGRESS = \"actionprogress\";",
" private static final Logger LOGGER = LoggerFactory.getLogger(XWikiAction.class);",
" /**\n * Actions that need to be resolved on the main wiki instead of the current non-existing wiki. This is used to be\n * able to render the skin even on a wiki that doesn't exist.\n */\n private static final List<String> ACTIONS_IGNORED_WHEN_WIKI_DOES_NOT_EXIST =\n Arrays.asList(\"skin\", \"ssx\", \"jsx\", \"download\");",
" @Inject\n protected ComponentDescriptor<LegacyAction> componentDescriptor;",
" @Inject\n protected Container container;",
" @Inject\n protected Execution execution;",
" @Inject\n protected ObservationManager observation;",
" @Inject\n @Named(\"context\")\n private ComponentManager componentManager;",
" /**\n * Indicate if the action allow asynchronous display (among which the XWiki initialization).\n */\n protected boolean waitForXWikiInitialization = true;",
" @Inject\n @Named(\"currentmixed\")\n private DocumentReferenceResolver<String> currentmixedReferenceResolver;",
" @Inject\n private ContextualAuthorizationManager autorization;",
" private ContextualLocalizationManager localization;",
" private JobProgressManager progress;",
" private ScriptContextManager scriptContextManager;",
" private EntityNameValidationManager entityNameValidationManager;",
" private EntityNameValidationConfiguration entityNameValidationConfiguration;",
" private EntityReferenceSerializer<String> localSerializer;",
"",
"\n /**\n * @return the class of the XWikiForm in charge of parsing the request\n * @since 13.0\n */\n @Unstable\n protected Class<? extends XWikiForm> getFormClass()\n {\n return null;\n }",
" protected ContextualLocalizationManager getLocalization()\n {\n if (this.localization == null) {\n this.localization = Utils.getComponent(ContextualLocalizationManager.class);\n }",
" return this.localization;\n }",
" /**\n * @since 12.10.6\n * @since 13.2RC1\n */\n protected DocumentReferenceResolver<String> getCurrentMixedDocumentReferenceResolver()\n {\n return this.currentmixedReferenceResolver;\n }",
" /**\n * @since 12.10.6\n * @since 13.2RC1\n */\n protected ContextualAuthorizationManager getContextualAuthorizationManager()\n {\n return this.autorization;\n }",
" protected String localizePlainOrKey(String key, Object... parameters)\n {\n return StringUtils.defaultString(getLocalization().getTranslationPlain(key, parameters), key);\n }",
" protected JobProgressManager getProgress()\n {\n if (this.progress == null) {\n this.progress = Utils.getComponent(JobProgressManager.class);\n }",
" return this.progress;\n }",
" protected EntityNameValidationManager getEntityNameValidationManager()\n {\n if (this.entityNameValidationManager == null) {\n this.entityNameValidationManager = Utils.getComponent(EntityNameValidationManager.class);\n }\n return this.entityNameValidationManager;\n }",
" protected EntityNameValidationConfiguration getEntityNameValidationConfiguration()\n {\n if (this.entityNameValidationConfiguration == null) {\n this.entityNameValidationConfiguration = Utils.getComponent(EntityNameValidationConfiguration.class);\n }",
" return this.entityNameValidationConfiguration;\n }",
" protected EntityReferenceSerializer<String> getLocalSerializer()\n {\n if (this.localSerializer == null) {\n this.localSerializer = Utils.getComponent(EntityReferenceSerializer.TYPE_STRING, \"local\");\n }\n return this.localSerializer;\n }",
" /**\n * @return the current unmodified {@link ScriptContext} instance\n * @since 8.3M1\n */\n protected ScriptContext getCurrentScriptContext()\n {\n if (this.scriptContextManager == null) {\n this.scriptContextManager = Utils.getComponent(ScriptContextManager.class);\n }",
" return this.scriptContextManager.getCurrentScriptContext();\n }",
" @Override\n public void execute(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception\n {\n XWikiContext context = null;",
" try {\n // Initialize the XWiki Context which is the main object used to pass information across\n // classes/methods. It's also wrapping the request, response, and all container objects\n // in general.\n context = initializeXWikiContext(servletRequest, servletResponse);",
" // From this line forward all information can be found in the XWiki Context.\n execute(context);\n } finally {\n if (context != null) {\n cleanupComponents();\n }\n }\n }",
" /**\n * Ensure that the given entity reference is valid according to the configured name strategy. Always returns true if\n * the name strategy is not found.\n *\n * @param entityReference the entity reference name to validate\n * @return {@code true} if the entity reference name is valid according to the name strategy.\n * @since 12.0RC1\n */\n protected boolean isEntityReferenceNameValid(EntityReference entityReference)\n {\n if (this.getEntityNameValidationManager().getEntityReferenceNameStrategy() != null\n && this.getEntityNameValidationConfiguration().useValidation()) {\n if (!this.getEntityNameValidationManager().getEntityReferenceNameStrategy().isValid(entityReference)) {\n Object[] args = {getLocalSerializer().serialize(entityReference)};\n XWikiException invalidNameException = new XWikiException(XWikiException.MODULE_XWIKI_STORE,\n XWikiException.ERROR_XWIKI_APP_DOCUMENT_NAME_INVALID,\n \"Cannot create document {0} because its name does not respect the name strategy of the wiki.\", null,\n args);\n ScriptContext scontext = getCurrentScriptContext();\n scontext.setAttribute(\"invalidNameReference\", entityReference, ScriptContext.ENGINE_SCOPE);\n scontext.setAttribute(\"createException\", invalidNameException, ScriptContext.ENGINE_SCOPE);\n return false;\n }\n }\n return true;\n }",
" /**\n * Write an error response to an ajax request.\n *\n * @param httpStatusCode The status code to set on the response.\n * @param message The message that should be displayed.\n * @param context the context.\n */\n protected void writeAjaxErrorResponse(int httpStatusCode, String message, XWikiContext context)\n {\n try {\n context.getResponse().setContentType(\"text/plain\");\n context.getResponse().setStatus(httpStatusCode);\n context.getResponse().setCharacterEncoding(context.getWiki().getEncoding());\n context.getResponse().getWriter().print(message);\n } catch (IOException e) {\n LOGGER.error(\"Failed to send error response to AJAX save and continue request.\", e);\n }\n }",
" public void execute(XWikiContext context) throws Exception\n {\n MonitorPlugin monitor = null;\n FileUploadPlugin fileupload = null;\n DefaultJobProgress actionProgress = null;\n String docName = \"\";",
" boolean debug = StringUtils.equals(context.getRequest().get(\"debug\"), \"true\");",
" String sasync = context.getRequest().get(\"async\");",
" try {\n String action = context.getAction();",
" // Start progress\n if (debug) {\n actionProgress = new DefaultJobProgress(context.getURL().toExternalForm());\n this.observation.addListener(new WrappedThreadEventListener(actionProgress));",
" // Register the action progress in the context\n ExecutionContext econtext = this.execution.getContext();\n if (econtext != null) {\n econtext.setProperty(XWikiAction.ACTION_PROGRESS, actionProgress);\n }\n }",
" getProgress().pushLevelProgress(2, this);",
" getProgress().startStep(this, \"Get XWiki instance\");",
" // Initialize context.getWiki() with the main wiki\n XWiki xwiki;",
" // Verify that the requested wiki exists\n try {\n // Don't show init screen if async is forced to false\n xwiki = XWiki.getXWiki(this.waitForXWikiInitialization || StringUtils.equals(sasync, \"false\"), context);",
" // If XWiki is still initializing display initialization template\n if (xwiki == null) {\n // Display initialization template\n renderInit(context);",
" // Initialization template has been displayed, stop here.\n return;\n }\n } catch (XWikiException e) {\n // If the wiki asked by the user doesn't exist, then we first attempt to use any existing global\n // redirects. If there are none, then we display the specific error template.\n if (e.getCode() == XWikiException.ERROR_XWIKI_DOES_NOT_EXIST) {\n xwiki = XWiki.getMainXWiki(context);",
" // Initialize the url factory\n XWikiURLFactory urlf = xwiki.getURLFactoryService().createURLFactory(context.getMode(), context);\n context.setURLFactory(urlf);",
" // Initialize the velocity context and its bindings so that it may be used in the velocity templates\n // that we\n // are parsing below.\n VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);\n VelocityContext vcontext = velocityManager.getVelocityContext();",
" if (!sendGlobalRedirect(context.getResponse(), context.getURL().toString(), context)) {\n // Starting XWiki 5.0M2, 'xwiki.virtual.redirect' was removed. Warn users still using it.\n if (!StringUtils.isEmpty(context.getWiki().Param(\"xwiki.virtual.redirect\"))) {\n LOGGER.warn(String.format(\"%s %s\", \"'xwiki.virtual.redirect' is no longer supported.\",\n \"Please update your configuration and/or see XWIKI-8914 for more details.\"));\n }",
" // Display the error template only for actions that are not ignored\n if (!ACTIONS_IGNORED_WHEN_WIKI_DOES_NOT_EXIST.contains(action)) {",
" // Add localization resources to the context\n xwiki.prepareResources(context);",
" // Set the main home page in the main space of the main wiki as the current requested entity\n // since we cannot set the non existing one as it would generate errors obviously...\n EntityReferenceValueProvider valueProvider =\n Utils.getComponent(EntityReferenceValueProvider.class);\n xwiki.setPhonyDocument(new DocumentReference(valueProvider.getDefaultValue(EntityType.WIKI),\n valueProvider.getDefaultValue(EntityType.SPACE),\n valueProvider.getDefaultValue(EntityType.DOCUMENT)), context, vcontext);",
" // Parse the error template\n Utils.parseTemplate(context.getWiki().Param(\"xwiki.wiki_exception\", \"wikidoesnotexist\"),\n context);",
" // Error template was displayed, stop here.\n return;\n }",
" // At this point, we allow regular execution of the ignored action because even if the wiki\n // does not exist, we still need to allow UI resources to be retrieved (from the filesystem\n // and the main wiki) or our error template will not be rendered properly.",
" // Proceed with serving the main wiki",
" } else {\n // Global redirect was executed, stop here.\n return;\n }\n } else {\n LOGGER.error(\"Uncaught exception during XWiki initialisation:\", e);\n throw e;\n }\n }",
" // Send global redirection (if any)\n if (sendGlobalRedirect(context.getResponse(), context.getURL().toString(), context)) {\n return;\n }",
" XWikiURLFactory urlf = xwiki.getURLFactoryService().createURLFactory(context.getMode(), context);\n context.setURLFactory(urlf);",
" // Handle ability to enter space URLs and convert them to page URLs (Nested Documents)\n if (redirectSpaceURLs(action, urlf, xwiki, context)) {\n return;\n }",
" String sajax = context.getRequest().get(\"ajax\");\n boolean ajax = false;\n if (sajax != null && !sajax.trim().equals(\"\") && !sajax.equals(\"0\")) {\n ajax = true;\n }\n context.put(\"ajax\", ajax);",
" boolean async = false;\n if (StringUtils.isNotEmpty(sasync)) {\n async = sasync.equals(\"true\");\n } else {\n // By default allow asynchronous rendering for \"human oriented\" actions which are not executing an ajax\n // request\n async = !ajax && !this.waitForXWikiInitialization;\n }\n Utils.getComponent(AsyncContext.class).setEnabled(async);",
" // Any error before this will be treated using a redirection to an error page",
" if (monitor != null) {\n monitor.startTimer(\"request\");\n }",
" getProgress().startStep(this, \"Execute request\");",
" VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);\n VelocityContext vcontext = velocityManager.getVelocityContext();",
" getProgress().pushLevelProgress(7, this);",
" boolean eventSent = false;\n try {\n getProgress().startStep(this, \"Prepare documents and put them in the context\");",
" // Prepare documents and put them in the context\n if (!xwiki.prepareDocuments(context.getRequest(), context, vcontext)) {\n return;\n }",
" // Start monitoring timer\n monitor = (MonitorPlugin) xwiki.getPlugin(\"monitor\", context);\n if (monitor != null) {\n monitor.startRequest(\"\", context.getAction(), context.getURL());\n monitor.startTimer(\"multipart\");\n }",
" getProgress().startStep(this, \"Parses multipart\");",
" // Parses multipart so that params in multipart are available for all actions\n fileupload = Utils.handleMultipart(context.getRequest().getHttpServletRequest(), context);\n if (monitor != null) {\n monitor.endTimer(\"multipart\");\n }",
" if (monitor != null) {\n monitor.setWikiPage(context.getDoc().getFullName());\n }",
" getProgress().startStep(this, \"Send [\" + context.getAction() + \"] action start event\");",
" // For the moment we're sending the XWiki context as the data, but this will be\n // changed in the future, when the whole platform will be written using components\n // and there won't be a need for the context.\n try {\n ActionExecutingEvent event = new ActionExecutingEvent(context.getAction());\n this.observation.notify(event, context.getDoc(), context);\n eventSent = true;\n if (event.isCanceled()) {\n // Action has been canceled\n // TODO: do something special ?\n return;\n }\n } catch (Throwable ex) {\n LOGGER.error(\"Cannot send action notifications for document [\" + context.getDoc()\n + \" using action [\" + context.getAction() + \"]\", ex);\n }",
" if (monitor != null) {\n monitor.endTimer(\"prenotify\");\n }",
" // Call the Actions",
" getProgress().startStep(this, \"Search and execute entity resource handler\");",
" // Call the new Entity Resource Reference Handler.\n ResourceReferenceHandler entityResourceReferenceHandler = Utils.getComponent(\n new DefaultParameterizedType(null, ResourceReferenceHandler.class, ResourceType.class), \"bin\");\n EntityResourceReference entityResourceReference =\n (EntityResourceReference) Utils.getComponent(ResourceReferenceManager.class).getResourceReference();",
" // We save the current action set since:\n // - by default the action is set to \"view\" for Extensions not installed as root and contributing some\n // new Entity Action (see https://jira.xwiki.org/browse/XWIKI-15182).\n // - we want to set back the action in case no ResourceReferenceHandler was found to handle the URL\n // TODO: Remove once https://jira.xwiki.org/browse/XWIKI-14947 is fixed\n String originalAction = context.getAction();\n try {\n // Force the action in the context because of https://jira.xwiki.org/browse/XWIKI-15182.\n // TODO: Remove once https://jira.xwiki.org/browse/XWIKI-14947 is fixed\n context.setAction(entityResourceReference.getAction().getActionName());\n entityResourceReferenceHandler.handle(entityResourceReference,\n DefaultResourceReferenceHandlerChain.EMPTY);\n // Don't let the old actions kick in!\n return;\n } catch (NotFoundResourceHandlerException e) {\n // No Entity Resource Action has been found. Don't do anything and let it go through\n // so that the old Action system kicks in...\n // Put back the action, because of https://jira.xwiki.org/browse/XWIKI-15182\n // TODO: Remove once https://jira.xwiki.org/browse/XWIKI-14947 is fixed\n context.setAction(originalAction);\n }",
" getProgress().startStep(this, \"Execute action render\");",
" // Handle the XWiki.RedirectClass object that can be attached to the current document\n boolean hasRedirect = handleRedirect(context);",
" // Then call the old Actions for backward compatibility (and because a lot of them have not been\n // migrated to new Actions yet).\n String renderResult = null;\n XWikiDocument doc = context.getDoc();\n docName = doc.getFullName();\n if (!hasRedirect && action(context)) {\n renderResult = render(context);\n }",
" if (renderResult != null) {\n // check for doc existence\n if (shouldReturnDocDoesNotExist(doc, context)) {\n String page = Utils.getPage(context.getRequest(), \"docdoesnotexist\");",
" getProgress().startStep(this, \"Execute template [\" + page + \"]\");\n Utils.parseTemplate(page, context);\n } else {\n String page = Utils.getPage(context.getRequest(), renderResult);",
" getProgress().startStep(this, \"Execute template [\" + page + \"]\");\n Utils.parseTemplate(page, !page.equals(\"direct\"), context);\n }\n }\n return;\n } catch (Throwable e) {\n if (e instanceof IOException) {\n e = new XWikiException(XWikiException.MODULE_XWIKI_APP,\n XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, \"Exception while sending response\", e);\n }",
" if (!(e instanceof XWikiException)) {\n e = new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_UNKNOWN,\n \"Uncaught exception\", e);\n }",
" try {\n XWikiException xex = (XWikiException) e;\n if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {\n // Connection aborted from the client side, there's not much we can do on the server side. We\n // simply ignore it.\n LOGGER.debug(\"Connection aborted\", e);\n // We don't write any other message to the response, as the connection is broken, anyway.\n return;\n } else if (xex.getCode() == XWikiException.ERROR_XWIKI_ACCESS_DENIED) {\n Utils.parseTemplate(context.getWiki().Param(\"xwiki.access_exception\", \"accessdenied\"), context);\n return;\n } else if (xex.getCode() == XWikiException.ERROR_XWIKI_USER_INACTIVE\n || xex.getCode() == XWikiException.ERROR_XWIKI_USER_DISABLED) {\n if (xex.getCode() == XWikiException.ERROR_XWIKI_USER_DISABLED) {\n context.put(\"cause\", \"disabled\");\n }\n // In case of user disabled or inactive, the resources are actually forbidden.\n context.getResponse().setStatus(HttpServletResponse.SC_FORBIDDEN);\n Utils.parseTemplate(context.getWiki().Param(\"xwiki.user_exception\", \"userinactive\"), context);",
" return;\n } else if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_ATTACHMENT_NOT_FOUND) {\n context.put(\"message\", \"attachmentdoesnotexist\");\n Utils.parseTemplate(\n context.getWiki().Param(\"xwiki.attachment_exception\", \"attachmentdoesnotexist\"), context);\n return;\n } else if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION) {\n vcontext.put(\"message\", localizePlainOrKey(\"platform.core.invalidUrl\"));\n xwiki.setPhonyDocument(xwiki.getDefaultSpace(context) + \".\" + xwiki.getDefaultPage(context),\n context, vcontext);\n context.getResponse().setStatus(HttpServletResponse.SC_BAD_REQUEST);\n Utils.parseTemplate(context.getWiki().Param(\"xwiki.invalid_url_exception\", \"error\"), context);\n return;\n }\n // Note: We don't use the vcontext variable computed above since apparently the velocity context\n // can have changed in between. Thus we get it again to be sure we're setting the binding in the\n // right one.\n velocityManager.getVelocityContext().put(\"exp\", e);\n if (LOGGER.isWarnEnabled()) {\n // Don't log \"Broken Pipe\" exceptions since they're not real errors and we don't want to pollute\n // the logs with unnecessary stack traces. It just means the client side has cancelled the\n // connection.\n if (ExceptionUtils.getRootCauseMessage(e).equals(\"IOException: Broken pipe\")) {\n return;\n }\n LOGGER.warn(\"Uncaught exception: \" + e.getMessage(), e);\n }\n // If the request is an AJAX request, we don't return a whole HTML page, but just the exception\n // inline.\n String exceptionTemplate = ajax ? \"exceptioninline\" : \"exception\";\n Utils.parseTemplate(Utils.getPage(context.getRequest(), exceptionTemplate), context);\n return;\n } catch (XWikiException ex) {\n if (ex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {\n LOGGER.error(\"Connection aborted\");\n }\n } catch (Exception e2) {\n // I hope this never happens\n LOGGER.error(\"Uncaught exceptions (inner): \", e);\n LOGGER.error(\"Uncaught exceptions (outer): \", e2);\n }\n return;\n } finally {\n // Let's make sure we have flushed content and closed\n try {\n context.getResponse().getWriter().flush();\n } catch (Throwable e) {\n // This might happen if the connection was closed, for example.\n // If we can't flush, then there's nothing more we can send to the client.\n }",
" if (monitor != null) {\n monitor.endTimer(\"request\");\n monitor.startTimer(\"notify\");\n }",
" if (eventSent) {\n // For the moment we're sending the XWiki context as the data, but this will be\n // changed in the future, when the whole platform will be written using components\n // and there won't be a need for the context.\n try {\n this.observation.notify(new ActionExecutedEvent(context.getAction()), context.getDoc(), context);\n } catch (Throwable ex) {\n LOGGER.error(\"Cannot send action notifications for document [\" + docName + \" using action [\"\n + context.getAction() + \"]\", ex);\n }\n }",
" if (monitor != null) {\n monitor.endTimer(\"notify\");\n }",
" getProgress().startStep(this, \"Cleanup database connections\");",
" // Make sure we cleanup database connections\n // There could be cases where we have some\n xwiki.getStore().cleanUp(context);",
" getProgress().popLevelProgress(this);\n }\n } finally {\n // End request\n if (monitor != null) {\n monitor.endRequest();\n }",
" // Stop progress\n if (actionProgress != null) {\n getProgress().popLevelProgress(this);",
" this.observation.removeListener(actionProgress.getName());\n }",
" if (fileupload != null) {\n fileupload.cleanFileList(context);\n }\n }\n }",
" /**\n * Check if the given document exists or not and if it should return a 404 based on the context. A {@link\n * DocExistValidator} with an hint matching the current action is used to check if the document exists. When no\n * {@link DocExistValidator} is found, the response is always {@code false} When a {@link DocExistValidator} is\n * found, the result is delegated to {@link DocExistValidator#docExist(XWikiDocument, XWikiContext)}.\n *\n * @param doc the doc for which to check it exists or not\n * @param context the current context\n * @return {@code true} if we should return a 404\n * @throws ComponentLookupException if an error occurs when instantiating a {@link DocExistValidator}\n */\n private boolean shouldReturnDocDoesNotExist(XWikiDocument doc, XWikiContext context) throws ComponentLookupException\n {\n boolean result = false;\n String action = context.getAction();\n if (this.componentManager.hasComponent(DocExistValidator.class, action)) {\n result = this.componentManager.<DocExistValidator>getInstance(DocExistValidator.class, action)\n .docExist(doc, context);\n }\n return result;\n }",
" private void renderInit(XWikiContext xcontext) throws Exception\n {\n RenderingContext renderingContext = Utils.getComponent(RenderingContext.class);\n MutableRenderingContext mutableRenderingContext =\n renderingContext instanceof MutableRenderingContext ? (MutableRenderingContext) renderingContext : null;",
" if (mutableRenderingContext != null) {\n mutableRenderingContext.push(renderingContext.getTransformation(), renderingContext.getXDOM(),\n renderingContext.getDefaultSyntax(), \"init.vm\", renderingContext.isRestricted(), Syntax.XHTML_1_0);\n }",
" xcontext.getResponse().setStatus(202);\n xcontext.getResponse().setContentType(\"text/html; charset=UTF-8\");",
" try {\n Utils.getComponent(TemplateManager.class).render(\"init.vm\", xcontext.getResponse().getWriter());\n } finally {\n if (mutableRenderingContext != null) {\n mutableRenderingContext.pop();\n }\n }",
" xcontext.getResponse().flushBuffer();",
" xcontext.setFinished(true);\n }",
" protected XWikiContext initializeXWikiContext(HttpServletRequest servletRequest,\n HttpServletResponse servletResponse)\n throws XWikiException, ServletException, InstantiationException, IllegalAccessException\n {\n XWikiForm form;\n if (getFormClass() != null) {\n form = getFormClass().newInstance();\n } else {\n form = null;\n }",
" return initializeXWikiContext(servletRequest, servletResponse, form);\n }",
" /**\n * @return the name to put in the {@link XWikiContext}, by default the component role hint is used\n * @since 13.0\n */\n @Unstable\n protected String getName()\n {\n return this.componentDescriptor.getRoleHint();\n }",
" protected XWikiContext initializeXWikiContext(HttpServletRequest servletRequest,\n HttpServletResponse servletResponse, XWikiForm form) throws XWikiException, ServletException\n {\n String action = getName();",
" XWikiRequest request = new XWikiServletRequest(servletRequest);\n XWikiResponse response = new XWikiServletResponse(servletResponse);\n XWikiContext context = Utils.prepareContext(action, request, response,\n new XWikiServletContext(servletRequest.getServletContext()));",
" if (form != null) {\n form.reset(request);\n }",
" // Add the form to the context\n context.setForm(form);",
" // Initialize the Container component which is the new way of transporting the Context in the new\n // component architecture.\n initializeContainerComponent(context);",
" return context;\n }",
" protected void initializeContainerComponent(XWikiContext context) throws ServletException\n {\n // Initialize the Container fields (request, response, session).\n // Note that this is a bridge between the old core and the component architecture.\n // In the new component architecture we use ThreadLocal to transport the request,\n // response and session to components which require them.\n // In the future this Servlet will be replaced by the XWikiPlexusServlet Servlet.\n ServletContainerInitializer containerInitializer = Utils.getComponent(ServletContainerInitializer.class);",
" try {\n containerInitializer.initializeRequest(context.getRequest().getHttpServletRequest(), context);\n containerInitializer.initializeResponse(context.getResponse());\n containerInitializer.initializeSession(context.getRequest().getHttpServletRequest());\n } catch (ServletContainerException e) {\n throw new ServletException(\"Failed to initialize Request/Response or Session\", e);\n }\n }",
" protected void cleanupComponents()\n {\n // We must ensure we clean the ThreadLocal variables located in the Container and Execution\n // components as otherwise we will have a potential memory leak.\n container.removeRequest();\n container.removeResponse();\n container.removeSession();\n execution.removeContext();\n }",
" public String getRealPath(String path)\n {\n Request request = this.container.getRequest();",
" if (request instanceof ServletRequest) {\n return ((ServletRequest) request).getHttpServletRequest().getServletContext().getRealPath(path);\n }",
" return null;\n }",
" // hook\n public boolean action(XWikiContext context) throws XWikiException\n {\n return true;\n }",
" // hook\n public String render(XWikiContext context) throws XWikiException\n {\n return null;\n }",
" /**\n * Indicate if the action support redirection. The default value is {@code false}.\n *\n * @return {@code true} if the action supports redirections, {@code false} otherwise\n * @since 14.0RC1\n */\n @Unstable\n protected boolean supportRedirections()\n {\n return false;\n }\n",
"",
" protected void handleRevision(XWikiContext context) throws XWikiException\n {\n String rev = context.getRequest().getParameter(\"rev\");\n if (rev != null) {\n context.put(\"rev\", rev);\n XWikiDocument doc = (XWikiDocument) context.get(\"doc\");\n XWikiDocument tdoc = (XWikiDocument) context.get(\"tdoc\");\n // if the doc is deleted and we request a specific language, we have to set the locale so we can retrieve\n // properly the document revision.\n if (rev.startsWith(\"deleted\") && !StringUtils.isEmpty(context.getRequest().getParameter(\"language\"))\n && doc == tdoc) {\n Locale locale = LocaleUtils.toLocale(context.getRequest().getParameter(\"language\"), Locale.ROOT);\n tdoc = new XWikiDocument(tdoc.getDocumentReference(), locale);\n }",
" XWikiDocument rdoc =\n (!doc.getLocale().equals(tdoc.getLocale())) ? doc : context.getWiki().getDocument(doc, rev, context);",
" XWikiDocument rtdoc =\n (doc.getLocale().equals(tdoc.getLocale())) ? rdoc : context.getWiki().getDocument(tdoc, rev, context);",
"\n context.put(\"tdoc\", rtdoc);\n context.put(\"cdoc\", rdoc);\n context.put(\"doc\", rdoc);\n }\n }",
" /**\n * Send redirection based on a regexp pattern (if any) set at the main wiki level. To enable this feature you must\n * add xwiki.preferences.redirect=1 to your xwiki.cfg.\n *\n * @param response the servlet response\n * @param url url of the request\n * @param context the XWiki context\n * @return true if a redirection has been sent\n */\n protected boolean sendGlobalRedirect(XWikiResponse response, String url, XWikiContext context) throws Exception\n {\n if (\"1\".equals(context.getWiki().Param(\"xwiki.preferences.redirect\"))) {\n // Note: This implementation is not performant at all and will slow down the wiki as the number\n // of redirects increases. A better implementation would use a cache of redirects and would use\n // the notification mechanism to update the cache when the XWiki.XWikiPreferences document is\n // modified.\n XWikiDocument globalPreferences = context.getWiki().getDocument(\"xwiki:XWiki.XWikiPreferences\", context);\n Vector<BaseObject> redirects = globalPreferences.getObjects(\"XWiki.GlobalRedirect\");",
" if (redirects != null) {\n for (BaseObject redir : redirects) {\n if (redir != null) {\n String p = redir.getStringValue(\"pattern\");\n if (p != null && url.matches(p)) {\n String dest = redir.getStringValue(\"destination\");\n response.sendRedirect(url.replaceAll(p, dest));\n return true;\n }\n }\n }\n }\n }\n return false;\n }",
" /**\n * Perform a redirect to the given URL.\n * @param response the response to use to perform the redirect\n * @param url the location of the redirect\n * @throws XWikiException in case of IOException when performing the redirect.\n */\n protected void sendRedirect(XWikiResponse response, String url) throws XWikiException\n {\n try {\n if (url != null) {\n response.sendRedirect(response.encodeRedirectURL(url));\n }\n } catch (IOException e) {\n Object[] args = {url};\n throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_REDIRECT_EXCEPTION,\n \"Exception while sending redirect to page {0}\", e, args);\n }\n }",
" /**\n * Gets the translated version of a document, in the specified language. If the translation does not exist, a new\n * document translation is created. If the requested language does not correspond to a translation (is not defined\n * or is the same as the main document), then the main document is returned.\n *\n * @param doc the main (default, untranslated) document to translate\n * @param language the requested document language\n * @param context the current request context\n * @return the translated document, or the original untranslated document if the requested language is not a\n * translation\n * @throws XWikiException if the translation cannot be retrieved from the database\n */\n protected XWikiDocument getTranslatedDocument(XWikiDocument doc, String language, XWikiContext context)\n throws XWikiException\n {\n XWikiDocument tdoc;\n if (StringUtils.isBlank(language) || language.equals(\"default\") || language.equals(doc.getDefaultLanguage())) {\n tdoc = doc;\n } else {\n tdoc = doc.getTranslatedDocument(language, context);\n if (tdoc == doc) {\n tdoc = new XWikiDocument(doc.getDocumentReference());\n tdoc.setLanguage(language);\n tdoc.setStore(doc.getStore());\n }\n tdoc.setTranslation(1);\n }\n return tdoc;\n }",
" /**\n * Perform CSRF check and redirect to the resubmission page if needed. Throws an exception if the access should be\n * denied, returns false if the check failed and the user will be redirected to a resubmission page.\n *\n * @param context current xwiki context containing the request\n * @return true if the check succeeded, false if resubmission is needed\n * @throws XWikiException if the check fails\n */\n protected boolean csrfTokenCheck(XWikiContext context) throws XWikiException\n {\n return csrfTokenCheck(context, false);\n }",
" /**\n * Perform CSRF check and redirect to the resubmission page if needed. Throws an exception if the access should be\n * denied, returns false if the check failed and the user will be redirected to a resubmission page.\n *\n * @param context current xwiki context containing the request\n * @param jsonAnswer if true, returns a JSON answer in case of AJAX request: allow to process it properly on client.\n * @return true if the check succeeded, false if resubmission is needed\n * @throws XWikiException if the check fails\n * @since 11.3RC1\n */\n protected boolean csrfTokenCheck(XWikiContext context, boolean jsonAnswer) throws XWikiException\n {\n final boolean isAjaxRequest = Utils.isAjaxRequest(context);\n CSRFToken csrf = Utils.getComponent(CSRFToken.class);\n try {\n String token = context.getRequest().getParameter(\"form_token\");\n if (!csrf.isTokenValid(token)) {\n if (isAjaxRequest) {\n if (jsonAnswer) {\n Map<String, String> jsonObject = new LinkedHashMap<>();\n jsonObject.put(\"errorType\", \"CSRF\");\n jsonObject.put(\"resubmissionURI\", csrf.getRequestURI());\n jsonObject.put(\"newToken\", csrf.getToken());\n this.answerJSON(context, HttpServletResponse.SC_FORBIDDEN, jsonObject);\n } else {\n final String csrfCheckFailedMessage = localizePlainOrKey(\"core.editors.csrfCheckFailed\");\n writeAjaxErrorResponse(HttpServletResponse.SC_FORBIDDEN, csrfCheckFailedMessage, context);\n }\n } else {\n sendRedirect(context.getResponse(), csrf.getResubmissionURL());\n }",
" return false;\n }\n } catch (XWikiException exception) {\n // too bad\n throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,\n \"Access denied, secret token verification failed\", exception);\n }\n return true;\n }",
" /**\n * In order to let users enter URLs to Spaces we do the following when receiving {@code /A/B} (where A and B are\n * spaces):\n * <ul>\n * <li>check that the action is \"view\" (we only support this for the view action since otherwise this would break\n * apps written before this concept was introduced in XWiki 7.2M1)</li>\n * <li>if A.B exists then continue</li>\n * <li>if A.B doesn't exist then forward to A.B.WebHome</li>\n * </ul>\n * In order to disable this redirect you should provide the {@code spaceRedirect=false} Query String parameter and\n * value.\n *\n * @since 7.2M1\n */\n private boolean redirectSpaceURLs(String action, XWikiURLFactory urlf, XWiki xwiki, XWikiContext context)\n throws Exception\n {\n if (\"view\".equals(action) && !\"false\".equalsIgnoreCase(context.getRequest().getParameter(\"spaceRedirect\"))) {\n DocumentReference reference = xwiki.getDocumentReference(context.getRequest(), context);\n if (!xwiki.exists(reference, context)) {\n String defaultDocumentName = Utils.getComponent(EntityReferenceProvider.class)\n .getDefaultReference(EntityType.DOCUMENT).getName();\n // Avoid an infinite loop by ensuring we're not on a WebHome already\n if (!reference.getName().equals(defaultDocumentName)) {\n // Consider the reference as a Space Reference and Construct a new reference to the home of that\n // Space. Then generate the URL for it and forward to it\n SpaceReference spaceReference = new SpaceReference(reference.getName(), reference.getParent());\n // Extract the anchor\n String anchor = new URL(context.getRequest().getRequestURL().toString()).getRef();\n URL forwardURL = urlf.createURL(getLocalSerializer().serialize(spaceReference), defaultDocumentName,\n action, context.getRequest().getQueryString(), anchor,\n spaceReference.getWikiReference().getName(), context);\n // Since createURL() contain the webapp context and since RequestDispatcher should not contain it,\n // we need to remove it!\n String webappContext = xwiki.getWebAppPath(context);\n String relativeURL = urlf.getURL(forwardURL, context);\n relativeURL = '/' + StringUtils.substringAfter(relativeURL, webappContext);\n context.getRequest().getRequestDispatcher(relativeURL).forward(context.getRequest(),\n context.getResponse());\n return true;\n }\n }\n }",
" return false;\n }",
" /**\n * Answer to a request with a JSON content.\n * \n * @param context the current context of the request.\n * @param status the status code to send back.\n * @param answer the content of the JSON answer.\n * @throws XWikiException in case of error during the serialization of the JSON.\n */\n protected void answerJSON(XWikiContext context, int status, Map<String, String> answer) throws XWikiException\n {\n ObjectMapper mapper = new ObjectMapper();",
" try {\n String jsonAnswerAsString = mapper.writeValueAsString(answer);\n context.getResponse().setContentType(\"application/json\");\n context.getResponse().setContentLength(jsonAnswerAsString.length());\n context.getResponse().setStatus(status);\n context.getResponse().setCharacterEncoding(context.getWiki().getEncoding());\n context.getResponse().getWriter().print(jsonAnswerAsString);\n context.setResponseSent(true);\n } catch (IOException e) {\n throw new XWikiException(\"Error while sending JSON answer.\", e);\n }\n }",
" /**\n * Make sure to set the right length (or nothing) in the response.\n * \n * @param response the response\n * @param length the length to set in the response\n * @since 11.10\n * @since 10.11.10\n * @since 11.3.6\n */\n protected void setContentLength(XWikiResponse response, long length)\n {\n // Set the content length in the response\n response.setContentLengthLong(length);\n }",
" /**\n * Helper used resolve the template passed to the action if the current user have access to it.\n * \n * @param template the template to copy\n * @return the reference of the template if not empty and the current user have access to it\n * @since 12.10.6\n * @since 13.2RC1\n */\n protected DocumentReference resolveTemplate(String template)\n {\n if (StringUtils.isNotBlank(template)) {\n DocumentReference templateReference = getCurrentMixedDocumentReferenceResolver().resolve(template);",
" // Make sure the current user have access to the template document before copying it\n if (getContextualAuthorizationManager().hasAccess(Right.VIEW, templateReference)) {\n return templateReference;\n }\n }",
" return null;\n }",
" /**\n * Helper used by various actions to initialize a document by copying a template to it.\n * \n * @param document the document to update\n * @param template the template to copy\n * @param context the XWiki context\n * @return true if the document was updated, false otherwise (for example when the current user does not have view\n * right on the template document)\n * @throws XWikiException when failing to copy the template\n * @since 12.10.6\n * @since 13.2RC1\n */\n @Unstable\n protected boolean readFromTemplate(XWikiDocument document, String template, XWikiContext context)\n throws XWikiException\n {\n DocumentReference templateReference = resolveTemplate(template);",
" if (templateReference != null) {\n document.readFromTemplate(templateReference, context);",
" return true;\n }",
" return false;\n }",
" /**\n * Loop over the {@link RedirectionFilter} components until one of them perform a redirection. If none of the does,\n * the action continues normally.\n *\n * @param context the current wiki content\n * @return {@code true} if a redirection has been performed, {@code false} otherwise\n * @throws XWikiException in case of error during the execution of a redirection filter\n */\n private boolean handleRedirect(XWikiContext context) throws XWikiException\n {\n // If no redirection are expected, this step is skipped.\n if (this.supportRedirections()) {\n try {\n for (RedirectionFilter filter : this.componentManager.<RedirectionFilter>getInstanceList(\n RedirectionFilter.class)) {\n if (filter.redirect(context)) {\n return true;\n }\n }\n } catch (ComponentLookupException e) {\n throw new XWikiException(\"Failed to resolve the redirection filters list\", e);\n }\n }\n return false;\n }\n}"
] |
[
1,
1,
1,
1,
0,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.web;",
"import java.io.IOException;\nimport java.net.URL;\nimport java.util.Arrays;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Vector;",
"import javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.script.ScriptContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;",
"import org.apache.commons.lang3.StringUtils;\nimport org.apache.commons.lang3.exception.ExceptionUtils;\nimport org.apache.velocity.VelocityContext;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.xwiki.bridge.event.ActionExecutedEvent;\nimport org.xwiki.bridge.event.ActionExecutingEvent;\nimport org.xwiki.component.descriptor.ComponentDescriptor;\nimport org.xwiki.component.manager.ComponentLookupException;\nimport org.xwiki.component.manager.ComponentManager;\nimport org.xwiki.component.util.DefaultParameterizedType;\nimport org.xwiki.container.Container;\nimport org.xwiki.container.Request;\nimport org.xwiki.container.servlet.ServletContainerException;\nimport org.xwiki.container.servlet.ServletContainerInitializer;\nimport org.xwiki.container.servlet.ServletRequest;\nimport org.xwiki.context.Execution;\nimport org.xwiki.context.ExecutionContext;\nimport org.xwiki.csrf.CSRFToken;\nimport org.xwiki.internal.web.DocExistValidator;\nimport org.xwiki.job.event.status.JobProgressManager;\nimport org.xwiki.job.internal.DefaultJobProgress;\nimport org.xwiki.localization.ContextualLocalizationManager;\nimport org.xwiki.localization.LocaleUtils;\nimport org.xwiki.model.EntityType;\nimport org.xwiki.model.reference.DocumentReference;\nimport org.xwiki.model.reference.DocumentReferenceResolver;\nimport org.xwiki.model.reference.EntityReference;\nimport org.xwiki.model.reference.EntityReferenceProvider;\nimport org.xwiki.model.reference.EntityReferenceSerializer;\nimport org.xwiki.model.reference.EntityReferenceValueProvider;\nimport org.xwiki.model.reference.SpaceReference;\nimport org.xwiki.model.validation.EntityNameValidationConfiguration;\nimport org.xwiki.model.validation.EntityNameValidationManager;\nimport org.xwiki.observation.ObservationManager;\nimport org.xwiki.observation.WrappedThreadEventListener;\nimport org.xwiki.rendering.async.AsyncContext;\nimport org.xwiki.rendering.internal.transformation.MutableRenderingContext;\nimport org.xwiki.rendering.syntax.Syntax;\nimport org.xwiki.rendering.transformation.RenderingContext;\nimport org.xwiki.resource.NotFoundResourceHandlerException;\nimport org.xwiki.resource.ResourceReferenceHandler;\nimport org.xwiki.resource.ResourceReferenceManager;\nimport org.xwiki.resource.ResourceType;\nimport org.xwiki.resource.entity.EntityResourceReference;\nimport org.xwiki.resource.internal.DefaultResourceReferenceHandlerChain;\nimport org.xwiki.script.ScriptContextManager;",
"import org.xwiki.security.authorization.AuthorizationException;",
"import org.xwiki.security.authorization.ContextualAuthorizationManager;\nimport org.xwiki.security.authorization.Right;\nimport org.xwiki.stability.Unstable;\nimport org.xwiki.template.TemplateManager;",
"import org.xwiki.user.UserReference;\nimport org.xwiki.user.UserReferenceResolver;",
"import org.xwiki.velocity.VelocityManager;",
"import com.fasterxml.jackson.databind.ObjectMapper;\nimport com.xpn.xwiki.XWiki;\nimport com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.XWikiException;",
"import com.xpn.xwiki.doc.DocumentRevisionProvider;",
"import com.xpn.xwiki.doc.XWikiDocument;\nimport com.xpn.xwiki.internal.web.LegacyAction;\nimport com.xpn.xwiki.monitor.api.MonitorPlugin;\nimport com.xpn.xwiki.objects.BaseObject;\nimport com.xpn.xwiki.plugin.fileupload.FileUploadPlugin;\nimport com.xpn.xwiki.redirection.RedirectionFilter;",
"/**\n * <p>\n * Root class for most XWiki actions. It provides a common framework that allows actions to execute just the specific\n * action code, handling the extra activities, such as preparing the context and retrieving the document corresponding\n * to the URL.\n * </p>\n * <p>\n * It defines two methods, {@link #action(XWikiContext)} and {@link #render(XWikiContext)}, that should be overridden by\n * specific actions. {@link #action(XWikiContext)} should contain the processing part of the action.\n * {@link #render(XWikiContext)} should return the name of a template that should be rendered, or manually write to the\n * {@link XWikiResponse response} stream.\n * </p>\n * <p>\n * Serving a request goes through the following phases:\n * </p>\n * <ul>\n * <li>Wrapping the request and response object in XWiki specific wrappers</li>\n * <li>Prepare the request {@link XWikiContext XWiki-specific context}</li>\n * <li>Initialize/retrieve the XWiki object corresponding to the requested wiki</li>\n * <li>Handle file uploads</li>\n * <li>Prepare the velocity context</li>\n * <li>Prepare the document objects corresponding to the requested URL</li>\n * <li>Send action pre-notifications to listeners</li>\n * <li>Run the overridden {@link #action(XWikiContext)}</li>\n * <li>If {@link #action(XWikiContext)} returns true, run the overridden {@link #render(XWikiContext)}</li>\n * <li>If {@link #render(XWikiContext)} returned a string (template name), render the template with that name</li>\n * <li>Send action post-notifications to listeners</li>\n * </ul>\n * <p>\n * During this process, also handle specific errors, like when a document does not exist, or the user does not have the\n * right to perform the current action.\n * </p>\n */\npublic abstract class XWikiAction implements LegacyAction\n{\n public static final String ACTION_PROGRESS = \"actionprogress\";",
" private static final Logger LOGGER = LoggerFactory.getLogger(XWikiAction.class);",
" /**\n * Actions that need to be resolved on the main wiki instead of the current non-existing wiki. This is used to be\n * able to render the skin even on a wiki that doesn't exist.\n */\n private static final List<String> ACTIONS_IGNORED_WHEN_WIKI_DOES_NOT_EXIST =\n Arrays.asList(\"skin\", \"ssx\", \"jsx\", \"download\");",
" @Inject\n protected ComponentDescriptor<LegacyAction> componentDescriptor;",
" @Inject\n protected Container container;",
" @Inject\n protected Execution execution;",
" @Inject\n protected ObservationManager observation;",
" @Inject\n @Named(\"context\")\n private ComponentManager componentManager;",
" /**\n * Indicate if the action allow asynchronous display (among which the XWiki initialization).\n */\n protected boolean waitForXWikiInitialization = true;",
" @Inject\n @Named(\"currentmixed\")\n private DocumentReferenceResolver<String> currentmixedReferenceResolver;",
" @Inject\n private ContextualAuthorizationManager autorization;",
" private ContextualLocalizationManager localization;",
" private JobProgressManager progress;",
" private ScriptContextManager scriptContextManager;",
" private EntityNameValidationManager entityNameValidationManager;",
" private EntityNameValidationConfiguration entityNameValidationConfiguration;",
" private EntityReferenceSerializer<String> localSerializer;",
"\n @Inject\n private DocumentRevisionProvider documentRevisionProvider;",
" @Inject\n @Named(\"document\")\n private UserReferenceResolver<DocumentReference> userReferenceResolver;",
"\n /**\n * @return the class of the XWikiForm in charge of parsing the request\n * @since 13.0\n */\n @Unstable\n protected Class<? extends XWikiForm> getFormClass()\n {\n return null;\n }",
" protected ContextualLocalizationManager getLocalization()\n {\n if (this.localization == null) {\n this.localization = Utils.getComponent(ContextualLocalizationManager.class);\n }",
" return this.localization;\n }",
" /**\n * @since 12.10.6\n * @since 13.2RC1\n */\n protected DocumentReferenceResolver<String> getCurrentMixedDocumentReferenceResolver()\n {\n return this.currentmixedReferenceResolver;\n }",
" /**\n * @since 12.10.6\n * @since 13.2RC1\n */\n protected ContextualAuthorizationManager getContextualAuthorizationManager()\n {\n return this.autorization;\n }",
" protected String localizePlainOrKey(String key, Object... parameters)\n {\n return StringUtils.defaultString(getLocalization().getTranslationPlain(key, parameters), key);\n }",
" protected JobProgressManager getProgress()\n {\n if (this.progress == null) {\n this.progress = Utils.getComponent(JobProgressManager.class);\n }",
" return this.progress;\n }",
" protected EntityNameValidationManager getEntityNameValidationManager()\n {\n if (this.entityNameValidationManager == null) {\n this.entityNameValidationManager = Utils.getComponent(EntityNameValidationManager.class);\n }\n return this.entityNameValidationManager;\n }",
" protected EntityNameValidationConfiguration getEntityNameValidationConfiguration()\n {\n if (this.entityNameValidationConfiguration == null) {\n this.entityNameValidationConfiguration = Utils.getComponent(EntityNameValidationConfiguration.class);\n }",
" return this.entityNameValidationConfiguration;\n }",
" protected EntityReferenceSerializer<String> getLocalSerializer()\n {\n if (this.localSerializer == null) {\n this.localSerializer = Utils.getComponent(EntityReferenceSerializer.TYPE_STRING, \"local\");\n }\n return this.localSerializer;\n }",
" /**\n * @return the current unmodified {@link ScriptContext} instance\n * @since 8.3M1\n */\n protected ScriptContext getCurrentScriptContext()\n {\n if (this.scriptContextManager == null) {\n this.scriptContextManager = Utils.getComponent(ScriptContextManager.class);\n }",
" return this.scriptContextManager.getCurrentScriptContext();\n }",
" @Override\n public void execute(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception\n {\n XWikiContext context = null;",
" try {\n // Initialize the XWiki Context which is the main object used to pass information across\n // classes/methods. It's also wrapping the request, response, and all container objects\n // in general.\n context = initializeXWikiContext(servletRequest, servletResponse);",
" // From this line forward all information can be found in the XWiki Context.\n execute(context);\n } finally {\n if (context != null) {\n cleanupComponents();\n }\n }\n }",
" /**\n * Ensure that the given entity reference is valid according to the configured name strategy. Always returns true if\n * the name strategy is not found.\n *\n * @param entityReference the entity reference name to validate\n * @return {@code true} if the entity reference name is valid according to the name strategy.\n * @since 12.0RC1\n */\n protected boolean isEntityReferenceNameValid(EntityReference entityReference)\n {\n if (this.getEntityNameValidationManager().getEntityReferenceNameStrategy() != null\n && this.getEntityNameValidationConfiguration().useValidation()) {\n if (!this.getEntityNameValidationManager().getEntityReferenceNameStrategy().isValid(entityReference)) {\n Object[] args = {getLocalSerializer().serialize(entityReference)};\n XWikiException invalidNameException = new XWikiException(XWikiException.MODULE_XWIKI_STORE,\n XWikiException.ERROR_XWIKI_APP_DOCUMENT_NAME_INVALID,\n \"Cannot create document {0} because its name does not respect the name strategy of the wiki.\", null,\n args);\n ScriptContext scontext = getCurrentScriptContext();\n scontext.setAttribute(\"invalidNameReference\", entityReference, ScriptContext.ENGINE_SCOPE);\n scontext.setAttribute(\"createException\", invalidNameException, ScriptContext.ENGINE_SCOPE);\n return false;\n }\n }\n return true;\n }",
" /**\n * Write an error response to an ajax request.\n *\n * @param httpStatusCode The status code to set on the response.\n * @param message The message that should be displayed.\n * @param context the context.\n */\n protected void writeAjaxErrorResponse(int httpStatusCode, String message, XWikiContext context)\n {\n try {\n context.getResponse().setContentType(\"text/plain\");\n context.getResponse().setStatus(httpStatusCode);\n context.getResponse().setCharacterEncoding(context.getWiki().getEncoding());\n context.getResponse().getWriter().print(message);\n } catch (IOException e) {\n LOGGER.error(\"Failed to send error response to AJAX save and continue request.\", e);\n }\n }",
" public void execute(XWikiContext context) throws Exception\n {\n MonitorPlugin monitor = null;\n FileUploadPlugin fileupload = null;\n DefaultJobProgress actionProgress = null;\n String docName = \"\";",
" boolean debug = StringUtils.equals(context.getRequest().get(\"debug\"), \"true\");",
" String sasync = context.getRequest().get(\"async\");",
" try {\n String action = context.getAction();",
" // Start progress\n if (debug) {\n actionProgress = new DefaultJobProgress(context.getURL().toExternalForm());\n this.observation.addListener(new WrappedThreadEventListener(actionProgress));",
" // Register the action progress in the context\n ExecutionContext econtext = this.execution.getContext();\n if (econtext != null) {\n econtext.setProperty(XWikiAction.ACTION_PROGRESS, actionProgress);\n }\n }",
" getProgress().pushLevelProgress(2, this);",
" getProgress().startStep(this, \"Get XWiki instance\");",
" // Initialize context.getWiki() with the main wiki\n XWiki xwiki;",
" // Verify that the requested wiki exists\n try {\n // Don't show init screen if async is forced to false\n xwiki = XWiki.getXWiki(this.waitForXWikiInitialization || StringUtils.equals(sasync, \"false\"), context);",
" // If XWiki is still initializing display initialization template\n if (xwiki == null) {\n // Display initialization template\n renderInit(context);",
" // Initialization template has been displayed, stop here.\n return;\n }\n } catch (XWikiException e) {\n // If the wiki asked by the user doesn't exist, then we first attempt to use any existing global\n // redirects. If there are none, then we display the specific error template.\n if (e.getCode() == XWikiException.ERROR_XWIKI_DOES_NOT_EXIST) {\n xwiki = XWiki.getMainXWiki(context);",
" // Initialize the url factory\n XWikiURLFactory urlf = xwiki.getURLFactoryService().createURLFactory(context.getMode(), context);\n context.setURLFactory(urlf);",
" // Initialize the velocity context and its bindings so that it may be used in the velocity templates\n // that we\n // are parsing below.\n VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);\n VelocityContext vcontext = velocityManager.getVelocityContext();",
" if (!sendGlobalRedirect(context.getResponse(), context.getURL().toString(), context)) {\n // Starting XWiki 5.0M2, 'xwiki.virtual.redirect' was removed. Warn users still using it.\n if (!StringUtils.isEmpty(context.getWiki().Param(\"xwiki.virtual.redirect\"))) {\n LOGGER.warn(String.format(\"%s %s\", \"'xwiki.virtual.redirect' is no longer supported.\",\n \"Please update your configuration and/or see XWIKI-8914 for more details.\"));\n }",
" // Display the error template only for actions that are not ignored\n if (!ACTIONS_IGNORED_WHEN_WIKI_DOES_NOT_EXIST.contains(action)) {",
" // Add localization resources to the context\n xwiki.prepareResources(context);",
" // Set the main home page in the main space of the main wiki as the current requested entity\n // since we cannot set the non existing one as it would generate errors obviously...\n EntityReferenceValueProvider valueProvider =\n Utils.getComponent(EntityReferenceValueProvider.class);\n xwiki.setPhonyDocument(new DocumentReference(valueProvider.getDefaultValue(EntityType.WIKI),\n valueProvider.getDefaultValue(EntityType.SPACE),\n valueProvider.getDefaultValue(EntityType.DOCUMENT)), context, vcontext);",
" // Parse the error template\n Utils.parseTemplate(context.getWiki().Param(\"xwiki.wiki_exception\", \"wikidoesnotexist\"),\n context);",
" // Error template was displayed, stop here.\n return;\n }",
" // At this point, we allow regular execution of the ignored action because even if the wiki\n // does not exist, we still need to allow UI resources to be retrieved (from the filesystem\n // and the main wiki) or our error template will not be rendered properly.",
" // Proceed with serving the main wiki",
" } else {\n // Global redirect was executed, stop here.\n return;\n }\n } else {\n LOGGER.error(\"Uncaught exception during XWiki initialisation:\", e);\n throw e;\n }\n }",
" // Send global redirection (if any)\n if (sendGlobalRedirect(context.getResponse(), context.getURL().toString(), context)) {\n return;\n }",
" XWikiURLFactory urlf = xwiki.getURLFactoryService().createURLFactory(context.getMode(), context);\n context.setURLFactory(urlf);",
" // Handle ability to enter space URLs and convert them to page URLs (Nested Documents)\n if (redirectSpaceURLs(action, urlf, xwiki, context)) {\n return;\n }",
" String sajax = context.getRequest().get(\"ajax\");\n boolean ajax = false;\n if (sajax != null && !sajax.trim().equals(\"\") && !sajax.equals(\"0\")) {\n ajax = true;\n }\n context.put(\"ajax\", ajax);",
" boolean async = false;\n if (StringUtils.isNotEmpty(sasync)) {\n async = sasync.equals(\"true\");\n } else {\n // By default allow asynchronous rendering for \"human oriented\" actions which are not executing an ajax\n // request\n async = !ajax && !this.waitForXWikiInitialization;\n }\n Utils.getComponent(AsyncContext.class).setEnabled(async);",
" // Any error before this will be treated using a redirection to an error page",
" if (monitor != null) {\n monitor.startTimer(\"request\");\n }",
" getProgress().startStep(this, \"Execute request\");",
" VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);\n VelocityContext vcontext = velocityManager.getVelocityContext();",
" getProgress().pushLevelProgress(7, this);",
" boolean eventSent = false;\n try {\n getProgress().startStep(this, \"Prepare documents and put them in the context\");",
" // Prepare documents and put them in the context\n if (!xwiki.prepareDocuments(context.getRequest(), context, vcontext)) {\n return;\n }",
" // Start monitoring timer\n monitor = (MonitorPlugin) xwiki.getPlugin(\"monitor\", context);\n if (monitor != null) {\n monitor.startRequest(\"\", context.getAction(), context.getURL());\n monitor.startTimer(\"multipart\");\n }",
" getProgress().startStep(this, \"Parses multipart\");",
" // Parses multipart so that params in multipart are available for all actions\n fileupload = Utils.handleMultipart(context.getRequest().getHttpServletRequest(), context);\n if (monitor != null) {\n monitor.endTimer(\"multipart\");\n }",
" if (monitor != null) {\n monitor.setWikiPage(context.getDoc().getFullName());\n }",
" getProgress().startStep(this, \"Send [\" + context.getAction() + \"] action start event\");",
" // For the moment we're sending the XWiki context as the data, but this will be\n // changed in the future, when the whole platform will be written using components\n // and there won't be a need for the context.\n try {\n ActionExecutingEvent event = new ActionExecutingEvent(context.getAction());\n this.observation.notify(event, context.getDoc(), context);\n eventSent = true;\n if (event.isCanceled()) {\n // Action has been canceled\n // TODO: do something special ?\n return;\n }\n } catch (Throwable ex) {\n LOGGER.error(\"Cannot send action notifications for document [\" + context.getDoc()\n + \" using action [\" + context.getAction() + \"]\", ex);\n }",
" if (monitor != null) {\n monitor.endTimer(\"prenotify\");\n }",
" // Call the Actions",
" getProgress().startStep(this, \"Search and execute entity resource handler\");",
" // Call the new Entity Resource Reference Handler.\n ResourceReferenceHandler entityResourceReferenceHandler = Utils.getComponent(\n new DefaultParameterizedType(null, ResourceReferenceHandler.class, ResourceType.class), \"bin\");\n EntityResourceReference entityResourceReference =\n (EntityResourceReference) Utils.getComponent(ResourceReferenceManager.class).getResourceReference();",
" // We save the current action set since:\n // - by default the action is set to \"view\" for Extensions not installed as root and contributing some\n // new Entity Action (see https://jira.xwiki.org/browse/XWIKI-15182).\n // - we want to set back the action in case no ResourceReferenceHandler was found to handle the URL\n // TODO: Remove once https://jira.xwiki.org/browse/XWIKI-14947 is fixed\n String originalAction = context.getAction();\n try {\n // Force the action in the context because of https://jira.xwiki.org/browse/XWIKI-15182.\n // TODO: Remove once https://jira.xwiki.org/browse/XWIKI-14947 is fixed\n context.setAction(entityResourceReference.getAction().getActionName());\n entityResourceReferenceHandler.handle(entityResourceReference,\n DefaultResourceReferenceHandlerChain.EMPTY);\n // Don't let the old actions kick in!\n return;\n } catch (NotFoundResourceHandlerException e) {\n // No Entity Resource Action has been found. Don't do anything and let it go through\n // so that the old Action system kicks in...\n // Put back the action, because of https://jira.xwiki.org/browse/XWIKI-15182\n // TODO: Remove once https://jira.xwiki.org/browse/XWIKI-14947 is fixed\n context.setAction(originalAction);\n }",
" getProgress().startStep(this, \"Execute action render\");",
" // Handle the XWiki.RedirectClass object that can be attached to the current document\n boolean hasRedirect = handleRedirect(context);",
" // Then call the old Actions for backward compatibility (and because a lot of them have not been\n // migrated to new Actions yet).\n String renderResult = null;\n XWikiDocument doc = context.getDoc();\n docName = doc.getFullName();\n if (!hasRedirect && action(context)) {\n renderResult = render(context);\n }",
" if (renderResult != null) {\n // check for doc existence\n if (shouldReturnDocDoesNotExist(doc, context)) {\n String page = Utils.getPage(context.getRequest(), \"docdoesnotexist\");",
" getProgress().startStep(this, \"Execute template [\" + page + \"]\");\n Utils.parseTemplate(page, context);\n } else {\n String page = Utils.getPage(context.getRequest(), renderResult);",
" getProgress().startStep(this, \"Execute template [\" + page + \"]\");\n Utils.parseTemplate(page, !page.equals(\"direct\"), context);\n }\n }\n return;\n } catch (Throwable e) {\n if (e instanceof IOException) {\n e = new XWikiException(XWikiException.MODULE_XWIKI_APP,\n XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, \"Exception while sending response\", e);\n }",
" if (!(e instanceof XWikiException)) {\n e = new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_UNKNOWN,\n \"Uncaught exception\", e);\n }",
" try {\n XWikiException xex = (XWikiException) e;\n if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {\n // Connection aborted from the client side, there's not much we can do on the server side. We\n // simply ignore it.\n LOGGER.debug(\"Connection aborted\", e);\n // We don't write any other message to the response, as the connection is broken, anyway.\n return;\n } else if (xex.getCode() == XWikiException.ERROR_XWIKI_ACCESS_DENIED) {\n Utils.parseTemplate(context.getWiki().Param(\"xwiki.access_exception\", \"accessdenied\"), context);\n return;\n } else if (xex.getCode() == XWikiException.ERROR_XWIKI_USER_INACTIVE\n || xex.getCode() == XWikiException.ERROR_XWIKI_USER_DISABLED) {\n if (xex.getCode() == XWikiException.ERROR_XWIKI_USER_DISABLED) {\n context.put(\"cause\", \"disabled\");\n }\n // In case of user disabled or inactive, the resources are actually forbidden.\n context.getResponse().setStatus(HttpServletResponse.SC_FORBIDDEN);\n Utils.parseTemplate(context.getWiki().Param(\"xwiki.user_exception\", \"userinactive\"), context);",
" return;\n } else if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_ATTACHMENT_NOT_FOUND) {\n context.put(\"message\", \"attachmentdoesnotexist\");\n Utils.parseTemplate(\n context.getWiki().Param(\"xwiki.attachment_exception\", \"attachmentdoesnotexist\"), context);\n return;\n } else if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION) {\n vcontext.put(\"message\", localizePlainOrKey(\"platform.core.invalidUrl\"));\n xwiki.setPhonyDocument(xwiki.getDefaultSpace(context) + \".\" + xwiki.getDefaultPage(context),\n context, vcontext);\n context.getResponse().setStatus(HttpServletResponse.SC_BAD_REQUEST);\n Utils.parseTemplate(context.getWiki().Param(\"xwiki.invalid_url_exception\", \"error\"), context);\n return;\n }\n // Note: We don't use the vcontext variable computed above since apparently the velocity context\n // can have changed in between. Thus we get it again to be sure we're setting the binding in the\n // right one.\n velocityManager.getVelocityContext().put(\"exp\", e);\n if (LOGGER.isWarnEnabled()) {\n // Don't log \"Broken Pipe\" exceptions since they're not real errors and we don't want to pollute\n // the logs with unnecessary stack traces. It just means the client side has cancelled the\n // connection.\n if (ExceptionUtils.getRootCauseMessage(e).equals(\"IOException: Broken pipe\")) {\n return;\n }\n LOGGER.warn(\"Uncaught exception: \" + e.getMessage(), e);\n }\n // If the request is an AJAX request, we don't return a whole HTML page, but just the exception\n // inline.\n String exceptionTemplate = ajax ? \"exceptioninline\" : \"exception\";\n Utils.parseTemplate(Utils.getPage(context.getRequest(), exceptionTemplate), context);\n return;\n } catch (XWikiException ex) {\n if (ex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {\n LOGGER.error(\"Connection aborted\");\n }\n } catch (Exception e2) {\n // I hope this never happens\n LOGGER.error(\"Uncaught exceptions (inner): \", e);\n LOGGER.error(\"Uncaught exceptions (outer): \", e2);\n }\n return;\n } finally {\n // Let's make sure we have flushed content and closed\n try {\n context.getResponse().getWriter().flush();\n } catch (Throwable e) {\n // This might happen if the connection was closed, for example.\n // If we can't flush, then there's nothing more we can send to the client.\n }",
" if (monitor != null) {\n monitor.endTimer(\"request\");\n monitor.startTimer(\"notify\");\n }",
" if (eventSent) {\n // For the moment we're sending the XWiki context as the data, but this will be\n // changed in the future, when the whole platform will be written using components\n // and there won't be a need for the context.\n try {\n this.observation.notify(new ActionExecutedEvent(context.getAction()), context.getDoc(), context);\n } catch (Throwable ex) {\n LOGGER.error(\"Cannot send action notifications for document [\" + docName + \" using action [\"\n + context.getAction() + \"]\", ex);\n }\n }",
" if (monitor != null) {\n monitor.endTimer(\"notify\");\n }",
" getProgress().startStep(this, \"Cleanup database connections\");",
" // Make sure we cleanup database connections\n // There could be cases where we have some\n xwiki.getStore().cleanUp(context);",
" getProgress().popLevelProgress(this);\n }\n } finally {\n // End request\n if (monitor != null) {\n monitor.endRequest();\n }",
" // Stop progress\n if (actionProgress != null) {\n getProgress().popLevelProgress(this);",
" this.observation.removeListener(actionProgress.getName());\n }",
" if (fileupload != null) {\n fileupload.cleanFileList(context);\n }\n }\n }",
" /**\n * Check if the given document exists or not and if it should return a 404 based on the context. A {@link\n * DocExistValidator} with an hint matching the current action is used to check if the document exists. When no\n * {@link DocExistValidator} is found, the response is always {@code false} When a {@link DocExistValidator} is\n * found, the result is delegated to {@link DocExistValidator#docExist(XWikiDocument, XWikiContext)}.\n *\n * @param doc the doc for which to check it exists or not\n * @param context the current context\n * @return {@code true} if we should return a 404\n * @throws ComponentLookupException if an error occurs when instantiating a {@link DocExistValidator}\n */\n private boolean shouldReturnDocDoesNotExist(XWikiDocument doc, XWikiContext context) throws ComponentLookupException\n {\n boolean result = false;\n String action = context.getAction();\n if (this.componentManager.hasComponent(DocExistValidator.class, action)) {\n result = this.componentManager.<DocExistValidator>getInstance(DocExistValidator.class, action)\n .docExist(doc, context);\n }\n return result;\n }",
" private void renderInit(XWikiContext xcontext) throws Exception\n {\n RenderingContext renderingContext = Utils.getComponent(RenderingContext.class);\n MutableRenderingContext mutableRenderingContext =\n renderingContext instanceof MutableRenderingContext ? (MutableRenderingContext) renderingContext : null;",
" if (mutableRenderingContext != null) {\n mutableRenderingContext.push(renderingContext.getTransformation(), renderingContext.getXDOM(),\n renderingContext.getDefaultSyntax(), \"init.vm\", renderingContext.isRestricted(), Syntax.XHTML_1_0);\n }",
" xcontext.getResponse().setStatus(202);\n xcontext.getResponse().setContentType(\"text/html; charset=UTF-8\");",
" try {\n Utils.getComponent(TemplateManager.class).render(\"init.vm\", xcontext.getResponse().getWriter());\n } finally {\n if (mutableRenderingContext != null) {\n mutableRenderingContext.pop();\n }\n }",
" xcontext.getResponse().flushBuffer();",
" xcontext.setFinished(true);\n }",
" protected XWikiContext initializeXWikiContext(HttpServletRequest servletRequest,\n HttpServletResponse servletResponse)\n throws XWikiException, ServletException, InstantiationException, IllegalAccessException\n {\n XWikiForm form;\n if (getFormClass() != null) {\n form = getFormClass().newInstance();\n } else {\n form = null;\n }",
" return initializeXWikiContext(servletRequest, servletResponse, form);\n }",
" /**\n * @return the name to put in the {@link XWikiContext}, by default the component role hint is used\n * @since 13.0\n */\n @Unstable\n protected String getName()\n {\n return this.componentDescriptor.getRoleHint();\n }",
" protected XWikiContext initializeXWikiContext(HttpServletRequest servletRequest,\n HttpServletResponse servletResponse, XWikiForm form) throws XWikiException, ServletException\n {\n String action = getName();",
" XWikiRequest request = new XWikiServletRequest(servletRequest);\n XWikiResponse response = new XWikiServletResponse(servletResponse);\n XWikiContext context = Utils.prepareContext(action, request, response,\n new XWikiServletContext(servletRequest.getServletContext()));",
" if (form != null) {\n form.reset(request);\n }",
" // Add the form to the context\n context.setForm(form);",
" // Initialize the Container component which is the new way of transporting the Context in the new\n // component architecture.\n initializeContainerComponent(context);",
" return context;\n }",
" protected void initializeContainerComponent(XWikiContext context) throws ServletException\n {\n // Initialize the Container fields (request, response, session).\n // Note that this is a bridge between the old core and the component architecture.\n // In the new component architecture we use ThreadLocal to transport the request,\n // response and session to components which require them.\n // In the future this Servlet will be replaced by the XWikiPlexusServlet Servlet.\n ServletContainerInitializer containerInitializer = Utils.getComponent(ServletContainerInitializer.class);",
" try {\n containerInitializer.initializeRequest(context.getRequest().getHttpServletRequest(), context);\n containerInitializer.initializeResponse(context.getResponse());\n containerInitializer.initializeSession(context.getRequest().getHttpServletRequest());\n } catch (ServletContainerException e) {\n throw new ServletException(\"Failed to initialize Request/Response or Session\", e);\n }\n }",
" protected void cleanupComponents()\n {\n // We must ensure we clean the ThreadLocal variables located in the Container and Execution\n // components as otherwise we will have a potential memory leak.\n container.removeRequest();\n container.removeResponse();\n container.removeSession();\n execution.removeContext();\n }",
" public String getRealPath(String path)\n {\n Request request = this.container.getRequest();",
" if (request instanceof ServletRequest) {\n return ((ServletRequest) request).getHttpServletRequest().getServletContext().getRealPath(path);\n }",
" return null;\n }",
" // hook\n public boolean action(XWikiContext context) throws XWikiException\n {\n return true;\n }",
" // hook\n public String render(XWikiContext context) throws XWikiException\n {\n return null;\n }",
" /**\n * Indicate if the action support redirection. The default value is {@code false}.\n *\n * @return {@code true} if the action supports redirections, {@code false} otherwise\n * @since 14.0RC1\n */\n @Unstable\n protected boolean supportRedirections()\n {\n return false;\n }\n",
" private UserReference getCurrentUserReference(XWikiContext context)\n {\n return this.userReferenceResolver.resolve(context.getUserReference());\n }\n",
" protected void handleRevision(XWikiContext context) throws XWikiException\n {\n String rev = context.getRequest().getParameter(\"rev\");\n if (rev != null) {\n context.put(\"rev\", rev);\n XWikiDocument doc = (XWikiDocument) context.get(\"doc\");\n XWikiDocument tdoc = (XWikiDocument) context.get(\"tdoc\");\n // if the doc is deleted and we request a specific language, we have to set the locale so we can retrieve\n // properly the document revision.\n if (rev.startsWith(\"deleted\") && !StringUtils.isEmpty(context.getRequest().getParameter(\"language\"))\n && doc == tdoc) {\n Locale locale = LocaleUtils.toLocale(context.getRequest().getParameter(\"language\"), Locale.ROOT);\n tdoc = new XWikiDocument(tdoc.getDocumentReference(), locale);\n }",
"\n DocumentReference documentReference = doc.getDocumentReference();\n try {\n documentRevisionProvider\n .checkAccess(Right.VIEW, getCurrentUserReference(context), documentReference, rev);\n } catch (AuthorizationException e) {\n Object[] args = { documentReference, rev, context.getUserReference() };\n throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,\n \"Access to document {0} with revision {1} has been denied to user {2}\", e, args);\n }",
" XWikiDocument rdoc;\n XWikiDocument rtdoc;\n if (doc.getLocale().equals(tdoc.getLocale())) {\n rdoc = this.documentRevisionProvider.getRevision(doc.getDocumentReferenceWithLocale(), rev);\n rtdoc = rdoc;\n } else {\n rdoc = doc;\n rtdoc = this.documentRevisionProvider.getRevision(tdoc.getDocumentReferenceWithLocale(), rev);\n }",
"\n context.put(\"tdoc\", rtdoc);\n context.put(\"cdoc\", rdoc);\n context.put(\"doc\", rdoc);\n }\n }",
" /**\n * Send redirection based on a regexp pattern (if any) set at the main wiki level. To enable this feature you must\n * add xwiki.preferences.redirect=1 to your xwiki.cfg.\n *\n * @param response the servlet response\n * @param url url of the request\n * @param context the XWiki context\n * @return true if a redirection has been sent\n */\n protected boolean sendGlobalRedirect(XWikiResponse response, String url, XWikiContext context) throws Exception\n {\n if (\"1\".equals(context.getWiki().Param(\"xwiki.preferences.redirect\"))) {\n // Note: This implementation is not performant at all and will slow down the wiki as the number\n // of redirects increases. A better implementation would use a cache of redirects and would use\n // the notification mechanism to update the cache when the XWiki.XWikiPreferences document is\n // modified.\n XWikiDocument globalPreferences = context.getWiki().getDocument(\"xwiki:XWiki.XWikiPreferences\", context);\n Vector<BaseObject> redirects = globalPreferences.getObjects(\"XWiki.GlobalRedirect\");",
" if (redirects != null) {\n for (BaseObject redir : redirects) {\n if (redir != null) {\n String p = redir.getStringValue(\"pattern\");\n if (p != null && url.matches(p)) {\n String dest = redir.getStringValue(\"destination\");\n response.sendRedirect(url.replaceAll(p, dest));\n return true;\n }\n }\n }\n }\n }\n return false;\n }",
" /**\n * Perform a redirect to the given URL.\n * @param response the response to use to perform the redirect\n * @param url the location of the redirect\n * @throws XWikiException in case of IOException when performing the redirect.\n */\n protected void sendRedirect(XWikiResponse response, String url) throws XWikiException\n {\n try {\n if (url != null) {\n response.sendRedirect(response.encodeRedirectURL(url));\n }\n } catch (IOException e) {\n Object[] args = {url};\n throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_REDIRECT_EXCEPTION,\n \"Exception while sending redirect to page {0}\", e, args);\n }\n }",
" /**\n * Gets the translated version of a document, in the specified language. If the translation does not exist, a new\n * document translation is created. If the requested language does not correspond to a translation (is not defined\n * or is the same as the main document), then the main document is returned.\n *\n * @param doc the main (default, untranslated) document to translate\n * @param language the requested document language\n * @param context the current request context\n * @return the translated document, or the original untranslated document if the requested language is not a\n * translation\n * @throws XWikiException if the translation cannot be retrieved from the database\n */\n protected XWikiDocument getTranslatedDocument(XWikiDocument doc, String language, XWikiContext context)\n throws XWikiException\n {\n XWikiDocument tdoc;\n if (StringUtils.isBlank(language) || language.equals(\"default\") || language.equals(doc.getDefaultLanguage())) {\n tdoc = doc;\n } else {\n tdoc = doc.getTranslatedDocument(language, context);\n if (tdoc == doc) {\n tdoc = new XWikiDocument(doc.getDocumentReference());\n tdoc.setLanguage(language);\n tdoc.setStore(doc.getStore());\n }\n tdoc.setTranslation(1);\n }\n return tdoc;\n }",
" /**\n * Perform CSRF check and redirect to the resubmission page if needed. Throws an exception if the access should be\n * denied, returns false if the check failed and the user will be redirected to a resubmission page.\n *\n * @param context current xwiki context containing the request\n * @return true if the check succeeded, false if resubmission is needed\n * @throws XWikiException if the check fails\n */\n protected boolean csrfTokenCheck(XWikiContext context) throws XWikiException\n {\n return csrfTokenCheck(context, false);\n }",
" /**\n * Perform CSRF check and redirect to the resubmission page if needed. Throws an exception if the access should be\n * denied, returns false if the check failed and the user will be redirected to a resubmission page.\n *\n * @param context current xwiki context containing the request\n * @param jsonAnswer if true, returns a JSON answer in case of AJAX request: allow to process it properly on client.\n * @return true if the check succeeded, false if resubmission is needed\n * @throws XWikiException if the check fails\n * @since 11.3RC1\n */\n protected boolean csrfTokenCheck(XWikiContext context, boolean jsonAnswer) throws XWikiException\n {\n final boolean isAjaxRequest = Utils.isAjaxRequest(context);\n CSRFToken csrf = Utils.getComponent(CSRFToken.class);\n try {\n String token = context.getRequest().getParameter(\"form_token\");\n if (!csrf.isTokenValid(token)) {\n if (isAjaxRequest) {\n if (jsonAnswer) {\n Map<String, String> jsonObject = new LinkedHashMap<>();\n jsonObject.put(\"errorType\", \"CSRF\");\n jsonObject.put(\"resubmissionURI\", csrf.getRequestURI());\n jsonObject.put(\"newToken\", csrf.getToken());\n this.answerJSON(context, HttpServletResponse.SC_FORBIDDEN, jsonObject);\n } else {\n final String csrfCheckFailedMessage = localizePlainOrKey(\"core.editors.csrfCheckFailed\");\n writeAjaxErrorResponse(HttpServletResponse.SC_FORBIDDEN, csrfCheckFailedMessage, context);\n }\n } else {\n sendRedirect(context.getResponse(), csrf.getResubmissionURL());\n }",
" return false;\n }\n } catch (XWikiException exception) {\n // too bad\n throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,\n \"Access denied, secret token verification failed\", exception);\n }\n return true;\n }",
" /**\n * In order to let users enter URLs to Spaces we do the following when receiving {@code /A/B} (where A and B are\n * spaces):\n * <ul>\n * <li>check that the action is \"view\" (we only support this for the view action since otherwise this would break\n * apps written before this concept was introduced in XWiki 7.2M1)</li>\n * <li>if A.B exists then continue</li>\n * <li>if A.B doesn't exist then forward to A.B.WebHome</li>\n * </ul>\n * In order to disable this redirect you should provide the {@code spaceRedirect=false} Query String parameter and\n * value.\n *\n * @since 7.2M1\n */\n private boolean redirectSpaceURLs(String action, XWikiURLFactory urlf, XWiki xwiki, XWikiContext context)\n throws Exception\n {\n if (\"view\".equals(action) && !\"false\".equalsIgnoreCase(context.getRequest().getParameter(\"spaceRedirect\"))) {\n DocumentReference reference = xwiki.getDocumentReference(context.getRequest(), context);\n if (!xwiki.exists(reference, context)) {\n String defaultDocumentName = Utils.getComponent(EntityReferenceProvider.class)\n .getDefaultReference(EntityType.DOCUMENT).getName();\n // Avoid an infinite loop by ensuring we're not on a WebHome already\n if (!reference.getName().equals(defaultDocumentName)) {\n // Consider the reference as a Space Reference and Construct a new reference to the home of that\n // Space. Then generate the URL for it and forward to it\n SpaceReference spaceReference = new SpaceReference(reference.getName(), reference.getParent());\n // Extract the anchor\n String anchor = new URL(context.getRequest().getRequestURL().toString()).getRef();\n URL forwardURL = urlf.createURL(getLocalSerializer().serialize(spaceReference), defaultDocumentName,\n action, context.getRequest().getQueryString(), anchor,\n spaceReference.getWikiReference().getName(), context);\n // Since createURL() contain the webapp context and since RequestDispatcher should not contain it,\n // we need to remove it!\n String webappContext = xwiki.getWebAppPath(context);\n String relativeURL = urlf.getURL(forwardURL, context);\n relativeURL = '/' + StringUtils.substringAfter(relativeURL, webappContext);\n context.getRequest().getRequestDispatcher(relativeURL).forward(context.getRequest(),\n context.getResponse());\n return true;\n }\n }\n }",
" return false;\n }",
" /**\n * Answer to a request with a JSON content.\n * \n * @param context the current context of the request.\n * @param status the status code to send back.\n * @param answer the content of the JSON answer.\n * @throws XWikiException in case of error during the serialization of the JSON.\n */\n protected void answerJSON(XWikiContext context, int status, Map<String, String> answer) throws XWikiException\n {\n ObjectMapper mapper = new ObjectMapper();",
" try {\n String jsonAnswerAsString = mapper.writeValueAsString(answer);\n context.getResponse().setContentType(\"application/json\");\n context.getResponse().setContentLength(jsonAnswerAsString.length());\n context.getResponse().setStatus(status);\n context.getResponse().setCharacterEncoding(context.getWiki().getEncoding());\n context.getResponse().getWriter().print(jsonAnswerAsString);\n context.setResponseSent(true);\n } catch (IOException e) {\n throw new XWikiException(\"Error while sending JSON answer.\", e);\n }\n }",
" /**\n * Make sure to set the right length (or nothing) in the response.\n * \n * @param response the response\n * @param length the length to set in the response\n * @since 11.10\n * @since 10.11.10\n * @since 11.3.6\n */\n protected void setContentLength(XWikiResponse response, long length)\n {\n // Set the content length in the response\n response.setContentLengthLong(length);\n }",
" /**\n * Helper used resolve the template passed to the action if the current user have access to it.\n * \n * @param template the template to copy\n * @return the reference of the template if not empty and the current user have access to it\n * @since 12.10.6\n * @since 13.2RC1\n */\n protected DocumentReference resolveTemplate(String template)\n {\n if (StringUtils.isNotBlank(template)) {\n DocumentReference templateReference = getCurrentMixedDocumentReferenceResolver().resolve(template);",
" // Make sure the current user have access to the template document before copying it\n if (getContextualAuthorizationManager().hasAccess(Right.VIEW, templateReference)) {\n return templateReference;\n }\n }",
" return null;\n }",
" /**\n * Helper used by various actions to initialize a document by copying a template to it.\n * \n * @param document the document to update\n * @param template the template to copy\n * @param context the XWiki context\n * @return true if the document was updated, false otherwise (for example when the current user does not have view\n * right on the template document)\n * @throws XWikiException when failing to copy the template\n * @since 12.10.6\n * @since 13.2RC1\n */\n @Unstable\n protected boolean readFromTemplate(XWikiDocument document, String template, XWikiContext context)\n throws XWikiException\n {\n DocumentReference templateReference = resolveTemplate(template);",
" if (templateReference != null) {\n document.readFromTemplate(templateReference, context);",
" return true;\n }",
" return false;\n }",
" /**\n * Loop over the {@link RedirectionFilter} components until one of them perform a redirection. If none of the does,\n * the action continues normally.\n *\n * @param context the current wiki content\n * @return {@code true} if a redirection has been performed, {@code false} otherwise\n * @throws XWikiException in case of error during the execution of a redirection filter\n */\n private boolean handleRedirect(XWikiContext context) throws XWikiException\n {\n // If no redirection are expected, this step is skipped.\n if (this.supportRedirections()) {\n try {\n for (RedirectionFilter filter : this.componentManager.<RedirectionFilter>getInstanceList(\n RedirectionFilter.class)) {\n if (filter.redirect(context)) {\n return true;\n }\n }\n } catch (ComponentLookupException e) {\n throw new XWikiException(\"Failed to resolve the redirection filters list\", e);\n }\n }\n return false;\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.web;",
"import java.util.Arrays;\nimport java.util.List;\nimport java.util.Locale;",
"import org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.mockito.Mock;\nimport org.xwiki.csrf.CSRFToken;\nimport org.xwiki.job.Job;\nimport org.xwiki.job.JobExecutor;\nimport org.xwiki.model.reference.DocumentReference;\nimport org.xwiki.refactoring.job.RefactoringJobs;\nimport org.xwiki.refactoring.job.RestoreRequest;\nimport org.xwiki.refactoring.script.RefactoringScriptService;\nimport org.xwiki.refactoring.script.RequestFactory;\nimport org.xwiki.script.service.ScriptService;\nimport org.xwiki.security.authorization.Right;\nimport org.xwiki.test.junit5.mockito.InjectComponentManager;\nimport org.xwiki.test.junit5.mockito.MockComponent;\nimport org.xwiki.test.mockito.MockitoComponentManager;",
"import com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.doc.XWikiDeletedDocument;\nimport com.xpn.xwiki.doc.XWikiDocument;",
"",
"import com.xpn.xwiki.test.MockitoOldcore;\nimport com.xpn.xwiki.test.junit5.mockito.InjectMockitoOldcore;\nimport com.xpn.xwiki.test.junit5.mockito.OldcoreTest;\nimport com.xpn.xwiki.test.reference.ReferenceComponentList;",
"import static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertFalse;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\nimport static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.ArgumentMatchers.anyLong;\nimport static org.mockito.ArgumentMatchers.anyString;\nimport static org.mockito.Mockito.doReturn;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.never;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;",
"/**\n * Unit tests for {@link UndeleteAction}.\n *\n * @version $Id$\n */\n@OldcoreTest\n@ReferenceComponentList\nclass UndeleteActionTest\n{\n private static final DocumentReference DELETED_REFERENCE =\n new DocumentReference(\"xwiki\", \"Main\", \"DeletedDocument\");",
" private static final long ID = 13;",
" @MockComponent\n private RequestFactory requestFactory;",
" @MockComponent\n private CSRFToken csrfToken;",
" @Mock\n private RefactoringScriptService refactoringScriptService;",
" @MockComponent\n private JobExecutor jobExecutor;",
" @InjectMockitoOldcore\n private MockitoOldcore oldcore;",
" @InjectComponentManager\n private MockitoComponentManager componentManager;",
" @Mock\n private XWikiRequest request;",
" @Mock\n private Job job;",
" @Mock\n private RestoreRequest jobRequest;",
" @Mock\n private XWikiDeletedDocument deletedDocument;\n",
"",
" /**\n * The object being tested.\n */\n private UndeleteAction undeleteAction = new UndeleteAction();",
" @BeforeEach\n void beforeEach() throws Exception\n {\n this.oldcore.getXWikiContext().setRequest(this.request);",
"",
" XWikiDocument contextDocument = mock(XWikiDocument.class);\n when(contextDocument.getDocumentReference()).thenReturn(DELETED_REFERENCE);\n this.oldcore.getXWikiContext().setDoc(contextDocument);",
" when(this.jobExecutor.execute(anyString(), any())).thenReturn(this.job);",
" this.componentManager.registerComponent(ScriptService.class, \"refactoring\", this.refactoringScriptService);\n when(this.refactoringScriptService.getRequestFactory()).thenReturn(this.requestFactory);\n when(this.requestFactory.createRestoreRequest(any(List.class))).thenReturn(this.jobRequest);\n when(this.requestFactory.createRestoreRequest(anyString())).thenReturn(this.jobRequest);",
" when(this.request.getParameter(\"id\")).thenReturn(String.valueOf(ID));",
" when(this.deletedDocument.getLocale()).thenReturn(Locale.ROOT);\n when(deletedDocument.getLocale()).thenReturn(Locale.ROOT);\n when(deletedDocument.getId()).thenReturn(ID);\n when(deletedDocument.getDocumentReference()).thenReturn(DELETED_REFERENCE);\n doReturn(this.deletedDocument).when(this.oldcore.getSpyXWiki()).getDeletedDocument(anyLong(),\n any(XWikiContext.class));\n }",
" /**\n * Launches a RestoreJob with the current deleted document ID.\n */\n @Test\n void restoreSingleDocument() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);\n",
" when(this.oldcore.getMockRightService().hasAccessLevel(any(), any(), any(), any())).thenReturn(true);\n",
" assertFalse(this.undeleteAction.action(this.oldcore.getXWikiContext()));",
" verify(this.requestFactory).createRestoreRequest(Arrays.asList(ID));\n verify(jobExecutor).execute(RefactoringJobs.RESTORE, jobRequest);\n verify(job).join();\n }",
" @Test\n void restoreSingleDocumentWhenDeleter() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);\n",
" when(this.oldcore.getMockAuthorizationManager().hasAccess(Right.EDIT, null, DELETED_REFERENCE))",
" .thenReturn(true);",
" assertFalse(this.undeleteAction.action(this.oldcore.getXWikiContext()));",
" verify(this.requestFactory).createRestoreRequest(Arrays.asList(ID));\n verify(jobExecutor).execute(RefactoringJobs.RESTORE, jobRequest);\n verify(job).join();\n }",
" @Test\n void missingCSRFToken() throws Exception\n {\n // Invalid CSRF token.\n when(this.csrfToken.isTokenValid(null)).thenReturn(false);",
" assertFalse(this.undeleteAction.action(this.oldcore.getXWikiContext()));",
" // Verify that the resubmission URL was retrieved to be used in the redirect.\n verify(this.csrfToken).getResubmissionURL();\n }",
" /**\n * When the recycle bin is disabled or when the deleted document ID is invalid, the document should not be restored.\n */\n @Test\n void recycleBinDisabledOrInvalidId() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);",
" // null is returned when the ID is invalid or the Recycle Bin is disabled.\n doReturn(null).when(this.oldcore.getSpyXWiki()).getDeletedDocument(anyLong(), any(XWikiContext.class));",
" assertFalse(this.undeleteAction.action(this.oldcore.getXWikiContext()));",
" // Verify that we never get this far.\n verify(this.requestFactory, never()).createRestoreRequest(Arrays.asList(ID));\n }",
" /**\n * Show the \"restore\" UI with the option to include the batch when restoring and to see the contents of the batch of\n * the current deleted document.\n */\n @Test\n void showBatch() throws Exception\n {\n when(this.request.getParameter(\"showBatch\")).thenReturn(\"true\");\n",
" when(this.oldcore.getMockRightService().hasAccessLevel(any(), any(), any(), any())).thenReturn(true);\n",
" assertTrue(this.undeleteAction.action(this.oldcore.getXWikiContext()));\n // Render the \"restore\" template.\n assertEquals(\"restore\", undeleteAction.render(this.oldcore.getXWikiContext()));",
" // Just make sure that we stop to the display, since the \"confirm=true\" parameter was not passed.\n verify(this.requestFactory, never()).createRestoreRequest(Arrays.asList(ID));\n }",
" /**\n * Launches a RestoreJob with the batchId of the current deleted document.\n */\n @Test\n void restoreBatch() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);",
" String batchId = \"abc123\";",
" when(deletedDocument.getBatchId()).thenReturn(batchId);",
" // Go through the screen showing the option to include the batch and displaying its contents.\n when(this.request.getParameter(\"showBatch\")).thenReturn(\"true\");",
" // Option to include the entire batch when restoring is enabled.\n when(this.request.getParameter(\"includeBatch\")).thenReturn(\"true\");",
" // Confirmation button pressed.\n when(this.request.getParameter(\"confirm\")).thenReturn(\"true\");\n",
" when(this.oldcore.getMockRightService().hasAccessLevel(any(), any(), any(), any())).thenReturn(true);",
"\n assertFalse(this.undeleteAction.action(this.oldcore.getXWikiContext()));",
" verify(this.requestFactory).createRestoreRequest(batchId);\n verify(jobExecutor).execute(RefactoringJobs.RESTORE, jobRequest);\n verify(job).join();\n }",
" /**\n * When trying to restore, rights are checked on the current deleted document, regardless if single or batch\n * restore.\n */\n @Test\n void notAllowedToRestoreSinglePage() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);",
" when(this.oldcore.getMockRightService().hasAccessLevel(any(), any(), any(), any())).thenReturn(false);",
" assertTrue(this.undeleteAction.action(this.oldcore.getXWikiContext()));\n // Render the \"accessdenied\" template.\n assertEquals(\"accessdenied\", undeleteAction.render(this.oldcore.getXWikiContext()));",
" // Just make sure we don`t go any further.\n verify(this.requestFactory, never()).createRestoreRequest(Arrays.asList(ID));\n }",
" /**\n * When trying to restore, rights are checked on the current deleted document, regardless if single or batch\n * restore.\n */\n @Test\n void notAllowedToRestoreBatch() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);",
" String batchId = \"abc123\";",
" when(this.deletedDocument.getBatchId()).thenReturn(batchId);",
" // Go through the screen showing the option to include the batch and displaying its contents.\n when(this.request.getParameter(\"showBatch\")).thenReturn(\"true\");",
" // Option to include the entire batch when restoring is enabled.\n when(this.request.getParameter(\"includeBatch\")).thenReturn(\"true\");",
" // Confirmation button pressed.\n when(this.request.getParameter(\"confirm\")).thenReturn(\"true\");",
" // No rights to restore the page when checking from the Action. The job will check individual rights.\n when(this.oldcore.getMockRightService().hasAccessLevel(any(), any(), any(), any())).thenReturn(false);",
" assertTrue(this.undeleteAction.action(this.oldcore.getXWikiContext()));\n // Render the \"accessdenied\" template.\n assertEquals(\"accessdenied\", undeleteAction.render(this.oldcore.getXWikiContext()));",
" // Just make sure we don`t go any further.\n verify(this.requestFactory, never()).createRestoreRequest(batchId);\n }\n}"
] |
[
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\npackage com.xpn.xwiki.web;",
"import java.util.Arrays;\nimport java.util.List;\nimport java.util.Locale;",
"import org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.mockito.Mock;\nimport org.xwiki.csrf.CSRFToken;\nimport org.xwiki.job.Job;\nimport org.xwiki.job.JobExecutor;\nimport org.xwiki.model.reference.DocumentReference;\nimport org.xwiki.refactoring.job.RefactoringJobs;\nimport org.xwiki.refactoring.job.RestoreRequest;\nimport org.xwiki.refactoring.script.RefactoringScriptService;\nimport org.xwiki.refactoring.script.RequestFactory;\nimport org.xwiki.script.service.ScriptService;\nimport org.xwiki.security.authorization.Right;\nimport org.xwiki.test.junit5.mockito.InjectComponentManager;\nimport org.xwiki.test.junit5.mockito.MockComponent;\nimport org.xwiki.test.mockito.MockitoComponentManager;",
"import com.xpn.xwiki.XWikiContext;\nimport com.xpn.xwiki.doc.XWikiDeletedDocument;\nimport com.xpn.xwiki.doc.XWikiDocument;",
"import com.xpn.xwiki.store.XWikiHibernateRecycleBinStore;",
"import com.xpn.xwiki.test.MockitoOldcore;\nimport com.xpn.xwiki.test.junit5.mockito.InjectMockitoOldcore;\nimport com.xpn.xwiki.test.junit5.mockito.OldcoreTest;\nimport com.xpn.xwiki.test.reference.ReferenceComponentList;",
"import static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertFalse;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\nimport static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.ArgumentMatchers.anyLong;\nimport static org.mockito.ArgumentMatchers.anyString;\nimport static org.mockito.Mockito.doReturn;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.never;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;",
"/**\n * Unit tests for {@link UndeleteAction}.\n *\n * @version $Id$\n */\n@OldcoreTest\n@ReferenceComponentList\nclass UndeleteActionTest\n{\n private static final DocumentReference DELETED_REFERENCE =\n new DocumentReference(\"xwiki\", \"Main\", \"DeletedDocument\");",
" private static final long ID = 13;",
" @MockComponent\n private RequestFactory requestFactory;",
" @MockComponent\n private CSRFToken csrfToken;",
" @Mock\n private RefactoringScriptService refactoringScriptService;",
" @MockComponent\n private JobExecutor jobExecutor;",
" @InjectMockitoOldcore\n private MockitoOldcore oldcore;",
" @InjectComponentManager\n private MockitoComponentManager componentManager;",
" @Mock\n private XWikiRequest request;",
" @Mock\n private Job job;",
" @Mock\n private RestoreRequest jobRequest;",
" @Mock\n private XWikiDeletedDocument deletedDocument;\n",
" @Mock\n private XWikiHibernateRecycleBinStore recycleBinStore;\n",
" /**\n * The object being tested.\n */\n private UndeleteAction undeleteAction = new UndeleteAction();",
" @BeforeEach\n void beforeEach() throws Exception\n {\n this.oldcore.getXWikiContext().setRequest(this.request);",
" this.oldcore.getSpyXWiki().setRecycleBinStore(this.recycleBinStore);",
" XWikiDocument contextDocument = mock(XWikiDocument.class);\n when(contextDocument.getDocumentReference()).thenReturn(DELETED_REFERENCE);\n this.oldcore.getXWikiContext().setDoc(contextDocument);",
" when(this.jobExecutor.execute(anyString(), any())).thenReturn(this.job);",
" this.componentManager.registerComponent(ScriptService.class, \"refactoring\", this.refactoringScriptService);\n when(this.refactoringScriptService.getRequestFactory()).thenReturn(this.requestFactory);\n when(this.requestFactory.createRestoreRequest(any(List.class))).thenReturn(this.jobRequest);\n when(this.requestFactory.createRestoreRequest(anyString())).thenReturn(this.jobRequest);",
" when(this.request.getParameter(\"id\")).thenReturn(String.valueOf(ID));",
" when(this.deletedDocument.getLocale()).thenReturn(Locale.ROOT);\n when(deletedDocument.getLocale()).thenReturn(Locale.ROOT);\n when(deletedDocument.getId()).thenReturn(ID);\n when(deletedDocument.getDocumentReference()).thenReturn(DELETED_REFERENCE);\n doReturn(this.deletedDocument).when(this.oldcore.getSpyXWiki()).getDeletedDocument(anyLong(),\n any(XWikiContext.class));\n }",
" /**\n * Launches a RestoreJob with the current deleted document ID.\n */\n @Test\n void restoreSingleDocument() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);\n",
" when(this.recycleBinStore.hasAccess(any(), any(), any()))\n .thenReturn(true);",
" assertFalse(this.undeleteAction.action(this.oldcore.getXWikiContext()));",
" verify(this.requestFactory).createRestoreRequest(Arrays.asList(ID));\n verify(jobExecutor).execute(RefactoringJobs.RESTORE, jobRequest);\n verify(job).join();\n }",
" @Test\n void restoreSingleDocumentWhenDeleter() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);\n",
" when(this.recycleBinStore.hasAccess(any(), any(), any()))",
" .thenReturn(true);",
" assertFalse(this.undeleteAction.action(this.oldcore.getXWikiContext()));",
" verify(this.requestFactory).createRestoreRequest(Arrays.asList(ID));\n verify(jobExecutor).execute(RefactoringJobs.RESTORE, jobRequest);\n verify(job).join();\n }",
" @Test\n void missingCSRFToken() throws Exception\n {\n // Invalid CSRF token.\n when(this.csrfToken.isTokenValid(null)).thenReturn(false);",
" assertFalse(this.undeleteAction.action(this.oldcore.getXWikiContext()));",
" // Verify that the resubmission URL was retrieved to be used in the redirect.\n verify(this.csrfToken).getResubmissionURL();\n }",
" /**\n * When the recycle bin is disabled or when the deleted document ID is invalid, the document should not be restored.\n */\n @Test\n void recycleBinDisabledOrInvalidId() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);",
" // null is returned when the ID is invalid or the Recycle Bin is disabled.\n doReturn(null).when(this.oldcore.getSpyXWiki()).getDeletedDocument(anyLong(), any(XWikiContext.class));",
" assertFalse(this.undeleteAction.action(this.oldcore.getXWikiContext()));",
" // Verify that we never get this far.\n verify(this.requestFactory, never()).createRestoreRequest(Arrays.asList(ID));\n }",
" /**\n * Show the \"restore\" UI with the option to include the batch when restoring and to see the contents of the batch of\n * the current deleted document.\n */\n @Test\n void showBatch() throws Exception\n {\n when(this.request.getParameter(\"showBatch\")).thenReturn(\"true\");\n",
" when(this.recycleBinStore.hasAccess(any(), any(), any()))\n .thenReturn(true);",
" assertTrue(this.undeleteAction.action(this.oldcore.getXWikiContext()));\n // Render the \"restore\" template.\n assertEquals(\"restore\", undeleteAction.render(this.oldcore.getXWikiContext()));",
" // Just make sure that we stop to the display, since the \"confirm=true\" parameter was not passed.\n verify(this.requestFactory, never()).createRestoreRequest(Arrays.asList(ID));\n }",
" /**\n * Launches a RestoreJob with the batchId of the current deleted document.\n */\n @Test\n void restoreBatch() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);",
" String batchId = \"abc123\";",
" when(deletedDocument.getBatchId()).thenReturn(batchId);",
" // Go through the screen showing the option to include the batch and displaying its contents.\n when(this.request.getParameter(\"showBatch\")).thenReturn(\"true\");",
" // Option to include the entire batch when restoring is enabled.\n when(this.request.getParameter(\"includeBatch\")).thenReturn(\"true\");",
" // Confirmation button pressed.\n when(this.request.getParameter(\"confirm\")).thenReturn(\"true\");\n",
" when(this.recycleBinStore.hasAccess(any(), any(), any()))\n .thenReturn(true);",
"\n assertFalse(this.undeleteAction.action(this.oldcore.getXWikiContext()));",
" verify(this.requestFactory).createRestoreRequest(batchId);\n verify(jobExecutor).execute(RefactoringJobs.RESTORE, jobRequest);\n verify(job).join();\n }",
" /**\n * When trying to restore, rights are checked on the current deleted document, regardless if single or batch\n * restore.\n */\n @Test\n void notAllowedToRestoreSinglePage() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);",
" when(this.oldcore.getMockRightService().hasAccessLevel(any(), any(), any(), any())).thenReturn(false);",
" assertTrue(this.undeleteAction.action(this.oldcore.getXWikiContext()));\n // Render the \"accessdenied\" template.\n assertEquals(\"accessdenied\", undeleteAction.render(this.oldcore.getXWikiContext()));",
" // Just make sure we don`t go any further.\n verify(this.requestFactory, never()).createRestoreRequest(Arrays.asList(ID));\n }",
" /**\n * When trying to restore, rights are checked on the current deleted document, regardless if single or batch\n * restore.\n */\n @Test\n void notAllowedToRestoreBatch() throws Exception\n {\n when(this.csrfToken.isTokenValid(null)).thenReturn(true);",
" String batchId = \"abc123\";",
" when(this.deletedDocument.getBatchId()).thenReturn(batchId);",
" // Go through the screen showing the option to include the batch and displaying its contents.\n when(this.request.getParameter(\"showBatch\")).thenReturn(\"true\");",
" // Option to include the entire batch when restoring is enabled.\n when(this.request.getParameter(\"includeBatch\")).thenReturn(\"true\");",
" // Confirmation button pressed.\n when(this.request.getParameter(\"confirm\")).thenReturn(\"true\");",
" // No rights to restore the page when checking from the Action. The job will check individual rights.\n when(this.oldcore.getMockRightService().hasAccessLevel(any(), any(), any(), any())).thenReturn(false);",
" assertTrue(this.undeleteAction.action(this.oldcore.getXWikiContext()));\n // Render the \"accessdenied\" template.\n assertEquals(\"accessdenied\", undeleteAction.render(this.oldcore.getXWikiContext()));",
" // Just make sure we don`t go any further.\n verify(this.requestFactory, never()).createRestoreRequest(batchId);\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"## ---------------------------------------------------------------------------\n## See the NOTICE file distributed with this work for additional\n## information regarding copyright ownership.\n##\n## This is free software; you can redistribute it and/or modify it\n## under the terms of the GNU Lesser General Public License as\n## published by the Free Software Foundation; either version 2.1 of\n## the License, or (at your option) any later version.\n##\n## This software is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n## Lesser General Public License for more details.\n##\n## You should have received a copy of the GNU Lesser General Public\n## License along with this software; if not, write to the Free\n## Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n## 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n## ---------------------------------------------------------------------------\n### Show list of deleted documents\n#set($dds = $xwiki.getDeletedDocuments($tdoc.fullName, $tdoc.locale))\n#displayDeletedDocuments($dds, 'docs')",
"#if ($doc.documentReference.name == 'WebHome')\n ## Also display the list of terminal documents sharing the same location.\n ## eg. If the current document is: \"A.B.WebHome\", we should also display any deleted terminal page called \"A.B\".\n ## This is important because when the user delete a terminal document and go back to the location, she should see\n ## the page she have just deleted, and not an empty page because A.B.WebHome has never existed...\n #set($dds = $xwiki.getDeletedDocuments($tdoc.space, $tdoc.locale))\n #displayDeletedDocuments($dds, 'terminal-docs', 'core.recyclebin.showListTerminalPagesMsg')\n#end",
"#*\n * Display the given list of deleted documents\n * @param $list the list to display\n * @param $className the name of the css class to apply to the list\n * @param $message (optional) the translation key for the message which introduce the list\n *#\n#macro (displayDeletedDocuments $list $className $message)\n #if (!$message)\n #set ($message = 'core.recyclebin.showlistmsg')\n #end \n #if($list && $list.size() > 0)\n #set ($canDelete = $list[0].canDelete())\n #set ($canRestore = $list[0].canUndelete())",
"",
" <hr />\n <div class=\"centered $!className\">\n <p class=\"recyclebin-message\">$escapetool.xml($services.localization.render($message))</p>\n <table class=\"centered\">\n <thead>\n <tr>\n <th>$escapetool.xml($services.localization.render('core.recyclebin.deleter'))</td>\n <th>$escapetool.xml($services.localization.render('core.recyclebin.deleteDate'))</td>\n #if ($canRestore)\n <th>$escapetool.xml($services.localization.render('core.recyclebin.batchId'))</td>\n #end\n <th colspan=\"2\">$escapetool.xml($services.localization.render('core.recyclebin.actions'))</th>\n </tr>\n </thead>\n <tbody>\n #foreach($dd in $list)\n <tr>\n <td>$xwiki.getUserName($dd.getDeleter())</td>\n <td>",
"",
" <a class=\"link-view\" href=\"$doc.getURL('view', $escapetool.url({'rev' : \"deleted:${dd.getId()}\"}))\">\n $xwiki.formatDate($dd.getDate())\n </a>",
"",
" </td>\n #if ($canRestore)\n <td><a href=\"$xwiki.getURL($dd.fullName, 'undelete', \"id=${dd.id}&showBatch=true\")\">$!{dd.batchId}</a></td>\n #end\n <td>\n #if($canRestore)\n <a href=\"$xwiki.getURL($dd.getFullName(), 'undelete', \"form_token=$!{services.csrf.getToken()}&id=$dd.getId()\")\" class=\"action-restore\">\n $escapetool.xml($services.localization.render('core.recyclebin.restore'))\n </a>\n #end\n </td>\n <td>\n #if($canDelete)\n <a href=\"$xwiki.getURL($dd.getFullName(), 'delete', \"form_token=$!{services.csrf.getToken()}&id=$dd.getId()\")\"\n onclick=\"if (confirm('$escapetool.javascript($services.localization.render('core.recyclebin.completelyDeleteConfirm'))')) {this.href += '&confirm=1'; return true;} return false;\" class=\"action-delete\">\n $escapetool.xml($services.localization.render('core.recyclebin.delete'))\n </a>\n #end\n </td>\n </tr>\n #end\n </tbody>\n </table>\n </div>\n #end\n#end"
] |
[
1,
1,
1,
0,
1,
0,
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"## ---------------------------------------------------------------------------\n## See the NOTICE file distributed with this work for additional\n## information regarding copyright ownership.\n##\n## This is free software; you can redistribute it and/or modify it\n## under the terms of the GNU Lesser General Public License as\n## published by the Free Software Foundation; either version 2.1 of\n## the License, or (at your option) any later version.\n##\n## This software is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n## Lesser General Public License for more details.\n##\n## You should have received a copy of the GNU Lesser General Public\n## License along with this software; if not, write to the Free\n## Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n## 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n## ---------------------------------------------------------------------------\n### Show list of deleted documents\n#set($dds = $xwiki.getDeletedDocuments($tdoc.fullName, $tdoc.locale))\n#displayDeletedDocuments($dds, 'docs')",
"#if ($doc.documentReference.name == 'WebHome')\n ## Also display the list of terminal documents sharing the same location.\n ## eg. If the current document is: \"A.B.WebHome\", we should also display any deleted terminal page called \"A.B\".\n ## This is important because when the user delete a terminal document and go back to the location, she should see\n ## the page she have just deleted, and not an empty page because A.B.WebHome has never existed...\n #set($dds = $xwiki.getDeletedDocuments($tdoc.space, $tdoc.locale))\n #displayDeletedDocuments($dds, 'terminal-docs', 'core.recyclebin.showListTerminalPagesMsg')\n#end",
"#*\n * Display the given list of deleted documents\n * @param $list the list to display\n * @param $className the name of the css class to apply to the list\n * @param $message (optional) the translation key for the message which introduce the list\n *#\n#macro (displayDeletedDocuments $list $className $message)\n #if (!$message)\n #set ($message = 'core.recyclebin.showlistmsg')\n #end \n #if($list && $list.size() > 0)\n #set ($canDelete = $list[0].canDelete())\n #set ($canRestore = $list[0].canUndelete())",
" #set ($canView = $list[0].canView())",
" <hr />\n <div class=\"centered $!className\">\n <p class=\"recyclebin-message\">$escapetool.xml($services.localization.render($message))</p>\n <table class=\"centered\">\n <thead>\n <tr>\n <th>$escapetool.xml($services.localization.render('core.recyclebin.deleter'))</td>\n <th>$escapetool.xml($services.localization.render('core.recyclebin.deleteDate'))</td>\n #if ($canRestore)\n <th>$escapetool.xml($services.localization.render('core.recyclebin.batchId'))</td>\n #end\n <th colspan=\"2\">$escapetool.xml($services.localization.render('core.recyclebin.actions'))</th>\n </tr>\n </thead>\n <tbody>\n #foreach($dd in $list)\n <tr>\n <td>$xwiki.getUserName($dd.getDeleter())</td>\n <td>",
" #if ($canView)",
" <a class=\"link-view\" href=\"$doc.getURL('view', $escapetool.url({'rev' : \"deleted:${dd.getId()}\"}))\">\n $xwiki.formatDate($dd.getDate())\n </a>",
" #else\n $xwiki.formatDate($dd.getDate())\n #end",
" </td>\n #if ($canRestore)\n <td><a href=\"$xwiki.getURL($dd.fullName, 'undelete', \"id=${dd.id}&showBatch=true\")\">$!{dd.batchId}</a></td>\n #end\n <td>\n #if($canRestore)\n <a href=\"$xwiki.getURL($dd.getFullName(), 'undelete', \"form_token=$!{services.csrf.getToken()}&id=$dd.getId()\")\" class=\"action-restore\">\n $escapetool.xml($services.localization.render('core.recyclebin.restore'))\n </a>\n #end\n </td>\n <td>\n #if($canDelete)\n <a href=\"$xwiki.getURL($dd.getFullName(), 'delete', \"form_token=$!{services.csrf.getToken()}&id=$dd.getId()\")\"\n onclick=\"if (confirm('$escapetool.javascript($services.localization.render('core.recyclebin.completelyDeleteConfirm'))')) {this.href += '&confirm=1'; return true;} return false;\" class=\"action-delete\">\n $escapetool.xml($services.localization.render('core.recyclebin.delete'))\n </a>\n #end\n </td>\n </tr>\n #end\n </tbody>\n </table>\n </div>\n #end\n#end"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [153, 58, 396, 90, 71, 432, 234, 914, 240, 67], "buggy_code_start_loc": [25, 23, 26, 26, 28, 24, 24, 84, 45, 45], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/api/DeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/DocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/doc/XWikiDeletedDocument.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DefaultDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/doc/DeletedDocumentRevisionProvider.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiHibernateRecycleBinStore.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/XWikiRecycleBinStoreInterface.java", "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiAction.java", "xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/UndeleteActionTest.java", "xwiki-platform-core/xwiki-platform-web/xwiki-platform-web-templates/src/main/resources/templates/recyclebinlist.vm"], "fixing_code_end_loc": [184, 85, 408, 114, 86, 474, 274, 945, 245, 73], "fixing_code_start_loc": [24, 24, 27, 27, 29, 25, 25, 85, 46, 46], "message": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB7E83A5-F68B-487F-B235-9AA7BC32B4D7", "versionEndExcluding": "13.10.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.1", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "FC782E27-0FE5-48CE-B1E6-896F47ACB5BD", "versionEndExcluding": "14.4.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "569EE28C-5C86-467F-A153-DD4B9BF0053D", "versionEndExcluding": "14.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.5", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Commons are technical libraries common to several other top level XWiki projects. Rights added to a document are not taken into account for viewing it once it's deleted. Note that this vulnerability only impact deleted documents that where containing view rights: the view rights provided on a space of a deleted document are properly checked. The problem has been patched in XWiki 14.10 by checking the rights of current user: only admin and deleter of the document are allowed to view it."}], "evaluatorComment": null, "id": "CVE-2023-29208", "lastModified": "2023-04-25T18:47:18.827", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-04-15T16:15:07.380", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-4f8g-fq6x-jqrr"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking"], "url": "https://jira.xwiki.org/browse/XWIKI-16285"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/d9e947559077e947315bf700c5703dfc7dd8a8d7"}, "type": "CWE-668"}
| 253
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"# frozen_string_literal: true",
"class SessionsController < Devise::SessionsController\n prepend_before_action :check_recaptcha, only: [:create]\n before_action :set_recaptcha, only: [:new]",
"",
"\n def new\n super\n end",
" def create\n super\n set_user_locale if user_signed_in?\n end",
" def destroy",
" current_user.invalidate_all_sessions!",
" super\n end",
" private",
" def set_user_locale\n current_user.update(locale: cookies[:locale]) unless default_locale?\n end",
" def default_locale?\n cookies[:locale].eql?(I18n.default_locale)\n end",
" def check_recaptcha\n if recaptcha_required_for_user? && !verify_recaptcha\n self.resource = resource_class.new sign_in_params\n redirect_to new_session_path(resource_name, recaptcha: true)\n else\n cookies.delete(:login_recaptcha)\n end\n end",
" def set_recaptcha\n return unless show_recaptcha?",
" @display_recaptcha = true\n cookies.permanent[:login_recaptcha] = true\n end",
" def show_recaptcha?\n RecaptchaService.recaptcha_configured? &&\n (cookies[:login_recaptcha] ||\n params[:recaptcha] ||\n recaptcha_required_for_user?)\n end",
" def recaptcha_required_for_user?\n user = User.find_by(email: sign_in_params[:email])\n return false if user.nil?",
" RecaptchaService.new(user).recaptcha_required_for_login?\n end",
"",
"end"
] |
[
1,
1,
0,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [59], "buggy_code_start_loc": [5], "filenames": ["app/controllers/sessions_controller.rb"], "fixing_code_end_loc": [64], "fixing_code_start_loc": [6], "message": "In Ifme, versions 1.0.0 to v.7.33.2 don\u2019t properly invalidate a user\u2019s session even after the user initiated logout. It makes it possible for an attacker to reuse the admin cookies either via local/network access or by other hypothetical attacks.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:if-me:ifme:*:*:*:*:*:*:*:*", "matchCriteriaId": "6E1D784A-C106-43D7-9302-4A4654BE9E7D", "versionEndExcluding": null, "versionEndIncluding": "7.33.2", "versionStartExcluding": null, "versionStartIncluding": "1.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Ifme, versions 1.0.0 to v.7.33.2 don\u2019t properly invalidate a user\u2019s session even after the user initiated logout. It makes it possible for an attacker to reuse the admin cookies either via local/network access or by other hypothetical attacks."}, {"lang": "es", "value": "En Ifme, versiones 1.0.0 a v.7.33.2, no invalidan apropiadamente la sesi\u00f3n de un usuario incluso despu\u00e9s de que \u00e9ste haya iniciado la sesi\u00f3n. Esto hace posible que un atacante pueda reusar las cookies del administrador, ya sea por medio de un acceso local/de red o mediante otros hipot\u00e9ticos ataques"}], "evaluatorComment": null, "id": "CVE-2021-25992", "lastModified": "2022-02-22T21:48:06.750", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "vulnerabilitylab@mend.io", "type": "Primary"}]}, "published": "2022-02-10T10:15:13.973", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ifmeorg/ifme/commit/014f6d3526a594109d4d6607c2f30b1865e37611"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Exploit", "Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25992"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-613"}], "source": "vulnerabilitylab@mend.io", "type": "Primary"}]}, "github_commit_url": "https://github.com/ifmeorg/ifme/commit/014f6d3526a594109d4d6607c2f30b1865e37611"}, "type": "CWE-613"}
| 254
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"# frozen_string_literal: true",
"class SessionsController < Devise::SessionsController\n prepend_before_action :check_recaptcha, only: [:create]\n before_action :set_recaptcha, only: [:new]",
" prepend_before_action :invalidate_all_sessions, only: [:destroy]",
"\n def new\n super\n end",
" def create\n super\n set_user_locale if user_signed_in?\n end",
" def destroy",
"",
" super\n end",
" private",
" def set_user_locale\n current_user.update(locale: cookies[:locale]) unless default_locale?\n end",
" def default_locale?\n cookies[:locale].eql?(I18n.default_locale)\n end",
" def check_recaptcha\n if recaptcha_required_for_user? && !verify_recaptcha\n self.resource = resource_class.new sign_in_params\n redirect_to new_session_path(resource_name, recaptcha: true)\n else\n cookies.delete(:login_recaptcha)\n end\n end",
" def set_recaptcha\n return unless show_recaptcha?",
" @display_recaptcha = true\n cookies.permanent[:login_recaptcha] = true\n end",
" def show_recaptcha?\n RecaptchaService.recaptcha_configured? &&\n (cookies[:login_recaptcha] ||\n params[:recaptcha] ||\n recaptcha_required_for_user?)\n end",
" def recaptcha_required_for_user?\n user = User.find_by(email: sign_in_params[:email])\n return false if user.nil?",
" RecaptchaService.new(user).recaptcha_required_for_login?\n end",
"\n def invalidate_all_sessions\n current_user.invalidate_all_sessions!\n end",
"end"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [59], "buggy_code_start_loc": [5], "filenames": ["app/controllers/sessions_controller.rb"], "fixing_code_end_loc": [64], "fixing_code_start_loc": [6], "message": "In Ifme, versions 1.0.0 to v.7.33.2 don\u2019t properly invalidate a user\u2019s session even after the user initiated logout. It makes it possible for an attacker to reuse the admin cookies either via local/network access or by other hypothetical attacks.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:if-me:ifme:*:*:*:*:*:*:*:*", "matchCriteriaId": "6E1D784A-C106-43D7-9302-4A4654BE9E7D", "versionEndExcluding": null, "versionEndIncluding": "7.33.2", "versionStartExcluding": null, "versionStartIncluding": "1.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Ifme, versions 1.0.0 to v.7.33.2 don\u2019t properly invalidate a user\u2019s session even after the user initiated logout. It makes it possible for an attacker to reuse the admin cookies either via local/network access or by other hypothetical attacks."}, {"lang": "es", "value": "En Ifme, versiones 1.0.0 a v.7.33.2, no invalidan apropiadamente la sesi\u00f3n de un usuario incluso despu\u00e9s de que \u00e9ste haya iniciado la sesi\u00f3n. Esto hace posible que un atacante pueda reusar las cookies del administrador, ya sea por medio de un acceso local/de red o mediante otros hipot\u00e9ticos ataques"}], "evaluatorComment": null, "id": "CVE-2021-25992", "lastModified": "2022-02-22T21:48:06.750", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "vulnerabilitylab@mend.io", "type": "Primary"}]}, "published": "2022-02-10T10:15:13.973", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ifmeorg/ifme/commit/014f6d3526a594109d4d6607c2f30b1865e37611"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Exploit", "Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25992"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-613"}], "source": "vulnerabilitylab@mend.io", "type": "Primary"}]}, "github_commit_url": "https://github.com/ifmeorg/ifme/commit/014f6d3526a594109d4d6607c2f30b1865e37611"}, "type": "CWE-613"}
| 254
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Licensed to Jasig under one or more contributor license\n * agreements. See the NOTICE file distributed with this work\n * for additional information regarding copyright ownership.\n * Jasig licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a\n * copy of the License at:\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on\n * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */",
"using System;\nusing System.Collections.Specialized;\nusing System.Text;\nusing System.Web;",
"namespace DotNetCasClient.Utils\n{\n /// <summary>\n /// An internal class used to generate and modify URLs\n /// as needed for redirection and external communication.\n /// </summary>\n /// <remarks>\n /// See https://wiki.jasig.org/display/CASC/UrlUtil+Methods for additional\n /// information including sample output of each method.\n /// </remarks>\n /// <author>Scott Holodak</author>\n public sealed class UrlUtil\n {\n /// <summary>\n /// Constructs the URL to use for redirection to the CAS server for login\n /// </summary>\n /// <remarks>\n /// The server name is not parsed from the request for security reasons, which\n /// is why the service and server name configuration parameters exist.\n /// </remarks>\n /// <returns>The redirection URL to use</returns>\n public static string ConstructLoginRedirectUrl(bool gateway, bool renew)\n {\n if (gateway && renew)\n {\n throw new ArgumentException(\"Gateway and Renew parameters are mutually exclusive and cannot both be True\");\n }",
" CasAuthentication.Initialize();",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(CasAuthentication.FormsLoginUrl);\n ub.QueryItems.Set(CasAuthentication.TicketValidator.ServiceParameterName, HttpUtility.UrlEncode(ConstructServiceUrl(gateway)));",
" if (renew)\n {\n ub.QueryItems.Add(\"renew\", \"true\");\n }\n else if (gateway)\n {\n ub.QueryItems.Add(\"gateway\", \"true\");\n }",
" string url = ub.Uri.AbsoluteUri;",
" return url;\n }",
" /// <summary>\n /// Constructs a service URL using configured values in the following order:\n /// 1. if not empty, the value configured for Service is used\n /// - otherwise -\n /// 2. the value configured for ServerName is used together with HttpRequest\n /// data\n /// </summary>\n /// <remarks>\n /// The server name is not parsed from the request for security reasons, which\n /// is why the service and server name configuration parameters exist, per Jasig\n /// website.\n /// </remarks>\n /// <returns>the service URL to use, not encoded</returns>\n public static string ConstructServiceUrl(bool gateway)\n {\n CasAuthentication.Initialize();",
" HttpContext context = HttpContext.Current;\n HttpRequest request = context.Request;",
" StringBuilder buffer = new StringBuilder();\n if (!(CasAuthentication.ServerName.StartsWith(\"https://\") || CasAuthentication.ServerName.StartsWith(\"http://\")))\n {\n buffer.Append(request.IsSecureConnection ? \"https://\" : \"http://\");\n }\n buffer.Append(CasAuthentication.ServerName);",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(buffer.ToString());\n ub.Path = request.Url.AbsolutePath;\n ub.QueryItems.Add(request.QueryString);\n ub.QueryItems.Remove(CasAuthentication.TicketValidator.ServiceParameterName);\n ub.QueryItems.Remove(CasAuthentication.TicketValidator.ArtifactParameterName);",
" if (gateway)\n {\n ub.QueryItems.Set(CasAuthentication.GatewayParameterName, \"true\");\n }\n else\n {\n ub.QueryItems.Remove(CasAuthentication.GatewayParameterName);\n }\n return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Constructs a URL used to check the validitiy of a service ticket, with or without a proxy \n /// callback URL, and with or without requiring renewed credentials.\n /// </summary>\n /// <remarks>See CAS Protocol specification, section 2.5</remarks>\n /// <param name=\"serviceTicket\">The service ticket to validate.</param>\n /// <param name=\"renew\">\n /// Whether or not renewed credentials are required. If True, ticket validation\n /// will fail for Single Sign On credentials.\n /// </param>\n /// <param name=\"gateway\">\n /// whether or not to include gatewayResponse=true in the request (client specific).\n /// </param>\n /// <param name=\"customParameters\">custom parameters to add to the validation URL</param>\n /// <returns>The service ticket validation URL to use</returns>\n public static string ConstructValidateUrl(string serviceTicket, bool gateway, bool renew, NameValueCollection customParameters)\n {\n if (gateway && renew)\n {\n throw new ArgumentException(\"Gateway and Renew parameters are mutually exclusive and cannot both be True\");\n }",
" CasAuthentication.Initialize();",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(EnhancedUriBuilder.Combine(CasAuthentication.CasServerUrlPrefix, CasAuthentication.TicketValidator.UrlSuffix));\n ub.QueryItems.Add(CasAuthentication.TicketValidator.ServiceParameterName, HttpUtility.UrlEncode(ConstructServiceUrl(gateway)));",
" ub.QueryItems.Add(CasAuthentication.TicketValidator.ArtifactParameterName, serviceTicket);",
"\n if (renew)\n {\n ub.QueryItems.Set(\"renew\", \"true\");\n }",
" if (customParameters != null)\n {\n for (int i = 0; i < customParameters.Count; i++)\n {\n string key = customParameters.AllKeys[i];\n string value = customParameters[i];",
" ub.QueryItems.Add(key, value);\n }\n }\n return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Constructs a proxy callback URL containing a ProxyCallbackParameter \n /// (proxyResponse by default). This URL is sent to the CAS server during a proxy\n /// ticket request and is then connected to by the CAS server. If the 'CasProxyCallbackUrl' settings is specified,\n /// its value will be used to construct the proxy url. Otherwise, `ServerName` will be used.\n /// If the CAS server cannot successfully connect (generally due to SSL configuration issues), the\n /// CAS server will refuse to send a proxy ticket. \n /// </summary>\n /// <returns>the proxy callback URL to use</returns>\n public static string ConstructProxyCallbackUrl(bool gateway)\n {\n CasAuthentication.Initialize();",
" HttpContext context = HttpContext.Current;\n HttpRequest request = context.Request;",
" EnhancedUriBuilder ub = null;\n if (CasAuthentication.CasProxyCallbackUrl != null && CasAuthentication.CasProxyCallbackUrl.Length > 0)\n {\n ub = new EnhancedUriBuilder(CasAuthentication.CasProxyCallbackUrl);\n }\n else\n {\n ub = new EnhancedUriBuilder(CasAuthentication.ServerName);\n }\n ub.Path = request.Url.AbsolutePath;\n ub.QueryItems.Add(request.QueryString);\n ub.QueryItems.Remove(CasAuthentication.TicketValidator.ArtifactParameterName);",
" if (gateway)\n {\n ub.QueryItems.Set(CasAuthentication.GatewayParameterName, \"true\");\n }\n else\n {\n ub.QueryItems.Remove(CasAuthentication.GatewayParameterName);\n }\n return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Constructs a proxy callback URL containing a ProxyCallbackParameter \n /// (proxyResponse by default). This URL is sent to the CAS server during a proxy\n /// ticket request and is then connected to by the CAS server. If the CAS server\n /// cannot successfully connect (generally due to SSL configuration issues), the\n /// CAS server will refuse to send a proxy ticket. \n /// </summary>\n /// <remarks>\n /// This is a .NET implementation specific method used to eliminate the need for \n /// a special HTTP Handler. Essentially, if the client detects an incoming request\n /// with the ProxyCallbackParameter in the URL (i.e., proxyResponse), that request \n /// is treated specially and behaves as if it were handled by an HTTP Handler. In \n /// other words, this behavior may or may not short circuit the request event \n /// processing and will not allow the underlying page to execute and transmit back to\n /// the client. If your application does coincidentally make use of the key \n /// 'proxyResponse' as a URL parameter, you will need to configure a custom \n /// proxyCallbackParameter value which does not conflict with the URL parameters in\n /// your application.\n /// </remarks>\n /// <returns>the proxy callback URL to use</returns>\n public static string ConstructProxyCallbackUrl()\n {\n CasAuthentication.Initialize();",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(ConstructProxyCallbackUrl(false));\n ub.QueryItems.Set(CasAuthentication.ProxyCallbackParameterName, \"true\");",
" return ub.Uri.AbsoluteUri;\n }\n \n /// <summary>\n /// Constructs a proxy ticket request URL containing both a proxy granting \n /// ticket and a URL Encoded targetServiceUrl. The URL returned will generally only\n /// be executed by the CAS client as a part of a proxy redirection in \n /// CasAuthentication.ProxyRedirect(...) or CasAuthentication.GetProxyTicketIdFor(...)\n /// but may also be used by applications which require low-level access to the proxy\n /// ticket request functionality.\n /// </summary>\n /// <param name=\"proxyGrantingTicketId\">\n /// The proxy granting ticket used to authorize the request for a proxy ticket on the \n /// CAS server\n /// </param>\n /// <param name=\"targetService\">\n /// The target service URL to request a proxy ticket request URL for\n /// </param>\n /// <returns>The URL to use to request a proxy ticket for the targetService specified</returns>\n public static string ConstructProxyTicketRequestUrl(string proxyGrantingTicketId, string targetService)\n {\n CasAuthentication.Initialize();",
" if (String.IsNullOrEmpty(proxyGrantingTicketId))\n {\n throw new ArgumentException(\"For proxy ticket requests, proxyGrantingTicketId cannot be null and must be specified.\");\n }",
" if (String.IsNullOrEmpty(targetService))\n {\n throw new ArgumentException(\"For proxy ticket requests, targetService cannot be null and must be specified.\");\n }",
" // TODO: Make \"proxy\" configurable.\n EnhancedUriBuilder ub = new EnhancedUriBuilder(EnhancedUriBuilder.Combine(CasAuthentication.CasServerUrlPrefix, \"proxy\"));\n ub.QueryItems.Add(\"pgt\", proxyGrantingTicketId);\n ub.QueryItems.Add(\"targetService\", HttpUtility.UrlEncode(targetService));",
" return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Attempts to request a proxy ticket for the targetService specified and\n /// returns a URL appropriate for redirection to the targetService containing\n /// a ticket.\n /// </summary>\n /// <param name=\"targetService\">The target service for proxy authentication</param>\n /// <returns>The URL of the target service with a proxy ticket included</returns>\n public static string GetProxyRedirectUrl(string targetService)\n {\n return GetProxyRedirectUrl(targetService, CasAuthentication.TicketValidator.ArtifactParameterName);\n }",
" /// <summary>\n /// Attempts to request a proxy ticket for the targetService specified and\n /// returns a URL appropriate for redirection to the targetService containing\n /// a ticket.\n /// </summary>\n /// <param name=\"targetService\">The target service for proxy authentication</param>\n /// <param name=\"proxyTicketUrlParameter\">\n /// The name of the ticket URL parameter expected by the target service (ticket by\n /// default)\n /// </param>\n /// <returns>The URL of the target service with a proxy ticket included</returns>\n public static string GetProxyRedirectUrl(string targetService, string proxyTicketUrlParameter)\n {\n CasAuthentication.Initialize();\n \n // Todo: Is ResolveUrl(...) appropriate/necessary? If the URL starts with ~, it shouldn't require proxy authentication\n string resolvedUrl = ResolveUrl(targetService);\n string proxyTicket = CasAuthentication.GetProxyTicketIdFor(resolvedUrl);",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(resolvedUrl);\n ub.QueryItems[proxyTicketUrlParameter] = proxyTicket;",
" return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Constructs the URL to use for redirection to the CAS server for single\n /// signout. The CAS server will invalidate the ticket granting ticket and\n /// redirect back to the current page. The web application must then call\n /// ClearAuthCookie and revoke the ticket from the ServiceTicketManager to sign \n /// the client out.\n /// </summary>\n /// <returns>the redirection URL to use, not encoded</returns>\n public static string ConstructSingleSignOutRedirectUrl()\n {\n CasAuthentication.Initialize();",
" // TODO: Make \"logout\" configurable\n EnhancedUriBuilder ub = new EnhancedUriBuilder(EnhancedUriBuilder.Combine(CasAuthentication.CasServerUrlPrefix, \"logout\"));\n ub.QueryItems.Set(CasAuthentication.TicketValidator.ServiceParameterName, HttpUtility.UrlEncode(ConstructServiceUrl(false)));",
" return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Returns a copy of the URL supplied modified to remove CAS protocol-specific\n /// URL parameters.\n /// </summary>\n /// <param name=\"url\">The URL to remove CAS artifacts from</param>\n /// <returns>The URL supplied without CAS artifacts</returns>\n public static string RemoveCasArtifactsFromUrl(string url)\n {\n CommonUtils.AssertNotNullOrEmpty(url, \"url parameter can not be null or empty.\");",
" CasAuthentication.Initialize();",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(url);\n ub.QueryItems.Remove(CasAuthentication.TicketValidator.ArtifactParameterName);\n ub.QueryItems.Remove(CasAuthentication.TicketValidator.ServiceParameterName);\n ub.QueryItems.Remove(CasAuthentication.GatewayParameterName);\n ub.QueryItems.Remove(CasAuthentication.ProxyCallbackParameterName);\n \n // ++ NETC-28\n Uri uriServerName;\n if (CasAuthentication.ServerName.StartsWith(\"http://\", StringComparison.InvariantCultureIgnoreCase) ||\n CasAuthentication.ServerName.StartsWith(\"https://\", StringComparison.InvariantCultureIgnoreCase))\n {\n uriServerName = new Uri(CasAuthentication.ServerName);\n }\n else\n {\n // .NET URIs require scheme\n uriServerName = new Uri(\"https://\" + CasAuthentication.ServerName);\n }",
" ub.Scheme = uriServerName.Scheme;\n ub.Host = uriServerName.Host;\n ub.Port = uriServerName.Port;",
" return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Resolves a relative ~/Url to a Url that is meaningful to the\n /// client.\n /// <remarks>\n /// Derived from: http://weblogs.asp.net/palermo4/archive/2004/06/18/getting-the-absolute-path-in-asp-net-part-2.aspx\n /// </remarks> \n /// </summary>\n /// <author>J. Michael Palermo IV</author>\n /// <author>Scott Holodak</author>\n /// <param name=\"url\">The Url to resolve</param>\n /// <returns>The fullly resolved Url</returns>\n internal static string ResolveUrl(string url)\n {\n CommonUtils.AssertNotNullOrEmpty(url, \"url parameter can not be null or empty.\");\n if (url[0] != '~') return url;",
" CasAuthentication.Initialize();",
" string applicationPath = HttpContext.Current.Request.ApplicationPath;\n if (url.Length == 1) return applicationPath;",
" // assume url looks like ~somePage \n int indexOfUrl = 1;",
" // determine the middle character \n string midPath = ((applicationPath ?? string.Empty).Length > 1) ? \"/\" : string.Empty;",
" // if url looks like ~/ or ~\\ change the indexOfUrl to 2 \n if (url[1] == '/' || url[1] == '\\\\') indexOfUrl = 2;",
" return applicationPath + midPath + url.Substring(indexOfUrl);\n } \n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [143], "buggy_code_start_loc": [142], "filenames": ["DotNetCasClient/Utils/UrlUtil.cs"], "fixing_code_end_loc": [143], "fixing_code_start_loc": [142], "message": "A URL parameter injection vulnerability was found in the back-channel ticket validation step of the CAS protocol in Jasig Java CAS Client before 3.3.2, .NET CAS Client before 1.0.2, and phpCAS before 1.3.3 that allow remote attackers to inject arbitrary web script or HTML via the (1) service parameter to validation/AbstractUrlBasedTicketValidator.java or (2) pgtUrl parameter to validation/Cas20ServiceTicketValidator.java.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apereo:.net_cas_client:*:*:*:*:*:*:*:*", "matchCriteriaId": "D0D3881B-F7F5-4E0F-B76F-EFA42ECB0E75", "versionEndExcluding": "1.0.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apereo:java_cas_client:*:*:*:*:*:*:*:*", "matchCriteriaId": "3A6BA56C-70FF-46A7-8648-E412BEA54EB9", "versionEndExcluding": "3.3.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apereo:phpcas:*:*:*:*:*:*:*:*", "matchCriteriaId": "949AB748-0980-4F16-8031-42A413597117", "versionEndExcluding": "1.3.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:20:*:*:*:*:*:*:*", "matchCriteriaId": "FF47C9F0-D8DA-4B55-89EB-9B2C9383ADB9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A URL parameter injection vulnerability was found in the back-channel ticket validation step of the CAS protocol in Jasig Java CAS Client before 3.3.2, .NET CAS Client before 1.0.2, and phpCAS before 1.3.3 that allow remote attackers to inject arbitrary web script or HTML via the (1) service parameter to validation/AbstractUrlBasedTicketValidator.java or (2) pgtUrl parameter to validation/Cas20ServiceTicketValidator.java."}, {"lang": "es", "value": "Se detect\u00f3 una vulnerabilidad de inyecci\u00f3n de par\u00e1metros de URL en el paso de validaci\u00f3n de tickets del canal posterior del protocolo CAS en Jasig Java CAS Client versiones anteriores a 3.3.2, .NET CAS Client versiones anteriores a 1.0.2 y phpCAS versiones anteriores a 1.3.3, que permiten a atacantes remotos inyectar script web o HTML arbitrario por medio del (1) par\u00e1metro service en el archivo validation/AbstractUrlBasedTicketValidator.java o del (2) par\u00e1metro pgtUrl en el archivo validation/Cas20ServiceTicketValidator.java."}], "evaluatorComment": null, "id": "CVE-2014-4172", "lastModified": "2020-02-12T15:18:54.907", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-01-24T19:15:12.010", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2014-August/137182.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=759718"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1131350"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/95673"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Jasig/dotnet-cas-client/commit/f0e030014fb7a39e5f38469f43199dc590fd0e8d"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Jasig/java-cas-client/commit/ae37092100c8eaec610dab6d83e5e05a8ee58814"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/Jasig/phpCAS/blob/master/docs/ChangeLog"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/Jasig/phpCAS/pull/125"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://issues.jasig.org/browse/CASC-228"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2014/dsa-3017.en.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.mail-archive.com/cas-user@lists.jasig.org/msg17338.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Jasig/dotnet-cas-client/commit/f0e030014fb7a39e5f38469f43199dc590fd0e8d"}, "type": "CWE-74"}
| 255
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Licensed to Jasig under one or more contributor license\n * agreements. See the NOTICE file distributed with this work\n * for additional information regarding copyright ownership.\n * Jasig licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a\n * copy of the License at:\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on\n * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */",
"using System;\nusing System.Collections.Specialized;\nusing System.Text;\nusing System.Web;",
"namespace DotNetCasClient.Utils\n{\n /// <summary>\n /// An internal class used to generate and modify URLs\n /// as needed for redirection and external communication.\n /// </summary>\n /// <remarks>\n /// See https://wiki.jasig.org/display/CASC/UrlUtil+Methods for additional\n /// information including sample output of each method.\n /// </remarks>\n /// <author>Scott Holodak</author>\n public sealed class UrlUtil\n {\n /// <summary>\n /// Constructs the URL to use for redirection to the CAS server for login\n /// </summary>\n /// <remarks>\n /// The server name is not parsed from the request for security reasons, which\n /// is why the service and server name configuration parameters exist.\n /// </remarks>\n /// <returns>The redirection URL to use</returns>\n public static string ConstructLoginRedirectUrl(bool gateway, bool renew)\n {\n if (gateway && renew)\n {\n throw new ArgumentException(\"Gateway and Renew parameters are mutually exclusive and cannot both be True\");\n }",
" CasAuthentication.Initialize();",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(CasAuthentication.FormsLoginUrl);\n ub.QueryItems.Set(CasAuthentication.TicketValidator.ServiceParameterName, HttpUtility.UrlEncode(ConstructServiceUrl(gateway)));",
" if (renew)\n {\n ub.QueryItems.Add(\"renew\", \"true\");\n }\n else if (gateway)\n {\n ub.QueryItems.Add(\"gateway\", \"true\");\n }",
" string url = ub.Uri.AbsoluteUri;",
" return url;\n }",
" /// <summary>\n /// Constructs a service URL using configured values in the following order:\n /// 1. if not empty, the value configured for Service is used\n /// - otherwise -\n /// 2. the value configured for ServerName is used together with HttpRequest\n /// data\n /// </summary>\n /// <remarks>\n /// The server name is not parsed from the request for security reasons, which\n /// is why the service and server name configuration parameters exist, per Jasig\n /// website.\n /// </remarks>\n /// <returns>the service URL to use, not encoded</returns>\n public static string ConstructServiceUrl(bool gateway)\n {\n CasAuthentication.Initialize();",
" HttpContext context = HttpContext.Current;\n HttpRequest request = context.Request;",
" StringBuilder buffer = new StringBuilder();\n if (!(CasAuthentication.ServerName.StartsWith(\"https://\") || CasAuthentication.ServerName.StartsWith(\"http://\")))\n {\n buffer.Append(request.IsSecureConnection ? \"https://\" : \"http://\");\n }\n buffer.Append(CasAuthentication.ServerName);",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(buffer.ToString());\n ub.Path = request.Url.AbsolutePath;\n ub.QueryItems.Add(request.QueryString);\n ub.QueryItems.Remove(CasAuthentication.TicketValidator.ServiceParameterName);\n ub.QueryItems.Remove(CasAuthentication.TicketValidator.ArtifactParameterName);",
" if (gateway)\n {\n ub.QueryItems.Set(CasAuthentication.GatewayParameterName, \"true\");\n }\n else\n {\n ub.QueryItems.Remove(CasAuthentication.GatewayParameterName);\n }\n return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Constructs a URL used to check the validitiy of a service ticket, with or without a proxy \n /// callback URL, and with or without requiring renewed credentials.\n /// </summary>\n /// <remarks>See CAS Protocol specification, section 2.5</remarks>\n /// <param name=\"serviceTicket\">The service ticket to validate.</param>\n /// <param name=\"renew\">\n /// Whether or not renewed credentials are required. If True, ticket validation\n /// will fail for Single Sign On credentials.\n /// </param>\n /// <param name=\"gateway\">\n /// whether or not to include gatewayResponse=true in the request (client specific).\n /// </param>\n /// <param name=\"customParameters\">custom parameters to add to the validation URL</param>\n /// <returns>The service ticket validation URL to use</returns>\n public static string ConstructValidateUrl(string serviceTicket, bool gateway, bool renew, NameValueCollection customParameters)\n {\n if (gateway && renew)\n {\n throw new ArgumentException(\"Gateway and Renew parameters are mutually exclusive and cannot both be True\");\n }",
" CasAuthentication.Initialize();",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(EnhancedUriBuilder.Combine(CasAuthentication.CasServerUrlPrefix, CasAuthentication.TicketValidator.UrlSuffix));\n ub.QueryItems.Add(CasAuthentication.TicketValidator.ServiceParameterName, HttpUtility.UrlEncode(ConstructServiceUrl(gateway)));",
" ub.QueryItems.Add(CasAuthentication.TicketValidator.ArtifactParameterName, HttpUtility.UrlEncode(serviceTicket));",
"\n if (renew)\n {\n ub.QueryItems.Set(\"renew\", \"true\");\n }",
" if (customParameters != null)\n {\n for (int i = 0; i < customParameters.Count; i++)\n {\n string key = customParameters.AllKeys[i];\n string value = customParameters[i];",
" ub.QueryItems.Add(key, value);\n }\n }\n return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Constructs a proxy callback URL containing a ProxyCallbackParameter \n /// (proxyResponse by default). This URL is sent to the CAS server during a proxy\n /// ticket request and is then connected to by the CAS server. If the 'CasProxyCallbackUrl' settings is specified,\n /// its value will be used to construct the proxy url. Otherwise, `ServerName` will be used.\n /// If the CAS server cannot successfully connect (generally due to SSL configuration issues), the\n /// CAS server will refuse to send a proxy ticket. \n /// </summary>\n /// <returns>the proxy callback URL to use</returns>\n public static string ConstructProxyCallbackUrl(bool gateway)\n {\n CasAuthentication.Initialize();",
" HttpContext context = HttpContext.Current;\n HttpRequest request = context.Request;",
" EnhancedUriBuilder ub = null;\n if (CasAuthentication.CasProxyCallbackUrl != null && CasAuthentication.CasProxyCallbackUrl.Length > 0)\n {\n ub = new EnhancedUriBuilder(CasAuthentication.CasProxyCallbackUrl);\n }\n else\n {\n ub = new EnhancedUriBuilder(CasAuthentication.ServerName);\n }\n ub.Path = request.Url.AbsolutePath;\n ub.QueryItems.Add(request.QueryString);\n ub.QueryItems.Remove(CasAuthentication.TicketValidator.ArtifactParameterName);",
" if (gateway)\n {\n ub.QueryItems.Set(CasAuthentication.GatewayParameterName, \"true\");\n }\n else\n {\n ub.QueryItems.Remove(CasAuthentication.GatewayParameterName);\n }\n return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Constructs a proxy callback URL containing a ProxyCallbackParameter \n /// (proxyResponse by default). This URL is sent to the CAS server during a proxy\n /// ticket request and is then connected to by the CAS server. If the CAS server\n /// cannot successfully connect (generally due to SSL configuration issues), the\n /// CAS server will refuse to send a proxy ticket. \n /// </summary>\n /// <remarks>\n /// This is a .NET implementation specific method used to eliminate the need for \n /// a special HTTP Handler. Essentially, if the client detects an incoming request\n /// with the ProxyCallbackParameter in the URL (i.e., proxyResponse), that request \n /// is treated specially and behaves as if it were handled by an HTTP Handler. In \n /// other words, this behavior may or may not short circuit the request event \n /// processing and will not allow the underlying page to execute and transmit back to\n /// the client. If your application does coincidentally make use of the key \n /// 'proxyResponse' as a URL parameter, you will need to configure a custom \n /// proxyCallbackParameter value which does not conflict with the URL parameters in\n /// your application.\n /// </remarks>\n /// <returns>the proxy callback URL to use</returns>\n public static string ConstructProxyCallbackUrl()\n {\n CasAuthentication.Initialize();",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(ConstructProxyCallbackUrl(false));\n ub.QueryItems.Set(CasAuthentication.ProxyCallbackParameterName, \"true\");",
" return ub.Uri.AbsoluteUri;\n }\n \n /// <summary>\n /// Constructs a proxy ticket request URL containing both a proxy granting \n /// ticket and a URL Encoded targetServiceUrl. The URL returned will generally only\n /// be executed by the CAS client as a part of a proxy redirection in \n /// CasAuthentication.ProxyRedirect(...) or CasAuthentication.GetProxyTicketIdFor(...)\n /// but may also be used by applications which require low-level access to the proxy\n /// ticket request functionality.\n /// </summary>\n /// <param name=\"proxyGrantingTicketId\">\n /// The proxy granting ticket used to authorize the request for a proxy ticket on the \n /// CAS server\n /// </param>\n /// <param name=\"targetService\">\n /// The target service URL to request a proxy ticket request URL for\n /// </param>\n /// <returns>The URL to use to request a proxy ticket for the targetService specified</returns>\n public static string ConstructProxyTicketRequestUrl(string proxyGrantingTicketId, string targetService)\n {\n CasAuthentication.Initialize();",
" if (String.IsNullOrEmpty(proxyGrantingTicketId))\n {\n throw new ArgumentException(\"For proxy ticket requests, proxyGrantingTicketId cannot be null and must be specified.\");\n }",
" if (String.IsNullOrEmpty(targetService))\n {\n throw new ArgumentException(\"For proxy ticket requests, targetService cannot be null and must be specified.\");\n }",
" // TODO: Make \"proxy\" configurable.\n EnhancedUriBuilder ub = new EnhancedUriBuilder(EnhancedUriBuilder.Combine(CasAuthentication.CasServerUrlPrefix, \"proxy\"));\n ub.QueryItems.Add(\"pgt\", proxyGrantingTicketId);\n ub.QueryItems.Add(\"targetService\", HttpUtility.UrlEncode(targetService));",
" return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Attempts to request a proxy ticket for the targetService specified and\n /// returns a URL appropriate for redirection to the targetService containing\n /// a ticket.\n /// </summary>\n /// <param name=\"targetService\">The target service for proxy authentication</param>\n /// <returns>The URL of the target service with a proxy ticket included</returns>\n public static string GetProxyRedirectUrl(string targetService)\n {\n return GetProxyRedirectUrl(targetService, CasAuthentication.TicketValidator.ArtifactParameterName);\n }",
" /// <summary>\n /// Attempts to request a proxy ticket for the targetService specified and\n /// returns a URL appropriate for redirection to the targetService containing\n /// a ticket.\n /// </summary>\n /// <param name=\"targetService\">The target service for proxy authentication</param>\n /// <param name=\"proxyTicketUrlParameter\">\n /// The name of the ticket URL parameter expected by the target service (ticket by\n /// default)\n /// </param>\n /// <returns>The URL of the target service with a proxy ticket included</returns>\n public static string GetProxyRedirectUrl(string targetService, string proxyTicketUrlParameter)\n {\n CasAuthentication.Initialize();\n \n // Todo: Is ResolveUrl(...) appropriate/necessary? If the URL starts with ~, it shouldn't require proxy authentication\n string resolvedUrl = ResolveUrl(targetService);\n string proxyTicket = CasAuthentication.GetProxyTicketIdFor(resolvedUrl);",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(resolvedUrl);\n ub.QueryItems[proxyTicketUrlParameter] = proxyTicket;",
" return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Constructs the URL to use for redirection to the CAS server for single\n /// signout. The CAS server will invalidate the ticket granting ticket and\n /// redirect back to the current page. The web application must then call\n /// ClearAuthCookie and revoke the ticket from the ServiceTicketManager to sign \n /// the client out.\n /// </summary>\n /// <returns>the redirection URL to use, not encoded</returns>\n public static string ConstructSingleSignOutRedirectUrl()\n {\n CasAuthentication.Initialize();",
" // TODO: Make \"logout\" configurable\n EnhancedUriBuilder ub = new EnhancedUriBuilder(EnhancedUriBuilder.Combine(CasAuthentication.CasServerUrlPrefix, \"logout\"));\n ub.QueryItems.Set(CasAuthentication.TicketValidator.ServiceParameterName, HttpUtility.UrlEncode(ConstructServiceUrl(false)));",
" return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Returns a copy of the URL supplied modified to remove CAS protocol-specific\n /// URL parameters.\n /// </summary>\n /// <param name=\"url\">The URL to remove CAS artifacts from</param>\n /// <returns>The URL supplied without CAS artifacts</returns>\n public static string RemoveCasArtifactsFromUrl(string url)\n {\n CommonUtils.AssertNotNullOrEmpty(url, \"url parameter can not be null or empty.\");",
" CasAuthentication.Initialize();",
" EnhancedUriBuilder ub = new EnhancedUriBuilder(url);\n ub.QueryItems.Remove(CasAuthentication.TicketValidator.ArtifactParameterName);\n ub.QueryItems.Remove(CasAuthentication.TicketValidator.ServiceParameterName);\n ub.QueryItems.Remove(CasAuthentication.GatewayParameterName);\n ub.QueryItems.Remove(CasAuthentication.ProxyCallbackParameterName);\n \n // ++ NETC-28\n Uri uriServerName;\n if (CasAuthentication.ServerName.StartsWith(\"http://\", StringComparison.InvariantCultureIgnoreCase) ||\n CasAuthentication.ServerName.StartsWith(\"https://\", StringComparison.InvariantCultureIgnoreCase))\n {\n uriServerName = new Uri(CasAuthentication.ServerName);\n }\n else\n {\n // .NET URIs require scheme\n uriServerName = new Uri(\"https://\" + CasAuthentication.ServerName);\n }",
" ub.Scheme = uriServerName.Scheme;\n ub.Host = uriServerName.Host;\n ub.Port = uriServerName.Port;",
" return ub.Uri.AbsoluteUri;\n }",
" /// <summary>\n /// Resolves a relative ~/Url to a Url that is meaningful to the\n /// client.\n /// <remarks>\n /// Derived from: http://weblogs.asp.net/palermo4/archive/2004/06/18/getting-the-absolute-path-in-asp-net-part-2.aspx\n /// </remarks> \n /// </summary>\n /// <author>J. Michael Palermo IV</author>\n /// <author>Scott Holodak</author>\n /// <param name=\"url\">The Url to resolve</param>\n /// <returns>The fullly resolved Url</returns>\n internal static string ResolveUrl(string url)\n {\n CommonUtils.AssertNotNullOrEmpty(url, \"url parameter can not be null or empty.\");\n if (url[0] != '~') return url;",
" CasAuthentication.Initialize();",
" string applicationPath = HttpContext.Current.Request.ApplicationPath;\n if (url.Length == 1) return applicationPath;",
" // assume url looks like ~somePage \n int indexOfUrl = 1;",
" // determine the middle character \n string midPath = ((applicationPath ?? string.Empty).Length > 1) ? \"/\" : string.Empty;",
" // if url looks like ~/ or ~\\ change the indexOfUrl to 2 \n if (url[1] == '/' || url[1] == '\\\\') indexOfUrl = 2;",
" return applicationPath + midPath + url.Substring(indexOfUrl);\n } \n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [143], "buggy_code_start_loc": [142], "filenames": ["DotNetCasClient/Utils/UrlUtil.cs"], "fixing_code_end_loc": [143], "fixing_code_start_loc": [142], "message": "A URL parameter injection vulnerability was found in the back-channel ticket validation step of the CAS protocol in Jasig Java CAS Client before 3.3.2, .NET CAS Client before 1.0.2, and phpCAS before 1.3.3 that allow remote attackers to inject arbitrary web script or HTML via the (1) service parameter to validation/AbstractUrlBasedTicketValidator.java or (2) pgtUrl parameter to validation/Cas20ServiceTicketValidator.java.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apereo:.net_cas_client:*:*:*:*:*:*:*:*", "matchCriteriaId": "D0D3881B-F7F5-4E0F-B76F-EFA42ECB0E75", "versionEndExcluding": "1.0.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apereo:java_cas_client:*:*:*:*:*:*:*:*", "matchCriteriaId": "3A6BA56C-70FF-46A7-8648-E412BEA54EB9", "versionEndExcluding": "3.3.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apereo:phpcas:*:*:*:*:*:*:*:*", "matchCriteriaId": "949AB748-0980-4F16-8031-42A413597117", "versionEndExcluding": "1.3.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:20:*:*:*:*:*:*:*", "matchCriteriaId": "FF47C9F0-D8DA-4B55-89EB-9B2C9383ADB9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A URL parameter injection vulnerability was found in the back-channel ticket validation step of the CAS protocol in Jasig Java CAS Client before 3.3.2, .NET CAS Client before 1.0.2, and phpCAS before 1.3.3 that allow remote attackers to inject arbitrary web script or HTML via the (1) service parameter to validation/AbstractUrlBasedTicketValidator.java or (2) pgtUrl parameter to validation/Cas20ServiceTicketValidator.java."}, {"lang": "es", "value": "Se detect\u00f3 una vulnerabilidad de inyecci\u00f3n de par\u00e1metros de URL en el paso de validaci\u00f3n de tickets del canal posterior del protocolo CAS en Jasig Java CAS Client versiones anteriores a 3.3.2, .NET CAS Client versiones anteriores a 1.0.2 y phpCAS versiones anteriores a 1.3.3, que permiten a atacantes remotos inyectar script web o HTML arbitrario por medio del (1) par\u00e1metro service en el archivo validation/AbstractUrlBasedTicketValidator.java o del (2) par\u00e1metro pgtUrl en el archivo validation/Cas20ServiceTicketValidator.java."}], "evaluatorComment": null, "id": "CVE-2014-4172", "lastModified": "2020-02-12T15:18:54.907", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-01-24T19:15:12.010", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2014-August/137182.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=759718"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1131350"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/95673"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Jasig/dotnet-cas-client/commit/f0e030014fb7a39e5f38469f43199dc590fd0e8d"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Jasig/java-cas-client/commit/ae37092100c8eaec610dab6d83e5e05a8ee58814"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/Jasig/phpCAS/blob/master/docs/ChangeLog"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/Jasig/phpCAS/pull/125"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://issues.jasig.org/browse/CASC-228"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2014/dsa-3017.en.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.mail-archive.com/cas-user@lists.jasig.org/msg17338.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Jasig/dotnet-cas-client/commit/f0e030014fb7a39e5f38469f43199dc590fd0e8d"}, "type": "CWE-74"}
| 255
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/**\n * Add a data array to the table, creating DOM node etc. This is the parallel to\n * _fnGatherData, but for adding rows from a Javascript source, rather than a\n * DOM source.\n * @param {object} oSettings dataTables settings object\n * @param {array} aData data array to be added\n * @param {node} [nTr] TR element to add to the table - optional. If not given,\n * DataTables will create a row automatically\n * @param {array} [anTds] Array of TD|TH elements for the row - must be given\n * if nTr is.\n * @returns {int} >=0 if successful (index of new aoData entry), -1 if failed\n * @memberof DataTable#oApi\n */\nfunction _fnAddData ( oSettings, aDataIn, nTr, anTds )\n{\n\t/* Create the object for storing information about this new row */\n\tvar iRow = oSettings.aoData.length;\n\tvar oData = $.extend( true, {}, DataTable.models.oRow, {\n\t\tsrc: nTr ? 'dom' : 'data',\n\t\tidx: iRow\n\t} );",
"\toData._aData = aDataIn;\n\toSettings.aoData.push( oData );",
"\t/* Create the cells */\n\tvar nTd, sThisType;\n\tvar columns = oSettings.aoColumns;",
"\t// Invalidate the column types as the new data needs to be revalidated\n\tfor ( var i=0, iLen=columns.length ; i<iLen ; i++ )\n\t{\n\t\tcolumns[i].sType = null;\n\t}",
"\t/* Add to the display array */\n\toSettings.aiDisplayMaster.push( iRow );",
"\tvar id = oSettings.rowIdFn( aDataIn );\n\tif ( id !== undefined ) {\n\t\toSettings.aIds[ id ] = oData;\n\t}",
"\t/* Create the DOM information, or register it if already present */\n\tif ( nTr || ! oSettings.oFeatures.bDeferRender )\n\t{\n\t\t_fnCreateTr( oSettings, iRow, nTr, anTds );\n\t}",
"\treturn iRow;\n}",
"\n/**\n * Add one or more TR elements to the table. Generally we'd expect to\n * use this for reading data from a DOM sourced table, but it could be\n * used for an TR element. Note that if a TR is given, it is used (i.e.\n * it is not cloned).\n * @param {object} settings dataTables settings object\n * @param {array|node|jQuery} trs The TR element(s) to add to the table\n * @returns {array} Array of indexes for the added rows\n * @memberof DataTable#oApi\n */\nfunction _fnAddTr( settings, trs )\n{\n\tvar row;",
"\t// Allow an individual node to be passed in\n\tif ( ! (trs instanceof $) ) {\n\t\ttrs = $(trs);\n\t}",
"\treturn trs.map( function (i, el) {\n\t\trow = _fnGetRowElements( settings, el );\n\t\treturn _fnAddData( settings, row.data, el, row.cells );\n\t} );\n}",
"\n/**\n * Take a TR element and convert it to an index in aoData\n * @param {object} oSettings dataTables settings object\n * @param {node} n the TR element to find\n * @returns {int} index if the node is found, null if not\n * @memberof DataTable#oApi\n */\nfunction _fnNodeToDataIndex( oSettings, n )\n{\n\treturn (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null;\n}",
"\n/**\n * Take a TD element and convert it into a column data index (not the visible index)\n * @param {object} oSettings dataTables settings object\n * @param {int} iRow The row number the TD/TH can be found in\n * @param {node} n The TD/TH element to find\n * @returns {int} index if the node is found, -1 if not\n * @memberof DataTable#oApi\n */\nfunction _fnNodeToColumnIndex( oSettings, iRow, n )\n{\n\treturn $.inArray( n, oSettings.aoData[ iRow ].anCells );\n}",
"\n/**\n * Get the data for a given cell from the internal cache, taking into account data mapping\n * @param {object} settings dataTables settings object\n * @param {int} rowIdx aoData row id\n * @param {int} colIdx Column index\n * @param {string} type data get type ('display', 'type' 'filter' 'sort')\n * @returns {*} Cell data\n * @memberof DataTable#oApi\n */\nfunction _fnGetCellData( settings, rowIdx, colIdx, type )\n{\n\tvar draw = settings.iDraw;\n\tvar col = settings.aoColumns[colIdx];\n\tvar rowData = settings.aoData[rowIdx]._aData;\n\tvar defaultContent = col.sDefaultContent;\n\tvar cellData = col.fnGetData( rowData, type, {\n\t\tsettings: settings,\n\t\trow: rowIdx,\n\t\tcol: colIdx\n\t} );",
"\tif ( cellData === undefined ) {\n\t\tif ( settings.iDrawError != draw && defaultContent === null ) {\n\t\t\t_fnLog( settings, 0, \"Requested unknown parameter \"+\n\t\t\t\t(typeof col.mData=='function' ? '{function}' : \"'\"+col.mData+\"'\")+\n\t\t\t\t\" for row \"+rowIdx+\", column \"+colIdx, 4 );\n\t\t\tsettings.iDrawError = draw;\n\t\t}\n\t\treturn defaultContent;\n\t}",
"\t// When the data source is null and a specific data type is requested (i.e.\n\t// not the original data), we can use default column data\n\tif ( (cellData === rowData || cellData === null) && defaultContent !== null && type !== undefined ) {\n\t\tcellData = defaultContent;\n\t}\n\telse if ( typeof cellData === 'function' ) {\n\t\t// If the data source is a function, then we run it and use the return,\n\t\t// executing in the scope of the data object (for instances)\n\t\treturn cellData.call( rowData );\n\t}",
"\tif ( cellData === null && type == 'display' ) {\n\t\treturn '';\n\t}\n\treturn cellData;\n}",
"\n/**\n * Set the value for a specific cell, into the internal data cache\n * @param {object} settings dataTables settings object\n * @param {int} rowIdx aoData row id\n * @param {int} colIdx Column index\n * @param {*} val Value to set\n * @memberof DataTable#oApi\n */\nfunction _fnSetCellData( settings, rowIdx, colIdx, val )\n{\n\tvar col = settings.aoColumns[colIdx];\n\tvar rowData = settings.aoData[rowIdx]._aData;",
"\tcol.fnSetData( rowData, val, {\n\t\tsettings: settings,\n\t\trow: rowIdx,\n\t\tcol: colIdx\n\t} );\n}",
"\n// Private variable that is used to match action syntax in the data property object\nvar __reArray = /\\[.*?\\]$/;\nvar __reFn = /\\(\\)$/;",
"/**\n * Split string on periods, taking into account escaped periods\n * @param {string} str String to split\n * @return {array} Split string\n */\nfunction _fnSplitObjNotation( str )\n{\n\treturn $.map( str.match(/(\\\\.|[^\\.])+/g) || [''], function ( s ) {\n\t\treturn s.replace(/\\\\\\./g, '.');\n\t} );\n}",
"\n/**\n * Return a function that can be used to get data from a source object, taking\n * into account the ability to use nested objects as a source\n * @param {string|int|function} mSource The data source for the object\n * @returns {function} Data get function\n * @memberof DataTable#oApi\n */\nfunction _fnGetObjectDataFn( mSource )\n{\n\tif ( $.isPlainObject( mSource ) )\n\t{\n\t\t/* Build an object of get functions, and wrap them in a single call */\n\t\tvar o = {};\n\t\t$.each( mSource, function (key, val) {\n\t\t\tif ( val ) {\n\t\t\t\to[key] = _fnGetObjectDataFn( val );\n\t\t\t}\n\t\t} );",
"\t\treturn function (data, type, row, meta) {\n\t\t\tvar t = o[type] || o._;\n\t\t\treturn t !== undefined ?\n\t\t\t\tt(data, type, row, meta) :\n\t\t\t\tdata;\n\t\t};\n\t}\n\telse if ( mSource === null )\n\t{\n\t\t/* Give an empty string for rendering / sorting etc */\n\t\treturn function (data) { // type, row and meta also passed, but not used\n\t\t\treturn data;\n\t\t};\n\t}\n\telse if ( typeof mSource === 'function' )\n\t{\n\t\treturn function (data, type, row, meta) {\n\t\t\treturn mSource( data, type, row, meta );\n\t\t};\n\t}\n\telse if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||\n\t\t mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )\n\t{\n\t\t/* If there is a . in the source string then the data source is in a\n\t\t * nested object so we loop over the data for each level to get the next\n\t\t * level down. On each loop we test for undefined, and if found immediately\n\t\t * return. This allows entire objects to be missing and sDefaultContent to\n\t\t * be used if defined, rather than throwing an error\n\t\t */\n\t\tvar fetchData = function (data, type, src) {\n\t\t\tvar arrayNotation, funcNotation, out, innerSrc;",
"\t\t\tif ( src !== \"\" )\n\t\t\t{\n\t\t\t\tvar a = _fnSplitObjNotation( src );",
"\t\t\t\tfor ( var i=0, iLen=a.length ; i<iLen ; i++ )\n\t\t\t\t{\n\t\t\t\t\t// Check if we are dealing with special notation\n\t\t\t\t\tarrayNotation = a[i].match(__reArray);\n\t\t\t\t\tfuncNotation = a[i].match(__reFn);",
"\t\t\t\t\tif ( arrayNotation )\n\t\t\t\t\t{\n\t\t\t\t\t\t// Array notation\n\t\t\t\t\t\ta[i] = a[i].replace(__reArray, '');",
"\t\t\t\t\t\t// Condition allows simply [] to be passed in\n\t\t\t\t\t\tif ( a[i] !== \"\" ) {\n\t\t\t\t\t\t\tdata = data[ a[i] ];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tout = [];",
"\t\t\t\t\t\t// Get the remainder of the nested object to get\n\t\t\t\t\t\ta.splice( 0, i+1 );\n\t\t\t\t\t\tinnerSrc = a.join('.');",
"\t\t\t\t\t\t// Traverse each entry in the array getting the properties requested\n\t\t\t\t\t\tif ( Array.isArray( data ) ) {\n\t\t\t\t\t\t\tfor ( var j=0, jLen=data.length ; j<jLen ; j++ ) {\n\t\t\t\t\t\t\t\tout.push( fetchData( data[j], type, innerSrc ) );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}",
"\t\t\t\t\t\t// If a string is given in between the array notation indicators, that\n\t\t\t\t\t\t// is used to join the strings together, otherwise an array is returned\n\t\t\t\t\t\tvar join = arrayNotation[0].substring(1, arrayNotation[0].length-1);\n\t\t\t\t\t\tdata = (join===\"\") ? out : out.join(join);",
"\t\t\t\t\t\t// The inner call to fetchData has already traversed through the remainder\n\t\t\t\t\t\t// of the source requested, so we exit from the loop\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse if ( funcNotation )\n\t\t\t\t\t{\n\t\t\t\t\t\t// Function call\n\t\t\t\t\t\ta[i] = a[i].replace(__reFn, '');\n\t\t\t\t\t\tdata = data[ a[i] ]();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}",
"\t\t\t\t\tif ( data === null || data[ a[i] ] === undefined )\n\t\t\t\t\t{\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\tdata = data[ a[i] ];\n\t\t\t\t}\n\t\t\t}",
"\t\t\treturn data;\n\t\t};",
"\t\treturn function (data, type) { // row and meta also passed, but not used\n\t\t\treturn fetchData( data, type, mSource );\n\t\t};\n\t}\n\telse\n\t{\n\t\t/* Array or flat object mapping */\n\t\treturn function (data, type) { // row and meta also passed, but not used\n\t\t\treturn data[mSource];\n\t\t};\n\t}\n}",
"\n/**\n * Return a function that can be used to set data from a source object, taking\n * into account the ability to use nested objects as a source\n * @param {string|int|function} mSource The data source for the object\n * @returns {function} Data set function\n * @memberof DataTable#oApi\n */\nfunction _fnSetObjectDataFn( mSource )\n{\n\tif ( $.isPlainObject( mSource ) )\n\t{\n\t\t/* Unlike get, only the underscore (global) option is used for for\n\t\t * setting data since we don't know the type here. This is why an object\n\t\t * option is not documented for `mData` (which is read/write), but it is\n\t\t * for `mRender` which is read only.\n\t\t */\n\t\treturn _fnSetObjectDataFn( mSource._ );\n\t}\n\telse if ( mSource === null )\n\t{\n\t\t/* Nothing to do when the data source is null */\n\t\treturn function () {};\n\t}\n\telse if ( typeof mSource === 'function' )\n\t{\n\t\treturn function (data, val, meta) {\n\t\t\tmSource( data, 'set', val, meta );\n\t\t};\n\t}\n\telse if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||\n\t\t mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )\n\t{\n\t\t/* Like the get, we need to get data from a nested object */\n\t\tvar setData = function (data, val, src) {\n\t\t\tvar a = _fnSplitObjNotation( src ), b;\n\t\t\tvar aLast = a[a.length-1];\n\t\t\tvar arrayNotation, funcNotation, o, innerSrc;",
"\t\t\tfor ( var i=0, iLen=a.length-1 ; i<iLen ; i++ )\n\t\t\t{\n\t\t\t\t// Protect against prototype pollution",
"\t\t\t\tif (a[i] === '__proto__') {",
"\t\t\t\t\tthrow new Error('Cannot set prototype values');\n\t\t\t\t}",
"\t\t\t\t// Check if we are dealing with an array notation request\n\t\t\t\tarrayNotation = a[i].match(__reArray);\n\t\t\t\tfuncNotation = a[i].match(__reFn);",
"\t\t\t\tif ( arrayNotation )\n\t\t\t\t{\n\t\t\t\t\ta[i] = a[i].replace(__reArray, '');\n\t\t\t\t\tdata[ a[i] ] = [];",
"\t\t\t\t\t// Get the remainder of the nested object to set so we can recurse\n\t\t\t\t\tb = a.slice();\n\t\t\t\t\tb.splice( 0, i+1 );\n\t\t\t\t\tinnerSrc = b.join('.');",
"\t\t\t\t\t// Traverse each entry in the array setting the properties requested\n\t\t\t\t\tif ( Array.isArray( val ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tfor ( var j=0, jLen=val.length ; j<jLen ; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\to = {};\n\t\t\t\t\t\t\tsetData( o, val[j], innerSrc );\n\t\t\t\t\t\t\tdata[ a[i] ].push( o );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// We've been asked to save data to an array, but it\n\t\t\t\t\t\t// isn't array data to be saved. Best that can be done\n\t\t\t\t\t\t// is to just save the value.\n\t\t\t\t\t\tdata[ a[i] ] = val;\n\t\t\t\t\t}",
"\t\t\t\t\t// The inner call to setData has already traversed through the remainder\n\t\t\t\t\t// of the source and has set the data, thus we can exit here\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if ( funcNotation )\n\t\t\t\t{\n\t\t\t\t\t// Function call\n\t\t\t\t\ta[i] = a[i].replace(__reFn, '');\n\t\t\t\t\tdata = data[ a[i] ]( val );\n\t\t\t\t}",
"\t\t\t\t// If the nested object doesn't currently exist - since we are\n\t\t\t\t// trying to set the value - create it\n\t\t\t\tif ( data[ a[i] ] === null || data[ a[i] ] === undefined )\n\t\t\t\t{\n\t\t\t\t\tdata[ a[i] ] = {};\n\t\t\t\t}\n\t\t\t\tdata = data[ a[i] ];\n\t\t\t}",
"\t\t\t// Last item in the input - i.e, the actual set\n\t\t\tif ( aLast.match(__reFn ) )\n\t\t\t{\n\t\t\t\t// Function call\n\t\t\t\tdata = data[ aLast.replace(__reFn, '') ]( val );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// If array notation is used, we just want to strip it and use the property name\n\t\t\t\t// and assign the value. If it isn't used, then we get the result we want anyway\n\t\t\t\tdata[ aLast.replace(__reArray, '') ] = val;\n\t\t\t}\n\t\t};",
"\t\treturn function (data, val) { // meta is also passed in, but not used\n\t\t\treturn setData( data, val, mSource );\n\t\t};\n\t}\n\telse\n\t{\n\t\t/* Array or flat object mapping */\n\t\treturn function (data, val) { // meta is also passed in, but not used\n\t\t\tdata[mSource] = val;\n\t\t};\n\t}\n}",
"\n/**\n * Return an array with the full table data\n * @param {object} oSettings dataTables settings object\n * @returns array {array} aData Master data array\n * @memberof DataTable#oApi\n */\nfunction _fnGetDataMaster ( settings )\n{\n\treturn _pluck( settings.aoData, '_aData' );\n}",
"\n/**\n * Nuke the table\n * @param {object} oSettings dataTables settings object\n * @memberof DataTable#oApi\n */\nfunction _fnClearTable( settings )\n{\n\tsettings.aoData.length = 0;\n\tsettings.aiDisplayMaster.length = 0;\n\tsettings.aiDisplay.length = 0;\n\tsettings.aIds = {};\n}",
"\n /**\n * Take an array of integers (index array) and remove a target integer (value - not\n * the key!)\n * @param {array} a Index array to target\n * @param {int} iTarget value to find\n * @memberof DataTable#oApi\n */\nfunction _fnDeleteIndex( a, iTarget, splice )\n{\n\tvar iTargetIndex = -1;",
"\tfor ( var i=0, iLen=a.length ; i<iLen ; i++ )\n\t{\n\t\tif ( a[i] == iTarget )\n\t\t{\n\t\t\tiTargetIndex = i;\n\t\t}\n\t\telse if ( a[i] > iTarget )\n\t\t{\n\t\t\ta[i]--;\n\t\t}\n\t}",
"\tif ( iTargetIndex != -1 && splice === undefined )\n\t{\n\t\ta.splice( iTargetIndex, 1 );\n\t}\n}",
"\n/**\n * Mark cached data as invalid such that a re-read of the data will occur when\n * the cached data is next requested. Also update from the data source object.\n *\n * @param {object} settings DataTables settings object\n * @param {int} rowIdx Row index to invalidate\n * @param {string} [src] Source to invalidate from: undefined, 'auto', 'dom'\n * or 'data'\n * @param {int} [colIdx] Column index to invalidate. If undefined the whole\n * row will be invalidated\n * @memberof DataTable#oApi\n *\n * @todo For the modularisation of v1.11 this will need to become a callback, so\n * the sort and filter methods can subscribe to it. That will required\n * initialisation options for sorting, which is why it is not already baked in\n */\nfunction _fnInvalidate( settings, rowIdx, src, colIdx )\n{\n\tvar row = settings.aoData[ rowIdx ];\n\tvar i, ien;\n\tvar cellWrite = function ( cell, col ) {\n\t\t// This is very frustrating, but in IE if you just write directly\n\t\t// to innerHTML, and elements that are overwritten are GC'ed,\n\t\t// even if there is a reference to them elsewhere\n\t\twhile ( cell.childNodes.length ) {\n\t\t\tcell.removeChild( cell.firstChild );\n\t\t}",
"\t\tcell.innerHTML = _fnGetCellData( settings, rowIdx, col, 'display' );\n\t};",
"\t// Are we reading last data from DOM or the data object?\n\tif ( src === 'dom' || ((! src || src === 'auto') && row.src === 'dom') ) {\n\t\t// Read the data from the DOM\n\t\trow._aData = _fnGetRowElements(\n\t\t\t\tsettings, row, colIdx, colIdx === undefined ? undefined : row._aData\n\t\t\t)\n\t\t\t.data;\n\t}\n\telse {\n\t\t// Reading from data object, update the DOM\n\t\tvar cells = row.anCells;",
"\t\tif ( cells ) {\n\t\t\tif ( colIdx !== undefined ) {\n\t\t\t\tcellWrite( cells[colIdx], colIdx );\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor ( i=0, ien=cells.length ; i<ien ; i++ ) {\n\t\t\t\t\tcellWrite( cells[i], i );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\t// For both row and cell invalidation, the cached data for sorting and\n\t// filtering is nulled out\n\trow._aSortData = null;\n\trow._aFilterData = null;",
"\t// Invalidate the type for a specific column (if given) or all columns since\n\t// the data might have changed\n\tvar cols = settings.aoColumns;\n\tif ( colIdx !== undefined ) {\n\t\tcols[ colIdx ].sType = null;\n\t}\n\telse {\n\t\tfor ( i=0, ien=cols.length ; i<ien ; i++ ) {\n\t\t\tcols[i].sType = null;\n\t\t}",
"\t\t// Update DataTables special `DT_*` attributes for the row\n\t\t_fnRowAttributes( settings, row );\n\t}\n}",
"\n/**\n * Build a data source object from an HTML row, reading the contents of the\n * cells that are in the row.\n *\n * @param {object} settings DataTables settings object\n * @param {node|object} TR element from which to read data or existing row\n * object from which to re-read the data from the cells\n * @param {int} [colIdx] Optional column index\n * @param {array|object} [d] Data source object. If `colIdx` is given then this\n * parameter should also be given and will be used to write the data into.\n * Only the column in question will be written\n * @returns {object} Object with two parameters: `data` the data read, in\n * document order, and `cells` and array of nodes (they can be useful to the\n * caller, so rather than needing a second traversal to get them, just return\n * them from here).\n * @memberof DataTable#oApi\n */\nfunction _fnGetRowElements( settings, row, colIdx, d )\n{\n\tvar\n\t\ttds = [],\n\t\ttd = row.firstChild,\n\t\tname, col, o, i=0, contents,\n\t\tcolumns = settings.aoColumns,\n\t\tobjectRead = settings._rowReadObject;",
"\t// Allow the data object to be passed in, or construct\n\td = d !== undefined ?\n\t\td :\n\t\tobjectRead ?\n\t\t\t{} :\n\t\t\t[];",
"\tvar attr = function ( str, td ) {\n\t\tif ( typeof str === 'string' ) {\n\t\t\tvar idx = str.indexOf('@');",
"\t\t\tif ( idx !== -1 ) {\n\t\t\t\tvar attr = str.substring( idx+1 );\n\t\t\t\tvar setter = _fnSetObjectDataFn( str );\n\t\t\t\tsetter( d, td.getAttribute( attr ) );\n\t\t\t}\n\t\t}\n\t};",
"\t// Read data from a cell and store into the data object\n\tvar cellProcess = function ( cell ) {\n\t\tif ( colIdx === undefined || colIdx === i ) {\n\t\t\tcol = columns[i];\n\t\t\tcontents = (cell.innerHTML).trim();",
"\t\t\tif ( col && col._bAttrSrc ) {\n\t\t\t\tvar setter = _fnSetObjectDataFn( col.mData._ );\n\t\t\t\tsetter( d, contents );",
"\t\t\t\tattr( col.mData.sort, cell );\n\t\t\t\tattr( col.mData.type, cell );\n\t\t\t\tattr( col.mData.filter, cell );\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Depending on the `data` option for the columns the data can\n\t\t\t\t// be read to either an object or an array.\n\t\t\t\tif ( objectRead ) {\n\t\t\t\t\tif ( ! col._setter ) {\n\t\t\t\t\t\t// Cache the setter function\n\t\t\t\t\t\tcol._setter = _fnSetObjectDataFn( col.mData );\n\t\t\t\t\t}\n\t\t\t\t\tcol._setter( d, contents );\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\td[i] = contents;\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\ti++;\n\t};",
"\tif ( td ) {\n\t\t// `tr` element was passed in\n\t\twhile ( td ) {\n\t\t\tname = td.nodeName.toUpperCase();",
"\t\t\tif ( name == \"TD\" || name == \"TH\" ) {\n\t\t\t\tcellProcess( td );\n\t\t\t\ttds.push( td );\n\t\t\t}",
"\t\t\ttd = td.nextSibling;\n\t\t}\n\t}\n\telse {\n\t\t// Existing row object passed in\n\t\ttds = row.anCells;",
"\t\tfor ( var j=0, jen=tds.length ; j<jen ; j++ ) {\n\t\t\tcellProcess( tds[j] );\n\t\t}\n\t}",
"\t// Read the ID from the DOM if present\n\tvar rowNode = row.firstChild ? row : row.nTr;",
"\tif ( rowNode ) {\n\t\tvar id = rowNode.getAttribute( 'id' );",
"\t\tif ( id ) {\n\t\t\t_fnSetObjectDataFn( settings.rowId )( d, id );\n\t\t}\n\t}",
"\treturn {\n\t\tdata: d,\n\t\tcells: tds\n\t};\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [361], "buggy_code_start_loc": [360], "filenames": ["js/core/core.data.js"], "fixing_code_end_loc": [361], "fixing_code_start_loc": [360], "message": "All versions of package datatables.net are vulnerable to Prototype Pollution due to an incomplete fix for https://snyk.io/vuln/SNYK-JS-DATATABLESNET-598806.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:datatables:datatables.net:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "E9C31498-D6FB-4A18-86D6-10D48577C6EF", "versionEndExcluding": "1.10.23", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "All versions of package datatables.net are vulnerable to Prototype Pollution due to an incomplete fix for https://snyk.io/vuln/SNYK-JS-DATATABLESNET-598806."}, {"lang": "es", "value": "Todas las versiones del paquete datatables.net son vulnerables a una contaminaci\u00f3n de prototipos debido a una correcci\u00f3n incompleta para https://snyk.io/vuln/SNYK-JS-DATATABLESNET-598806"}], "evaluatorComment": null, "id": "CVE-2020-28458", "lastModified": "2022-08-15T15:51:35.970", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.4, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2020-12-16T11:15:12.130", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/DataTables/DataTablesSrc/commit/a51cbe99fd3d02aa5582f97d4af1615d11a1ea03"}, {"source": "report@snyk.io", "tags": ["Broken Link", "Third Party Advisory"], "url": "https://github.com/DataTables/Dist-DataTables/blob/master/js/jquery.dataTables.js%23L2766"}, {"source": "report@snyk.io", "tags": ["Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSBOWER-1051961"}, {"source": "report@snyk.io", "tags": ["Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSNPM-1051962"}, {"source": "report@snyk.io", "tags": ["Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-DATATABLESNET-1016402"}, {"source": "report@snyk.io", "tags": ["Exploit", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-DATATABLESNET-598806"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-1321"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/DataTables/DataTablesSrc/commit/a51cbe99fd3d02aa5582f97d4af1615d11a1ea03"}, "type": "CWE-1321"}
| 256
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/**\n * Add a data array to the table, creating DOM node etc. This is the parallel to\n * _fnGatherData, but for adding rows from a Javascript source, rather than a\n * DOM source.\n * @param {object} oSettings dataTables settings object\n * @param {array} aData data array to be added\n * @param {node} [nTr] TR element to add to the table - optional. If not given,\n * DataTables will create a row automatically\n * @param {array} [anTds] Array of TD|TH elements for the row - must be given\n * if nTr is.\n * @returns {int} >=0 if successful (index of new aoData entry), -1 if failed\n * @memberof DataTable#oApi\n */\nfunction _fnAddData ( oSettings, aDataIn, nTr, anTds )\n{\n\t/* Create the object for storing information about this new row */\n\tvar iRow = oSettings.aoData.length;\n\tvar oData = $.extend( true, {}, DataTable.models.oRow, {\n\t\tsrc: nTr ? 'dom' : 'data',\n\t\tidx: iRow\n\t} );",
"\toData._aData = aDataIn;\n\toSettings.aoData.push( oData );",
"\t/* Create the cells */\n\tvar nTd, sThisType;\n\tvar columns = oSettings.aoColumns;",
"\t// Invalidate the column types as the new data needs to be revalidated\n\tfor ( var i=0, iLen=columns.length ; i<iLen ; i++ )\n\t{\n\t\tcolumns[i].sType = null;\n\t}",
"\t/* Add to the display array */\n\toSettings.aiDisplayMaster.push( iRow );",
"\tvar id = oSettings.rowIdFn( aDataIn );\n\tif ( id !== undefined ) {\n\t\toSettings.aIds[ id ] = oData;\n\t}",
"\t/* Create the DOM information, or register it if already present */\n\tif ( nTr || ! oSettings.oFeatures.bDeferRender )\n\t{\n\t\t_fnCreateTr( oSettings, iRow, nTr, anTds );\n\t}",
"\treturn iRow;\n}",
"\n/**\n * Add one or more TR elements to the table. Generally we'd expect to\n * use this for reading data from a DOM sourced table, but it could be\n * used for an TR element. Note that if a TR is given, it is used (i.e.\n * it is not cloned).\n * @param {object} settings dataTables settings object\n * @param {array|node|jQuery} trs The TR element(s) to add to the table\n * @returns {array} Array of indexes for the added rows\n * @memberof DataTable#oApi\n */\nfunction _fnAddTr( settings, trs )\n{\n\tvar row;",
"\t// Allow an individual node to be passed in\n\tif ( ! (trs instanceof $) ) {\n\t\ttrs = $(trs);\n\t}",
"\treturn trs.map( function (i, el) {\n\t\trow = _fnGetRowElements( settings, el );\n\t\treturn _fnAddData( settings, row.data, el, row.cells );\n\t} );\n}",
"\n/**\n * Take a TR element and convert it to an index in aoData\n * @param {object} oSettings dataTables settings object\n * @param {node} n the TR element to find\n * @returns {int} index if the node is found, null if not\n * @memberof DataTable#oApi\n */\nfunction _fnNodeToDataIndex( oSettings, n )\n{\n\treturn (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null;\n}",
"\n/**\n * Take a TD element and convert it into a column data index (not the visible index)\n * @param {object} oSettings dataTables settings object\n * @param {int} iRow The row number the TD/TH can be found in\n * @param {node} n The TD/TH element to find\n * @returns {int} index if the node is found, -1 if not\n * @memberof DataTable#oApi\n */\nfunction _fnNodeToColumnIndex( oSettings, iRow, n )\n{\n\treturn $.inArray( n, oSettings.aoData[ iRow ].anCells );\n}",
"\n/**\n * Get the data for a given cell from the internal cache, taking into account data mapping\n * @param {object} settings dataTables settings object\n * @param {int} rowIdx aoData row id\n * @param {int} colIdx Column index\n * @param {string} type data get type ('display', 'type' 'filter' 'sort')\n * @returns {*} Cell data\n * @memberof DataTable#oApi\n */\nfunction _fnGetCellData( settings, rowIdx, colIdx, type )\n{\n\tvar draw = settings.iDraw;\n\tvar col = settings.aoColumns[colIdx];\n\tvar rowData = settings.aoData[rowIdx]._aData;\n\tvar defaultContent = col.sDefaultContent;\n\tvar cellData = col.fnGetData( rowData, type, {\n\t\tsettings: settings,\n\t\trow: rowIdx,\n\t\tcol: colIdx\n\t} );",
"\tif ( cellData === undefined ) {\n\t\tif ( settings.iDrawError != draw && defaultContent === null ) {\n\t\t\t_fnLog( settings, 0, \"Requested unknown parameter \"+\n\t\t\t\t(typeof col.mData=='function' ? '{function}' : \"'\"+col.mData+\"'\")+\n\t\t\t\t\" for row \"+rowIdx+\", column \"+colIdx, 4 );\n\t\t\tsettings.iDrawError = draw;\n\t\t}\n\t\treturn defaultContent;\n\t}",
"\t// When the data source is null and a specific data type is requested (i.e.\n\t// not the original data), we can use default column data\n\tif ( (cellData === rowData || cellData === null) && defaultContent !== null && type !== undefined ) {\n\t\tcellData = defaultContent;\n\t}\n\telse if ( typeof cellData === 'function' ) {\n\t\t// If the data source is a function, then we run it and use the return,\n\t\t// executing in the scope of the data object (for instances)\n\t\treturn cellData.call( rowData );\n\t}",
"\tif ( cellData === null && type == 'display' ) {\n\t\treturn '';\n\t}\n\treturn cellData;\n}",
"\n/**\n * Set the value for a specific cell, into the internal data cache\n * @param {object} settings dataTables settings object\n * @param {int} rowIdx aoData row id\n * @param {int} colIdx Column index\n * @param {*} val Value to set\n * @memberof DataTable#oApi\n */\nfunction _fnSetCellData( settings, rowIdx, colIdx, val )\n{\n\tvar col = settings.aoColumns[colIdx];\n\tvar rowData = settings.aoData[rowIdx]._aData;",
"\tcol.fnSetData( rowData, val, {\n\t\tsettings: settings,\n\t\trow: rowIdx,\n\t\tcol: colIdx\n\t} );\n}",
"\n// Private variable that is used to match action syntax in the data property object\nvar __reArray = /\\[.*?\\]$/;\nvar __reFn = /\\(\\)$/;",
"/**\n * Split string on periods, taking into account escaped periods\n * @param {string} str String to split\n * @return {array} Split string\n */\nfunction _fnSplitObjNotation( str )\n{\n\treturn $.map( str.match(/(\\\\.|[^\\.])+/g) || [''], function ( s ) {\n\t\treturn s.replace(/\\\\\\./g, '.');\n\t} );\n}",
"\n/**\n * Return a function that can be used to get data from a source object, taking\n * into account the ability to use nested objects as a source\n * @param {string|int|function} mSource The data source for the object\n * @returns {function} Data get function\n * @memberof DataTable#oApi\n */\nfunction _fnGetObjectDataFn( mSource )\n{\n\tif ( $.isPlainObject( mSource ) )\n\t{\n\t\t/* Build an object of get functions, and wrap them in a single call */\n\t\tvar o = {};\n\t\t$.each( mSource, function (key, val) {\n\t\t\tif ( val ) {\n\t\t\t\to[key] = _fnGetObjectDataFn( val );\n\t\t\t}\n\t\t} );",
"\t\treturn function (data, type, row, meta) {\n\t\t\tvar t = o[type] || o._;\n\t\t\treturn t !== undefined ?\n\t\t\t\tt(data, type, row, meta) :\n\t\t\t\tdata;\n\t\t};\n\t}\n\telse if ( mSource === null )\n\t{\n\t\t/* Give an empty string for rendering / sorting etc */\n\t\treturn function (data) { // type, row and meta also passed, but not used\n\t\t\treturn data;\n\t\t};\n\t}\n\telse if ( typeof mSource === 'function' )\n\t{\n\t\treturn function (data, type, row, meta) {\n\t\t\treturn mSource( data, type, row, meta );\n\t\t};\n\t}\n\telse if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||\n\t\t mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )\n\t{\n\t\t/* If there is a . in the source string then the data source is in a\n\t\t * nested object so we loop over the data for each level to get the next\n\t\t * level down. On each loop we test for undefined, and if found immediately\n\t\t * return. This allows entire objects to be missing and sDefaultContent to\n\t\t * be used if defined, rather than throwing an error\n\t\t */\n\t\tvar fetchData = function (data, type, src) {\n\t\t\tvar arrayNotation, funcNotation, out, innerSrc;",
"\t\t\tif ( src !== \"\" )\n\t\t\t{\n\t\t\t\tvar a = _fnSplitObjNotation( src );",
"\t\t\t\tfor ( var i=0, iLen=a.length ; i<iLen ; i++ )\n\t\t\t\t{\n\t\t\t\t\t// Check if we are dealing with special notation\n\t\t\t\t\tarrayNotation = a[i].match(__reArray);\n\t\t\t\t\tfuncNotation = a[i].match(__reFn);",
"\t\t\t\t\tif ( arrayNotation )\n\t\t\t\t\t{\n\t\t\t\t\t\t// Array notation\n\t\t\t\t\t\ta[i] = a[i].replace(__reArray, '');",
"\t\t\t\t\t\t// Condition allows simply [] to be passed in\n\t\t\t\t\t\tif ( a[i] !== \"\" ) {\n\t\t\t\t\t\t\tdata = data[ a[i] ];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tout = [];",
"\t\t\t\t\t\t// Get the remainder of the nested object to get\n\t\t\t\t\t\ta.splice( 0, i+1 );\n\t\t\t\t\t\tinnerSrc = a.join('.');",
"\t\t\t\t\t\t// Traverse each entry in the array getting the properties requested\n\t\t\t\t\t\tif ( Array.isArray( data ) ) {\n\t\t\t\t\t\t\tfor ( var j=0, jLen=data.length ; j<jLen ; j++ ) {\n\t\t\t\t\t\t\t\tout.push( fetchData( data[j], type, innerSrc ) );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}",
"\t\t\t\t\t\t// If a string is given in between the array notation indicators, that\n\t\t\t\t\t\t// is used to join the strings together, otherwise an array is returned\n\t\t\t\t\t\tvar join = arrayNotation[0].substring(1, arrayNotation[0].length-1);\n\t\t\t\t\t\tdata = (join===\"\") ? out : out.join(join);",
"\t\t\t\t\t\t// The inner call to fetchData has already traversed through the remainder\n\t\t\t\t\t\t// of the source requested, so we exit from the loop\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse if ( funcNotation )\n\t\t\t\t\t{\n\t\t\t\t\t\t// Function call\n\t\t\t\t\t\ta[i] = a[i].replace(__reFn, '');\n\t\t\t\t\t\tdata = data[ a[i] ]();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}",
"\t\t\t\t\tif ( data === null || data[ a[i] ] === undefined )\n\t\t\t\t\t{\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\tdata = data[ a[i] ];\n\t\t\t\t}\n\t\t\t}",
"\t\t\treturn data;\n\t\t};",
"\t\treturn function (data, type) { // row and meta also passed, but not used\n\t\t\treturn fetchData( data, type, mSource );\n\t\t};\n\t}\n\telse\n\t{\n\t\t/* Array or flat object mapping */\n\t\treturn function (data, type) { // row and meta also passed, but not used\n\t\t\treturn data[mSource];\n\t\t};\n\t}\n}",
"\n/**\n * Return a function that can be used to set data from a source object, taking\n * into account the ability to use nested objects as a source\n * @param {string|int|function} mSource The data source for the object\n * @returns {function} Data set function\n * @memberof DataTable#oApi\n */\nfunction _fnSetObjectDataFn( mSource )\n{\n\tif ( $.isPlainObject( mSource ) )\n\t{\n\t\t/* Unlike get, only the underscore (global) option is used for for\n\t\t * setting data since we don't know the type here. This is why an object\n\t\t * option is not documented for `mData` (which is read/write), but it is\n\t\t * for `mRender` which is read only.\n\t\t */\n\t\treturn _fnSetObjectDataFn( mSource._ );\n\t}\n\telse if ( mSource === null )\n\t{\n\t\t/* Nothing to do when the data source is null */\n\t\treturn function () {};\n\t}\n\telse if ( typeof mSource === 'function' )\n\t{\n\t\treturn function (data, val, meta) {\n\t\t\tmSource( data, 'set', val, meta );\n\t\t};\n\t}\n\telse if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||\n\t\t mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )\n\t{\n\t\t/* Like the get, we need to get data from a nested object */\n\t\tvar setData = function (data, val, src) {\n\t\t\tvar a = _fnSplitObjNotation( src ), b;\n\t\t\tvar aLast = a[a.length-1];\n\t\t\tvar arrayNotation, funcNotation, o, innerSrc;",
"\t\t\tfor ( var i=0, iLen=a.length-1 ; i<iLen ; i++ )\n\t\t\t{\n\t\t\t\t// Protect against prototype pollution",
"\t\t\t\tif (a[i] === '__proto__' || a[i] === 'constructor') {",
"\t\t\t\t\tthrow new Error('Cannot set prototype values');\n\t\t\t\t}",
"\t\t\t\t// Check if we are dealing with an array notation request\n\t\t\t\tarrayNotation = a[i].match(__reArray);\n\t\t\t\tfuncNotation = a[i].match(__reFn);",
"\t\t\t\tif ( arrayNotation )\n\t\t\t\t{\n\t\t\t\t\ta[i] = a[i].replace(__reArray, '');\n\t\t\t\t\tdata[ a[i] ] = [];",
"\t\t\t\t\t// Get the remainder of the nested object to set so we can recurse\n\t\t\t\t\tb = a.slice();\n\t\t\t\t\tb.splice( 0, i+1 );\n\t\t\t\t\tinnerSrc = b.join('.');",
"\t\t\t\t\t// Traverse each entry in the array setting the properties requested\n\t\t\t\t\tif ( Array.isArray( val ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tfor ( var j=0, jLen=val.length ; j<jLen ; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\to = {};\n\t\t\t\t\t\t\tsetData( o, val[j], innerSrc );\n\t\t\t\t\t\t\tdata[ a[i] ].push( o );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// We've been asked to save data to an array, but it\n\t\t\t\t\t\t// isn't array data to be saved. Best that can be done\n\t\t\t\t\t\t// is to just save the value.\n\t\t\t\t\t\tdata[ a[i] ] = val;\n\t\t\t\t\t}",
"\t\t\t\t\t// The inner call to setData has already traversed through the remainder\n\t\t\t\t\t// of the source and has set the data, thus we can exit here\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if ( funcNotation )\n\t\t\t\t{\n\t\t\t\t\t// Function call\n\t\t\t\t\ta[i] = a[i].replace(__reFn, '');\n\t\t\t\t\tdata = data[ a[i] ]( val );\n\t\t\t\t}",
"\t\t\t\t// If the nested object doesn't currently exist - since we are\n\t\t\t\t// trying to set the value - create it\n\t\t\t\tif ( data[ a[i] ] === null || data[ a[i] ] === undefined )\n\t\t\t\t{\n\t\t\t\t\tdata[ a[i] ] = {};\n\t\t\t\t}\n\t\t\t\tdata = data[ a[i] ];\n\t\t\t}",
"\t\t\t// Last item in the input - i.e, the actual set\n\t\t\tif ( aLast.match(__reFn ) )\n\t\t\t{\n\t\t\t\t// Function call\n\t\t\t\tdata = data[ aLast.replace(__reFn, '') ]( val );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// If array notation is used, we just want to strip it and use the property name\n\t\t\t\t// and assign the value. If it isn't used, then we get the result we want anyway\n\t\t\t\tdata[ aLast.replace(__reArray, '') ] = val;\n\t\t\t}\n\t\t};",
"\t\treturn function (data, val) { // meta is also passed in, but not used\n\t\t\treturn setData( data, val, mSource );\n\t\t};\n\t}\n\telse\n\t{\n\t\t/* Array or flat object mapping */\n\t\treturn function (data, val) { // meta is also passed in, but not used\n\t\t\tdata[mSource] = val;\n\t\t};\n\t}\n}",
"\n/**\n * Return an array with the full table data\n * @param {object} oSettings dataTables settings object\n * @returns array {array} aData Master data array\n * @memberof DataTable#oApi\n */\nfunction _fnGetDataMaster ( settings )\n{\n\treturn _pluck( settings.aoData, '_aData' );\n}",
"\n/**\n * Nuke the table\n * @param {object} oSettings dataTables settings object\n * @memberof DataTable#oApi\n */\nfunction _fnClearTable( settings )\n{\n\tsettings.aoData.length = 0;\n\tsettings.aiDisplayMaster.length = 0;\n\tsettings.aiDisplay.length = 0;\n\tsettings.aIds = {};\n}",
"\n /**\n * Take an array of integers (index array) and remove a target integer (value - not\n * the key!)\n * @param {array} a Index array to target\n * @param {int} iTarget value to find\n * @memberof DataTable#oApi\n */\nfunction _fnDeleteIndex( a, iTarget, splice )\n{\n\tvar iTargetIndex = -1;",
"\tfor ( var i=0, iLen=a.length ; i<iLen ; i++ )\n\t{\n\t\tif ( a[i] == iTarget )\n\t\t{\n\t\t\tiTargetIndex = i;\n\t\t}\n\t\telse if ( a[i] > iTarget )\n\t\t{\n\t\t\ta[i]--;\n\t\t}\n\t}",
"\tif ( iTargetIndex != -1 && splice === undefined )\n\t{\n\t\ta.splice( iTargetIndex, 1 );\n\t}\n}",
"\n/**\n * Mark cached data as invalid such that a re-read of the data will occur when\n * the cached data is next requested. Also update from the data source object.\n *\n * @param {object} settings DataTables settings object\n * @param {int} rowIdx Row index to invalidate\n * @param {string} [src] Source to invalidate from: undefined, 'auto', 'dom'\n * or 'data'\n * @param {int} [colIdx] Column index to invalidate. If undefined the whole\n * row will be invalidated\n * @memberof DataTable#oApi\n *\n * @todo For the modularisation of v1.11 this will need to become a callback, so\n * the sort and filter methods can subscribe to it. That will required\n * initialisation options for sorting, which is why it is not already baked in\n */\nfunction _fnInvalidate( settings, rowIdx, src, colIdx )\n{\n\tvar row = settings.aoData[ rowIdx ];\n\tvar i, ien;\n\tvar cellWrite = function ( cell, col ) {\n\t\t// This is very frustrating, but in IE if you just write directly\n\t\t// to innerHTML, and elements that are overwritten are GC'ed,\n\t\t// even if there is a reference to them elsewhere\n\t\twhile ( cell.childNodes.length ) {\n\t\t\tcell.removeChild( cell.firstChild );\n\t\t}",
"\t\tcell.innerHTML = _fnGetCellData( settings, rowIdx, col, 'display' );\n\t};",
"\t// Are we reading last data from DOM or the data object?\n\tif ( src === 'dom' || ((! src || src === 'auto') && row.src === 'dom') ) {\n\t\t// Read the data from the DOM\n\t\trow._aData = _fnGetRowElements(\n\t\t\t\tsettings, row, colIdx, colIdx === undefined ? undefined : row._aData\n\t\t\t)\n\t\t\t.data;\n\t}\n\telse {\n\t\t// Reading from data object, update the DOM\n\t\tvar cells = row.anCells;",
"\t\tif ( cells ) {\n\t\t\tif ( colIdx !== undefined ) {\n\t\t\t\tcellWrite( cells[colIdx], colIdx );\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor ( i=0, ien=cells.length ; i<ien ; i++ ) {\n\t\t\t\t\tcellWrite( cells[i], i );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\t// For both row and cell invalidation, the cached data for sorting and\n\t// filtering is nulled out\n\trow._aSortData = null;\n\trow._aFilterData = null;",
"\t// Invalidate the type for a specific column (if given) or all columns since\n\t// the data might have changed\n\tvar cols = settings.aoColumns;\n\tif ( colIdx !== undefined ) {\n\t\tcols[ colIdx ].sType = null;\n\t}\n\telse {\n\t\tfor ( i=0, ien=cols.length ; i<ien ; i++ ) {\n\t\t\tcols[i].sType = null;\n\t\t}",
"\t\t// Update DataTables special `DT_*` attributes for the row\n\t\t_fnRowAttributes( settings, row );\n\t}\n}",
"\n/**\n * Build a data source object from an HTML row, reading the contents of the\n * cells that are in the row.\n *\n * @param {object} settings DataTables settings object\n * @param {node|object} TR element from which to read data or existing row\n * object from which to re-read the data from the cells\n * @param {int} [colIdx] Optional column index\n * @param {array|object} [d] Data source object. If `colIdx` is given then this\n * parameter should also be given and will be used to write the data into.\n * Only the column in question will be written\n * @returns {object} Object with two parameters: `data` the data read, in\n * document order, and `cells` and array of nodes (they can be useful to the\n * caller, so rather than needing a second traversal to get them, just return\n * them from here).\n * @memberof DataTable#oApi\n */\nfunction _fnGetRowElements( settings, row, colIdx, d )\n{\n\tvar\n\t\ttds = [],\n\t\ttd = row.firstChild,\n\t\tname, col, o, i=0, contents,\n\t\tcolumns = settings.aoColumns,\n\t\tobjectRead = settings._rowReadObject;",
"\t// Allow the data object to be passed in, or construct\n\td = d !== undefined ?\n\t\td :\n\t\tobjectRead ?\n\t\t\t{} :\n\t\t\t[];",
"\tvar attr = function ( str, td ) {\n\t\tif ( typeof str === 'string' ) {\n\t\t\tvar idx = str.indexOf('@');",
"\t\t\tif ( idx !== -1 ) {\n\t\t\t\tvar attr = str.substring( idx+1 );\n\t\t\t\tvar setter = _fnSetObjectDataFn( str );\n\t\t\t\tsetter( d, td.getAttribute( attr ) );\n\t\t\t}\n\t\t}\n\t};",
"\t// Read data from a cell and store into the data object\n\tvar cellProcess = function ( cell ) {\n\t\tif ( colIdx === undefined || colIdx === i ) {\n\t\t\tcol = columns[i];\n\t\t\tcontents = (cell.innerHTML).trim();",
"\t\t\tif ( col && col._bAttrSrc ) {\n\t\t\t\tvar setter = _fnSetObjectDataFn( col.mData._ );\n\t\t\t\tsetter( d, contents );",
"\t\t\t\tattr( col.mData.sort, cell );\n\t\t\t\tattr( col.mData.type, cell );\n\t\t\t\tattr( col.mData.filter, cell );\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Depending on the `data` option for the columns the data can\n\t\t\t\t// be read to either an object or an array.\n\t\t\t\tif ( objectRead ) {\n\t\t\t\t\tif ( ! col._setter ) {\n\t\t\t\t\t\t// Cache the setter function\n\t\t\t\t\t\tcol._setter = _fnSetObjectDataFn( col.mData );\n\t\t\t\t\t}\n\t\t\t\t\tcol._setter( d, contents );\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\td[i] = contents;\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\ti++;\n\t};",
"\tif ( td ) {\n\t\t// `tr` element was passed in\n\t\twhile ( td ) {\n\t\t\tname = td.nodeName.toUpperCase();",
"\t\t\tif ( name == \"TD\" || name == \"TH\" ) {\n\t\t\t\tcellProcess( td );\n\t\t\t\ttds.push( td );\n\t\t\t}",
"\t\t\ttd = td.nextSibling;\n\t\t}\n\t}\n\telse {\n\t\t// Existing row object passed in\n\t\ttds = row.anCells;",
"\t\tfor ( var j=0, jen=tds.length ; j<jen ; j++ ) {\n\t\t\tcellProcess( tds[j] );\n\t\t}\n\t}",
"\t// Read the ID from the DOM if present\n\tvar rowNode = row.firstChild ? row : row.nTr;",
"\tif ( rowNode ) {\n\t\tvar id = rowNode.getAttribute( 'id' );",
"\t\tif ( id ) {\n\t\t\t_fnSetObjectDataFn( settings.rowId )( d, id );\n\t\t}\n\t}",
"\treturn {\n\t\tdata: d,\n\t\tcells: tds\n\t};\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [361], "buggy_code_start_loc": [360], "filenames": ["js/core/core.data.js"], "fixing_code_end_loc": [361], "fixing_code_start_loc": [360], "message": "All versions of package datatables.net are vulnerable to Prototype Pollution due to an incomplete fix for https://snyk.io/vuln/SNYK-JS-DATATABLESNET-598806.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:datatables:datatables.net:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "E9C31498-D6FB-4A18-86D6-10D48577C6EF", "versionEndExcluding": "1.10.23", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "All versions of package datatables.net are vulnerable to Prototype Pollution due to an incomplete fix for https://snyk.io/vuln/SNYK-JS-DATATABLESNET-598806."}, {"lang": "es", "value": "Todas las versiones del paquete datatables.net son vulnerables a una contaminaci\u00f3n de prototipos debido a una correcci\u00f3n incompleta para https://snyk.io/vuln/SNYK-JS-DATATABLESNET-598806"}], "evaluatorComment": null, "id": "CVE-2020-28458", "lastModified": "2022-08-15T15:51:35.970", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.4, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2020-12-16T11:15:12.130", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/DataTables/DataTablesSrc/commit/a51cbe99fd3d02aa5582f97d4af1615d11a1ea03"}, {"source": "report@snyk.io", "tags": ["Broken Link", "Third Party Advisory"], "url": "https://github.com/DataTables/Dist-DataTables/blob/master/js/jquery.dataTables.js%23L2766"}, {"source": "report@snyk.io", "tags": ["Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSBOWER-1051961"}, {"source": "report@snyk.io", "tags": ["Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSNPM-1051962"}, {"source": "report@snyk.io", "tags": ["Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-DATATABLESNET-1016402"}, {"source": "report@snyk.io", "tags": ["Exploit", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-DATATABLESNET-598806"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-1321"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/DataTables/DataTablesSrc/commit/a51cbe99fd3d02aa5582f97d4af1615d11a1ea03"}, "type": "CWE-1321"}
| 256
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"#!/bin/env python\nfrom flask import Flask",
"from flask import flash,request,send_file,send_from_directory,redirect,render_template, abort",
"\nfrom werkzeug.utils import secure_filename\nfrom ipaddress import ip_address, ip_network\nimport urllib.request",
"import os\nimport random",
"import hooker",
"hooker.EVENTS.append(\"pre_process\",\n help=\"Before any processing of the URL alias starts. Useful for UA filters, blacklists, etc\")\nhooker.EVENTS.append(\"pre_file\",\n help=\"Before the alias resolves to a file\")\nhooker.EVENTS.append(\"pre_response\",\n help=\"Before the created request is sent\")",
"import wormnest.db_handler as db_handler\nimport wormnest.utils as utils",
"'''\nTo run the App:\npython3 app.py\n'''\napp = Flask(__name__)",
"CONFIG = utils.parse_config()",
"app.config['UPLOAD_FOLDER'] = CONFIG['SRV_DIR']\nprint(CONFIG['IP_WHITELIST'])\n# sys.exit(10)",
"def get_random_alias(length=None):\n assert CONFIG['ALIAS_DIGITS_MIN'] <= CONFIG['ALIAS_DIGITS_MAX']\n if length == None:\n length = random.randint(CONFIG['ALIAS_DIGITS_MIN'], CONFIG['ALIAS_DIGITS_MAX'])\n return utils.randomword(length)",
"\ndef redirect_away():\n return redirect(CONFIG['REDIRECT_URL'], code=302)",
"def abort_404():\n return abort(404)",
"behaviours = {\n 'abort' : abort_404,\n 'redir' : redirect_away,\n}",
"default_miss = behaviours.get(CONFIG['MISS'],'abort')\non_expired = behaviours.get(CONFIG['EXPIRE'],'abort')\nblacklisted = behaviours.get(CONFIG['BLACKLISTED'],'abort')",
"\n@app.after_request\ndef add_header(response):\n response.headers['Cache-Control'] = 'no-store'\n del response.headers['Expires']\n response.headers['Server'] = CONFIG['SERVER_HEADER']\n response.headers['X-Content-Type-Options'] = \"nosniff\"\n del response.headers['Date']",
" return response",
"\n@app.route('/%s/' % CONFIG['MANAGE_URL_DIR'])\ndef show_manage():\n return render_template(\n \"manage_help.html\",\n manage_url = request.base_url\n )",
"@app.route('/%s/load_defaults' % CONFIG['MANAGE_URL_DIR'])\ndef load_defaults():\n add_url_template = \"http://127.0.0.1:{port}/{man}/add?path={path}&alias={alias}&unchecked=True\"\n try:\n if CONFIG['DEFAULT_PATHS_FILE']:\n print(\"[+] Importing defaults from '{}'\".format(CONFIG['DEFAULT_PATHS_FILE']))\n import json\n with open(CONFIG['DEFAULT_PATHS_FILE']) as url_defaults:\n defaults_url_dict = json.load(url_defaults)\n for path, url_params in defaults_url_dict.items():\n print(path, url_params)\n alias = url_params['alias']\n filename = url_params.get('filename',None)\n print (filename)\n if filename:\n add_url_template += '&filename={filename}'\n urllib.request.urlopen(add_url_template.format(\n port=CONFIG['PORT'],\n man=CONFIG['MANAGE_URL_DIR'],\n path=path,\n alias=alias,\n filename=filename,\n )\n )\n return \"<pre>{}</pre>\".format(\n json.dumps(defaults_url_dict, indent=2)\n )\n except Exception as e:\n return render_template(\"custom_error.html\",error_msg=str(e))",
"@app.route(\n '/%s/list/' % CONFIG['MANAGE_URL_DIR'],\n defaults={'req_path': ''}\n )",
"@app.route('/%s/list/<path:req_path>' % CONFIG['MANAGE_URL_DIR'])\ndef dir_listing(req_path):\n '''\n Found here:\nhttps://stackoverflow.com/questions/23718236/python-flask-browsing-through-directory-with-files\n '''\n # Joining the base and the requested path",
" abs_path = os.path.join(CONFIG['SRV_DIR'], req_path)",
"\n # Return 404 if path doesn't exist\n if not os.path.exists(abs_path):\n return abort(404)",
" # Check if path is a file and serve\n if os.path.isfile(abs_path):\n return send_file(abs_path)",
" # Show directory contents\n files = os.listdir(abs_path)\n full_paths = []\n for f in files:\n full_paths.append(\n (f, os.path.join(request.base_url, f))\n )\n # print (full_paths)\n add_url_link = \"%s%s/add\" % (request.url_root, CONFIG['MANAGE_URL_DIR'])\n return render_template('file.html',\n files=full_paths,\n add_url=add_url_link\n )",
"\n@app.route('/%s/add' % CONFIG['MANAGE_URL_DIR'])\ndef add_url():",
" path = request.args.get(\"path\")\n expires = request.args.get(\"clicks\", -1)\n alias = request.args.get(\"alias\", get_random_alias())\n attach_name = request.args.get(\"filename\")\n mimetype = request.args.get(\"mime\", None)\n unchecked_path = request.args.get(\"unchecked\", False)\n if not request.args:\n return render_template(\n 'add_help.html', \n )\n try:\n original_filename = path.split('/')[-1]\n original_extension = original_filename.split('.')[-1]\n except Exception as e:\n return render_template(\n 'custom_error.html', \n error_msg=\"The 'path' variable does not validate\"\n )",
" if original_filename == original_extension:\n # If they are the same, there is no extension\n original_extension = ''\n else:\n original_extension = '.' + original_extension",
" if not attach_name:",
" if not CONFIG['DEFAULT_FILENAME']:\n # The filename is the path's filename\n attach_name = original_filename\n else:\n attach_name = CONFIG['DEFAULT_FILENAME']\n if CONFIG['USE_ORIGINAL_EXTENSION']:\n attach_name += original_extension",
" path = os.path.join(CONFIG['SRV_DIR'], path)\n if not os.path.isfile(path) and not unchecked_path:\n return render_template(\n 'custom_error.html', \n error_msg=\"The path '{}' is NOT a file\".format(path)\n )",
" try:\n if expires is not None: \n int(expires)\n except:\n return render_template(\n 'custom_error.html', \n error_msg=\"Parameter 'clicks' must be positive Integer\"\n )\n try:\n db_handler.add_url(\n path, alias, expires,\n attachment = attach_name,\n mimetype = mimetype\n )\n except Exception as e:\n print (e)\n err = \"Error adding alias '{}'' for path '{}'\".format(alias, path)\n return render_template(\n 'custom_error.html', \n error_msg=err\n )\n full_link = request.url_root + alias\n return render_template(\n 'added_alias.html', \n alias=alias,\n path=path,\n clicks=expires,\n link=full_link\n )",
"@app.route('/%s/del' % CONFIG['MANAGE_URL_DIR'], methods=[\"GET\", \"POST\"])\ndef del_url():\n alias = request.args.get(\"alias\", None) \n if alias is None:\n alias = request.form.get(\"alias\", None)\n if alias is None:\n return render_template(\n 'del_help.html'\n )\n try:\n deleted = db_handler.del_url(alias)\n except KeyError:\n deleted = False\n return \"Deleted '/%s'\" % alias if deleted else \"NOT deleted\"",
"@app.route('/%s/config' % CONFIG['MANAGE_URL_DIR'])\ndef show_config(path=None):\n return render_template('show_config.html', entries=CONFIG)\n \n@app.route('/%s/show' % CONFIG['MANAGE_URL_DIR'])\ndef show_all(path=None):\n entries = db_handler.get_all(path)\n return render_template(\n 'show.html', # Fix show.html to contain mimetypes\n entries = entries\n )",
"@app.route(\n '/%s/upload' % CONFIG['MANAGE_URL_DIR'],\n methods=['POST', 'GET']\n )\ndef file_upload():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n return render_template(\n 'upload_page.html',\n manage_url = CONFIG['MANAGE_URL_DIR'],\n message = \"No file submitted\"\n )\n file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n return render_template(\n 'upload_page.html',\n manage_url = CONFIG['MANAGE_URL_DIR'],\n message = \"No filename submitted\"\n )\n if file:\n filename = request.form.get('filename', file.filename)\n filename = secure_filename(filename)\n try:\n file.save(\n os.path.join(\n app.config['UPLOAD_FOLDER'],\n filename\n )\n )\n except IsADirectoryError:\n return render_template(\n 'upload_page.html',\n manage_url = CONFIG['MANAGE_URL_DIR'],\n message = \"Filename exists\"\n )",
" if request.form.get(\"create_alias\",\n default = False,\n type = bool):\n alias_name = request.form.get(\"alias\", default=None)\n deliver_filename = request.form.get(\"deliver_filename\", default=None)\n return redirect(\n \"/{manage_url}/add?path={filepath}{alias}{filename}\".format(\n manage_url = CONFIG['MANAGE_URL_DIR'],\n filepath = filename,\n alias=\"\" if not alias_name else \"&alias=%s\" % alias_name,\n filename=\"\" if not deliver_filename else \"&filename=%s\" % deliver_filename,\n )\n )\n return render_template(\n 'upload_page.html',\n manage_url = CONFIG['MANAGE_URL_DIR'],\n message = \"File '{}' uploaded successfully!\".format(filename)\n )\n return render_template(\n 'upload_page.html',\n manage_url = CONFIG['MANAGE_URL_DIR'],\n )",
"# Default behaviour - Serve all non \"/manage\" paths\n@app.route('/<path:url_alias>', methods=['POST', 'GET'])\n@app.route('/', defaults={'url_alias': ''}, methods=['POST', 'GET'])\ndef resolve_url(url_alias):\n ret_response = None\n # check if whitelisted/blacklisted ip\n remote_host = ip_address(request.remote_addr)\n if utils.is_listed(CONFIG['IP_BLACKLIST'], remote_host):\n ret_response = blacklisted()\n return hook_n_respond(request, ret_response)",
" if not utils.is_listed(CONFIG['IP_WHITELIST'], remote_host):\n ret_response = blacklisted()\n return hook_n_respond(request, ret_response)",
" if utils.is_geolocation_listed(CONFIG['GEOLOCATION_BLACKLIST'], remote_host):\n ret_response = blacklisted()\n return hook_n_respond(request, ret_response)",
" # Run \"pre_process\" hook checks\n hook_ret = hooker.EVENTS[\"pre_process\"](\n request=request,\n url_alias=url_alias,\n )\n # In case the hook changed the original request\n url_alias = request.path[1:] # Remove the '/'\n print(\"[*] %s\" % url_alias)\n try:\n behaviour = hook_ret.popitem()[1]\n # Get the behavior from the list and generate its response:\n if behaviour is not None:\n ret_response = behaviours.get(behaviour, abort_404)()\n return hook_n_respond(request, ret_response)\n except KeyError:\n pass",
" # Check if URL Alias exists\n try:\n alias_db_obj = db_handler.get_path(url_alias)\n except KeyError:\n # Non-existent\n ret_response = default_miss()\n return hook_n_respond(request, ret_response)\n except utils.LinkExpired:\n # Existent and expired\n ret_response = on_expired()\n return hook_n_respond(request, ret_response)",
" path = alias_db_obj.path\n # Run the hooks for iconic filenames\n hook_ret = hooker.EVENTS[\"pre_file\"](\n filename=path,\n request=request,\n )\n try:\n iconic_fd = hook_ret.popitem()[1]\n except KeyError:\n iconic_fd = None",
" if iconic_fd:\n print(\n \"[+] Filename '{}' HOOKED! A Custom file is served!\".format(\n alias_db_obj.path\n )\n )\n # If it succeds the returned fd will be served \n ret_fd = iconic_fd\n ret_response = send_file(\n filename_or_fp = ret_fd,\n as_attachment = True,\n attachment_filename = alias_db_obj.attachment,\n mimetype = alias_db_obj.mimetype,\n )\n return hook_n_respond(request, ret_response)",
" # Else the file file system is checked for real files\n print(path, os.path.isfile(path))\n if not os.path.isfile(path): \n # If doensn't exist, 'miss' behaviour is triggered\n ret_response = default_miss()\n return hook_n_respond(request, ret_response)",
" ret_fd = open(path,'rb')\n # hook_ret = hooker.EVENTS[\"post_file\"](\n # filename=path,\n # request=request,\n # fd=ret_fd\n # )",
" ret_response = send_file(\n filename_or_fp = ret_fd,\n as_attachment = True,\n attachment_filename = alias_db_obj.attachment,\n mimetype = alias_db_obj.mimetype,\n )",
" return hook_n_respond(request, ret_response)",
"\ndef hook_n_respond(request, response):\n hook_ret = hooker.EVENTS[\"pre_response\"](\n request=request,\n response=response\n )\n try:\n ret_response_final = hook_ret.popitem()[1]\n except KeyError:\n ret_response_final = response\n return ret_response_final",
"\ndef main(*args, **kwargs):",
" utils.log_spawn(CONFIG['LOG_SPAWN_FILE'], CONFIG['MANAGE_URL_DIR'], CONFIG['PORT'])\n app.run(\n host=CONFIG['IP'],\n port=CONFIG['PORT'],\n debug=os.getenv(\"DEBUG\", False)\n )",
"if __name__==\"__main__\":\n main()"
] |
[
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [120], "buggy_code_start_loc": [3], "filenames": ["app.py"], "fixing_code_end_loc": [120], "fixing_code_start_loc": [3], "message": "The operatorequals/wormnest repository through 0.4.7 on GitHub allows absolute path traversal because the Flask send_file function is used unsafely.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wormnest_project:wormnest:*:*:*:*:*:*:*:*", "matchCriteriaId": "55DE4788-AF76-4775-85A5-735114998211", "versionEndExcluding": null, "versionEndIncluding": "0.4.7", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The operatorequals/wormnest repository through 0.4.7 on GitHub allows absolute path traversal because the Flask send_file function is used unsafely."}, {"lang": "es", "value": "El repositorio operatorequals/wormnest versiones hasta 0.4.7, en GitHub, permite un salto de ruta absoluto porque la funci\u00f3n send_file de Flask es usada de forma no segura"}], "evaluatorComment": null, "id": "CVE-2022-31502", "lastModified": "2022-07-15T12:09:40.533", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.4, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 9.3, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:N/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 4.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-07-11T01:15:08.083", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/github/securitylab/issues/669#issuecomment-1117265726"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/operatorequals/wormnest/commit/2dfe96fc2570586ac487b399ac20d41b3c114861"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/operatorequals/wormnest/commit/2dfe96fc2570586ac487b399ac20d41b3c114861"}, "type": "CWE-22"}
| 257
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"#!/bin/env python\nfrom flask import Flask",
"from flask import flash,request,send_file,send_from_directory,redirect,render_template, abort, safe_join",
"\nfrom werkzeug.utils import secure_filename\nfrom ipaddress import ip_address, ip_network\nimport urllib.request",
"import os\nimport random",
"import hooker",
"hooker.EVENTS.append(\"pre_process\",\n help=\"Before any processing of the URL alias starts. Useful for UA filters, blacklists, etc\")\nhooker.EVENTS.append(\"pre_file\",\n help=\"Before the alias resolves to a file\")\nhooker.EVENTS.append(\"pre_response\",\n help=\"Before the created request is sent\")",
"import wormnest.db_handler as db_handler\nimport wormnest.utils as utils",
"'''\nTo run the App:\npython3 app.py\n'''\napp = Flask(__name__)",
"CONFIG = utils.parse_config()",
"app.config['UPLOAD_FOLDER'] = CONFIG['SRV_DIR']\nprint(CONFIG['IP_WHITELIST'])\n# sys.exit(10)",
"def get_random_alias(length=None):\n assert CONFIG['ALIAS_DIGITS_MIN'] <= CONFIG['ALIAS_DIGITS_MAX']\n if length == None:\n length = random.randint(CONFIG['ALIAS_DIGITS_MIN'], CONFIG['ALIAS_DIGITS_MAX'])\n return utils.randomword(length)",
"\ndef redirect_away():\n return redirect(CONFIG['REDIRECT_URL'], code=302)",
"def abort_404():\n return abort(404)",
"behaviours = {\n 'abort' : abort_404,\n 'redir' : redirect_away,\n}",
"default_miss = behaviours.get(CONFIG['MISS'],'abort')\non_expired = behaviours.get(CONFIG['EXPIRE'],'abort')\nblacklisted = behaviours.get(CONFIG['BLACKLISTED'],'abort')",
"\n@app.after_request\ndef add_header(response):\n response.headers['Cache-Control'] = 'no-store'\n del response.headers['Expires']\n response.headers['Server'] = CONFIG['SERVER_HEADER']\n response.headers['X-Content-Type-Options'] = \"nosniff\"\n del response.headers['Date']",
" return response",
"\n@app.route('/%s/' % CONFIG['MANAGE_URL_DIR'])\ndef show_manage():\n return render_template(\n \"manage_help.html\",\n manage_url = request.base_url\n )",
"@app.route('/%s/load_defaults' % CONFIG['MANAGE_URL_DIR'])\ndef load_defaults():\n add_url_template = \"http://127.0.0.1:{port}/{man}/add?path={path}&alias={alias}&unchecked=True\"\n try:\n if CONFIG['DEFAULT_PATHS_FILE']:\n print(\"[+] Importing defaults from '{}'\".format(CONFIG['DEFAULT_PATHS_FILE']))\n import json\n with open(CONFIG['DEFAULT_PATHS_FILE']) as url_defaults:\n defaults_url_dict = json.load(url_defaults)\n for path, url_params in defaults_url_dict.items():\n print(path, url_params)\n alias = url_params['alias']\n filename = url_params.get('filename',None)\n print (filename)\n if filename:\n add_url_template += '&filename={filename}'\n urllib.request.urlopen(add_url_template.format(\n port=CONFIG['PORT'],\n man=CONFIG['MANAGE_URL_DIR'],\n path=path,\n alias=alias,\n filename=filename,\n )\n )\n return \"<pre>{}</pre>\".format(\n json.dumps(defaults_url_dict, indent=2)\n )\n except Exception as e:\n return render_template(\"custom_error.html\",error_msg=str(e))",
"@app.route(\n '/%s/list/' % CONFIG['MANAGE_URL_DIR'],\n defaults={'req_path': ''}\n )",
"@app.route('/%s/list/<path:req_path>' % CONFIG['MANAGE_URL_DIR'])\ndef dir_listing(req_path):\n '''\n Found here:\nhttps://stackoverflow.com/questions/23718236/python-flask-browsing-through-directory-with-files\n '''\n # Joining the base and the requested path",
" abs_path = safe_join(CONFIG['SRV_DIR'], req_path)",
"\n # Return 404 if path doesn't exist\n if not os.path.exists(abs_path):\n return abort(404)",
" # Check if path is a file and serve\n if os.path.isfile(abs_path):\n return send_file(abs_path)",
" # Show directory contents\n files = os.listdir(abs_path)\n full_paths = []\n for f in files:\n full_paths.append(\n (f, os.path.join(request.base_url, f))\n )\n # print (full_paths)\n add_url_link = \"%s%s/add\" % (request.url_root, CONFIG['MANAGE_URL_DIR'])\n return render_template('file.html',\n files=full_paths,\n add_url=add_url_link\n )",
"\n@app.route('/%s/add' % CONFIG['MANAGE_URL_DIR'])\ndef add_url():",
" path = request.args.get(\"path\")\n expires = request.args.get(\"clicks\", -1)\n alias = request.args.get(\"alias\", get_random_alias())\n attach_name = request.args.get(\"filename\")\n mimetype = request.args.get(\"mime\", None)\n unchecked_path = request.args.get(\"unchecked\", False)\n if not request.args:\n return render_template(\n 'add_help.html', \n )\n try:\n original_filename = path.split('/')[-1]\n original_extension = original_filename.split('.')[-1]\n except Exception as e:\n return render_template(\n 'custom_error.html', \n error_msg=\"The 'path' variable does not validate\"\n )",
" if original_filename == original_extension:\n # If they are the same, there is no extension\n original_extension = ''\n else:\n original_extension = '.' + original_extension",
" if not attach_name:",
" if not CONFIG['DEFAULT_FILENAME']:\n # The filename is the path's filename\n attach_name = original_filename\n else:\n attach_name = CONFIG['DEFAULT_FILENAME']\n if CONFIG['USE_ORIGINAL_EXTENSION']:\n attach_name += original_extension",
" path = os.path.join(CONFIG['SRV_DIR'], path)\n if not os.path.isfile(path) and not unchecked_path:\n return render_template(\n 'custom_error.html', \n error_msg=\"The path '{}' is NOT a file\".format(path)\n )",
" try:\n if expires is not None: \n int(expires)\n except:\n return render_template(\n 'custom_error.html', \n error_msg=\"Parameter 'clicks' must be positive Integer\"\n )\n try:\n db_handler.add_url(\n path, alias, expires,\n attachment = attach_name,\n mimetype = mimetype\n )\n except Exception as e:\n print (e)\n err = \"Error adding alias '{}'' for path '{}'\".format(alias, path)\n return render_template(\n 'custom_error.html', \n error_msg=err\n )\n full_link = request.url_root + alias\n return render_template(\n 'added_alias.html', \n alias=alias,\n path=path,\n clicks=expires,\n link=full_link\n )",
"@app.route('/%s/del' % CONFIG['MANAGE_URL_DIR'], methods=[\"GET\", \"POST\"])\ndef del_url():\n alias = request.args.get(\"alias\", None) \n if alias is None:\n alias = request.form.get(\"alias\", None)\n if alias is None:\n return render_template(\n 'del_help.html'\n )\n try:\n deleted = db_handler.del_url(alias)\n except KeyError:\n deleted = False\n return \"Deleted '/%s'\" % alias if deleted else \"NOT deleted\"",
"@app.route('/%s/config' % CONFIG['MANAGE_URL_DIR'])\ndef show_config(path=None):\n return render_template('show_config.html', entries=CONFIG)\n \n@app.route('/%s/show' % CONFIG['MANAGE_URL_DIR'])\ndef show_all(path=None):\n entries = db_handler.get_all(path)\n return render_template(\n 'show.html', # Fix show.html to contain mimetypes\n entries = entries\n )",
"@app.route(\n '/%s/upload' % CONFIG['MANAGE_URL_DIR'],\n methods=['POST', 'GET']\n )\ndef file_upload():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n return render_template(\n 'upload_page.html',\n manage_url = CONFIG['MANAGE_URL_DIR'],\n message = \"No file submitted\"\n )\n file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n return render_template(\n 'upload_page.html',\n manage_url = CONFIG['MANAGE_URL_DIR'],\n message = \"No filename submitted\"\n )\n if file:\n filename = request.form.get('filename', file.filename)\n filename = secure_filename(filename)\n try:\n file.save(\n os.path.join(\n app.config['UPLOAD_FOLDER'],\n filename\n )\n )\n except IsADirectoryError:\n return render_template(\n 'upload_page.html',\n manage_url = CONFIG['MANAGE_URL_DIR'],\n message = \"Filename exists\"\n )",
" if request.form.get(\"create_alias\",\n default = False,\n type = bool):\n alias_name = request.form.get(\"alias\", default=None)\n deliver_filename = request.form.get(\"deliver_filename\", default=None)\n return redirect(\n \"/{manage_url}/add?path={filepath}{alias}{filename}\".format(\n manage_url = CONFIG['MANAGE_URL_DIR'],\n filepath = filename,\n alias=\"\" if not alias_name else \"&alias=%s\" % alias_name,\n filename=\"\" if not deliver_filename else \"&filename=%s\" % deliver_filename,\n )\n )\n return render_template(\n 'upload_page.html',\n manage_url = CONFIG['MANAGE_URL_DIR'],\n message = \"File '{}' uploaded successfully!\".format(filename)\n )\n return render_template(\n 'upload_page.html',\n manage_url = CONFIG['MANAGE_URL_DIR'],\n )",
"# Default behaviour - Serve all non \"/manage\" paths\n@app.route('/<path:url_alias>', methods=['POST', 'GET'])\n@app.route('/', defaults={'url_alias': ''}, methods=['POST', 'GET'])\ndef resolve_url(url_alias):\n ret_response = None\n # check if whitelisted/blacklisted ip\n remote_host = ip_address(request.remote_addr)\n if utils.is_listed(CONFIG['IP_BLACKLIST'], remote_host):\n ret_response = blacklisted()\n return hook_n_respond(request, ret_response)",
" if not utils.is_listed(CONFIG['IP_WHITELIST'], remote_host):\n ret_response = blacklisted()\n return hook_n_respond(request, ret_response)",
" if utils.is_geolocation_listed(CONFIG['GEOLOCATION_BLACKLIST'], remote_host):\n ret_response = blacklisted()\n return hook_n_respond(request, ret_response)",
" # Run \"pre_process\" hook checks\n hook_ret = hooker.EVENTS[\"pre_process\"](\n request=request,\n url_alias=url_alias,\n )\n # In case the hook changed the original request\n url_alias = request.path[1:] # Remove the '/'\n print(\"[*] %s\" % url_alias)\n try:\n behaviour = hook_ret.popitem()[1]\n # Get the behavior from the list and generate its response:\n if behaviour is not None:\n ret_response = behaviours.get(behaviour, abort_404)()\n return hook_n_respond(request, ret_response)\n except KeyError:\n pass",
" # Check if URL Alias exists\n try:\n alias_db_obj = db_handler.get_path(url_alias)\n except KeyError:\n # Non-existent\n ret_response = default_miss()\n return hook_n_respond(request, ret_response)\n except utils.LinkExpired:\n # Existent and expired\n ret_response = on_expired()\n return hook_n_respond(request, ret_response)",
" path = alias_db_obj.path\n # Run the hooks for iconic filenames\n hook_ret = hooker.EVENTS[\"pre_file\"](\n filename=path,\n request=request,\n )\n try:\n iconic_fd = hook_ret.popitem()[1]\n except KeyError:\n iconic_fd = None",
" if iconic_fd:\n print(\n \"[+] Filename '{}' HOOKED! A Custom file is served!\".format(\n alias_db_obj.path\n )\n )\n # If it succeds the returned fd will be served \n ret_fd = iconic_fd\n ret_response = send_file(\n filename_or_fp = ret_fd,\n as_attachment = True,\n attachment_filename = alias_db_obj.attachment,\n mimetype = alias_db_obj.mimetype,\n )\n return hook_n_respond(request, ret_response)",
" # Else the file file system is checked for real files\n print(path, os.path.isfile(path))\n if not os.path.isfile(path): \n # If doensn't exist, 'miss' behaviour is triggered\n ret_response = default_miss()\n return hook_n_respond(request, ret_response)",
" ret_fd = open(path,'rb')\n # hook_ret = hooker.EVENTS[\"post_file\"](\n # filename=path,\n # request=request,\n # fd=ret_fd\n # )",
" ret_response = send_file(\n filename_or_fp = ret_fd,\n as_attachment = True,\n attachment_filename = alias_db_obj.attachment,\n mimetype = alias_db_obj.mimetype,\n )",
" return hook_n_respond(request, ret_response)",
"\ndef hook_n_respond(request, response):\n hook_ret = hooker.EVENTS[\"pre_response\"](\n request=request,\n response=response\n )\n try:\n ret_response_final = hook_ret.popitem()[1]\n except KeyError:\n ret_response_final = response\n return ret_response_final",
"\ndef main(*args, **kwargs):",
" utils.log_spawn(CONFIG['LOG_SPAWN_FILE'], CONFIG['MANAGE_URL_DIR'], CONFIG['PORT'])\n app.run(\n host=CONFIG['IP'],\n port=CONFIG['PORT'],\n debug=os.getenv(\"DEBUG\", False)\n )",
"if __name__==\"__main__\":\n main()"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [120], "buggy_code_start_loc": [3], "filenames": ["app.py"], "fixing_code_end_loc": [120], "fixing_code_start_loc": [3], "message": "The operatorequals/wormnest repository through 0.4.7 on GitHub allows absolute path traversal because the Flask send_file function is used unsafely.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wormnest_project:wormnest:*:*:*:*:*:*:*:*", "matchCriteriaId": "55DE4788-AF76-4775-85A5-735114998211", "versionEndExcluding": null, "versionEndIncluding": "0.4.7", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The operatorequals/wormnest repository through 0.4.7 on GitHub allows absolute path traversal because the Flask send_file function is used unsafely."}, {"lang": "es", "value": "El repositorio operatorequals/wormnest versiones hasta 0.4.7, en GitHub, permite un salto de ruta absoluto porque la funci\u00f3n send_file de Flask es usada de forma no segura"}], "evaluatorComment": null, "id": "CVE-2022-31502", "lastModified": "2022-07-15T12:09:40.533", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.4, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 9.3, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:N/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 4.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-07-11T01:15:08.083", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/github/securitylab/issues/669#issuecomment-1117265726"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/operatorequals/wormnest/commit/2dfe96fc2570586ac487b399ac20d41b3c114861"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/operatorequals/wormnest/commit/2dfe96fc2570586ac487b399ac20d41b3c114861"}, "type": "CWE-22"}
| 257
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Copyright 2014 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License, version 2.0 (the\n * \"License\"); you may not use this file except in compliance with the License. You may obtain a\n * copy of the License at:\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\npackage io.netty.handler.codec.http2;",
"import io.netty.buffer.ByteBuf;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.handler.codec.http.HttpHeaderNames;\nimport io.netty.handler.codec.http.HttpStatusClass;\nimport io.netty.handler.codec.http.HttpUtil;\nimport io.netty.handler.codec.http2.Http2Connection.Endpoint;\nimport io.netty.util.internal.SystemPropertyUtil;\nimport io.netty.util.internal.UnstableApi;\nimport io.netty.util.internal.logging.InternalLogger;\nimport io.netty.util.internal.logging.InternalLoggerFactory;",
"import java.util.List;",
"import static io.netty.handler.codec.http.HttpStatusClass.INFORMATIONAL;\nimport static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT;\nimport static io.netty.handler.codec.http2.Http2Error.INTERNAL_ERROR;\nimport static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;\nimport static io.netty.handler.codec.http2.Http2Error.STREAM_CLOSED;\nimport static io.netty.handler.codec.http2.Http2Exception.connectionError;\nimport static io.netty.handler.codec.http2.Http2Exception.streamError;\nimport static io.netty.handler.codec.http2.Http2PromisedRequestVerifier.ALWAYS_VERIFY;\nimport static io.netty.handler.codec.http2.Http2Stream.State.CLOSED;\nimport static io.netty.handler.codec.http2.Http2Stream.State.HALF_CLOSED_REMOTE;\nimport static io.netty.util.internal.ObjectUtil.checkNotNull;\nimport static java.lang.Integer.MAX_VALUE;\nimport static java.lang.Math.min;",
"/**\n * Provides the default implementation for processing inbound frame events and delegates to a\n * {@link Http2FrameListener}\n * <p>\n * This class will read HTTP/2 frames and delegate the events to a {@link Http2FrameListener}\n * <p>\n * This interface enforces inbound flow control functionality through\n * {@link Http2LocalFlowController}\n */\n@UnstableApi\npublic class DefaultHttp2ConnectionDecoder implements Http2ConnectionDecoder {\n private static final boolean VALIDATE_CONTENT_LENGTH =\n SystemPropertyUtil.getBoolean(\"io.netty.http2.validateContentLength\", true);\n private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultHttp2ConnectionDecoder.class);\n private Http2FrameListener internalFrameListener = new PrefaceFrameListener();\n private final Http2Connection connection;\n private Http2LifecycleManager lifecycleManager;\n private final Http2ConnectionEncoder encoder;\n private final Http2FrameReader frameReader;\n private Http2FrameListener listener;\n private final Http2PromisedRequestVerifier requestVerifier;\n private final Http2SettingsReceivedConsumer settingsReceivedConsumer;\n private final boolean autoAckPing;\n private final Http2Connection.PropertyKey contentLengthKey;",
" public DefaultHttp2ConnectionDecoder(Http2Connection connection,\n Http2ConnectionEncoder encoder,\n Http2FrameReader frameReader) {\n this(connection, encoder, frameReader, ALWAYS_VERIFY);\n }",
" public DefaultHttp2ConnectionDecoder(Http2Connection connection,\n Http2ConnectionEncoder encoder,\n Http2FrameReader frameReader,\n Http2PromisedRequestVerifier requestVerifier) {\n this(connection, encoder, frameReader, requestVerifier, true);\n }",
" /**\n * Create a new instance.\n * @param connection The {@link Http2Connection} associated with this decoder.\n * @param encoder The {@link Http2ConnectionEncoder} associated with this decoder.\n * @param frameReader Responsible for reading/parsing the raw frames. As opposed to this object which applies\n * h2 semantics on top of the frames.\n * @param requestVerifier Determines if push promised streams are valid.\n * @param autoAckSettings {@code false} to disable automatically applying and sending settings acknowledge frame.\n * The {@code Http2ConnectionEncoder} is expected to be an instance of {@link Http2SettingsReceivedConsumer} and\n * will apply the earliest received but not yet ACKed SETTINGS when writing the SETTINGS ACKs.\n * {@code true} to enable automatically applying and sending settings acknowledge frame.\n */\n public DefaultHttp2ConnectionDecoder(Http2Connection connection,\n Http2ConnectionEncoder encoder,\n Http2FrameReader frameReader,\n Http2PromisedRequestVerifier requestVerifier,\n boolean autoAckSettings) {\n this(connection, encoder, frameReader, requestVerifier, autoAckSettings, true);\n }",
" /**\n * Create a new instance.\n * @param connection The {@link Http2Connection} associated with this decoder.\n * @param encoder The {@link Http2ConnectionEncoder} associated with this decoder.\n * @param frameReader Responsible for reading/parsing the raw frames. As opposed to this object which applies\n * h2 semantics on top of the frames.\n * @param requestVerifier Determines if push promised streams are valid.\n * @param autoAckSettings {@code false} to disable automatically applying and sending settings acknowledge frame.\n * The {@code Http2ConnectionEncoder} is expected to be an instance of\n * {@link Http2SettingsReceivedConsumer} and will apply the earliest received but not yet\n * ACKed SETTINGS when writing the SETTINGS ACKs. {@code true} to enable automatically\n * applying and sending settings acknowledge frame.\n * @param autoAckPing {@code false} to disable automatically sending ping acknowledge frame. {@code true} to enable\n * automatically sending ping ack frame.\n */\n public DefaultHttp2ConnectionDecoder(Http2Connection connection,\n Http2ConnectionEncoder encoder,\n Http2FrameReader frameReader,\n Http2PromisedRequestVerifier requestVerifier,\n boolean autoAckSettings,\n boolean autoAckPing) {\n this.autoAckPing = autoAckPing;\n if (autoAckSettings) {\n settingsReceivedConsumer = null;\n } else {\n if (!(encoder instanceof Http2SettingsReceivedConsumer)) {\n throw new IllegalArgumentException(\"disabling autoAckSettings requires the encoder to be a \" +\n Http2SettingsReceivedConsumer.class);\n }\n settingsReceivedConsumer = (Http2SettingsReceivedConsumer) encoder;\n }\n this.connection = checkNotNull(connection, \"connection\");\n contentLengthKey = this.connection.newKey();\n this.frameReader = checkNotNull(frameReader, \"frameReader\");\n this.encoder = checkNotNull(encoder, \"encoder\");\n this.requestVerifier = checkNotNull(requestVerifier, \"requestVerifier\");\n if (connection.local().flowController() == null) {\n connection.local().flowController(new DefaultHttp2LocalFlowController(connection));\n }\n connection.local().flowController().frameWriter(encoder.frameWriter());\n }",
" @Override\n public void lifecycleManager(Http2LifecycleManager lifecycleManager) {\n this.lifecycleManager = checkNotNull(lifecycleManager, \"lifecycleManager\");\n }",
" @Override\n public Http2Connection connection() {\n return connection;\n }",
" @Override\n public final Http2LocalFlowController flowController() {\n return connection.local().flowController();\n }",
" @Override\n public void frameListener(Http2FrameListener listener) {\n this.listener = checkNotNull(listener, \"listener\");\n }",
" @Override\n public Http2FrameListener frameListener() {\n return listener;\n }",
" // Visible for testing\n Http2FrameListener internalFrameListener() {\n return internalFrameListener;\n }",
" @Override\n public boolean prefaceReceived() {\n return FrameReadListener.class == internalFrameListener.getClass();\n }",
" @Override\n public void decodeFrame(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Http2Exception {\n frameReader.readFrame(ctx, in, internalFrameListener);\n }",
" @Override\n public Http2Settings localSettings() {\n Http2Settings settings = new Http2Settings();\n Http2FrameReader.Configuration config = frameReader.configuration();\n Http2HeadersDecoder.Configuration headersConfig = config.headersConfiguration();\n Http2FrameSizePolicy frameSizePolicy = config.frameSizePolicy();\n settings.initialWindowSize(flowController().initialWindowSize());\n settings.maxConcurrentStreams(connection.remote().maxActiveStreams());\n settings.headerTableSize(headersConfig.maxHeaderTableSize());\n settings.maxFrameSize(frameSizePolicy.maxFrameSize());\n settings.maxHeaderListSize(headersConfig.maxHeaderListSize());\n if (!connection.isServer()) {\n // Only set the pushEnabled flag if this is a client endpoint.\n settings.pushEnabled(connection.local().allowPushTo());\n }\n return settings;\n }",
" @Override\n public void close() {\n frameReader.close();\n }",
" /**\n * Calculate the threshold in bytes which should trigger a {@code GO_AWAY} if a set of headers exceeds this amount.\n * @param maxHeaderListSize\n * <a href=\"https://tools.ietf.org/html/rfc7540#section-6.5.2\">SETTINGS_MAX_HEADER_LIST_SIZE</a> for the local\n * endpoint.\n * @return the threshold in bytes which should trigger a {@code GO_AWAY} if a set of headers exceeds this amount.\n */\n protected long calculateMaxHeaderListSizeGoAway(long maxHeaderListSize) {\n return Http2CodecUtil.calculateMaxHeaderListSizeGoAway(maxHeaderListSize);\n }",
" private int unconsumedBytes(Http2Stream stream) {\n return flowController().unconsumedBytes(stream);\n }",
" void onGoAwayRead0(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)\n throws Http2Exception {\n listener.onGoAwayRead(ctx, lastStreamId, errorCode, debugData);\n connection.goAwayReceived(lastStreamId, errorCode, debugData);\n }",
" void onUnknownFrame0(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,\n ByteBuf payload) throws Http2Exception {\n listener.onUnknownFrame(ctx, frameType, streamId, flags, payload);\n }",
" // See https://tools.ietf.org/html/rfc7540#section-8.1.2.6\n private void verifyContentLength(Http2Stream stream, int data, boolean isEnd) throws Http2Exception {\n if (!VALIDATE_CONTENT_LENGTH) {\n return;\n }\n ContentLength contentLength = stream.getProperty(contentLengthKey);\n if (contentLength != null) {\n try {\n contentLength.increaseReceivedBytes(connection.isServer(), stream.id(), data, isEnd);\n } finally {\n if (isEnd) {\n stream.removeProperty(contentLengthKey);\n }\n }\n }\n }",
" /**\n * Handles all inbound frames from the network.\n */\n private final class FrameReadListener implements Http2FrameListener {\n @Override\n public int onDataRead(final ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,\n boolean endOfStream) throws Http2Exception {\n Http2Stream stream = connection.stream(streamId);\n Http2LocalFlowController flowController = flowController();\n int readable = data.readableBytes();\n int bytesToReturn = readable + padding;",
" final boolean shouldIgnore;\n try {\n shouldIgnore = shouldIgnoreHeadersOrDataFrame(ctx, streamId, stream, \"DATA\");\n } catch (Http2Exception e) {\n // Ignoring this frame. We still need to count the frame towards the connection flow control\n // window, but we immediately mark all bytes as consumed.\n flowController.receiveFlowControlledFrame(stream, data, padding, endOfStream);\n flowController.consumeBytes(stream, bytesToReturn);\n throw e;\n } catch (Throwable t) {\n throw connectionError(INTERNAL_ERROR, t, \"Unhandled error on data stream id %d\", streamId);\n }",
" if (shouldIgnore) {\n // Ignoring this frame. We still need to count the frame towards the connection flow control\n // window, but we immediately mark all bytes as consumed.\n flowController.receiveFlowControlledFrame(stream, data, padding, endOfStream);\n flowController.consumeBytes(stream, bytesToReturn);",
" // Verify that the stream may have existed after we apply flow control.\n verifyStreamMayHaveExisted(streamId);",
" // All bytes have been consumed.\n return bytesToReturn;\n }\n Http2Exception error = null;\n switch (stream.state()) {\n case OPEN:\n case HALF_CLOSED_LOCAL:\n break;\n case HALF_CLOSED_REMOTE:\n case CLOSED:\n error = streamError(stream.id(), STREAM_CLOSED, \"Stream %d in unexpected state: %s\",\n stream.id(), stream.state());\n break;\n default:\n error = streamError(stream.id(), PROTOCOL_ERROR,\n \"Stream %d in unexpected state: %s\", stream.id(), stream.state());\n break;\n }",
" int unconsumedBytes = unconsumedBytes(stream);\n try {\n flowController.receiveFlowControlledFrame(stream, data, padding, endOfStream);\n // Update the unconsumed bytes after flow control is applied.\n unconsumedBytes = unconsumedBytes(stream);",
" // If the stream is in an invalid state to receive the frame, throw the error.\n if (error != null) {\n throw error;\n }",
" verifyContentLength(stream, readable, endOfStream);",
" // Call back the application and retrieve the number of bytes that have been\n // immediately processed.\n bytesToReturn = listener.onDataRead(ctx, streamId, data, padding, endOfStream);",
" if (endOfStream) {\n lifecycleManager.closeStreamRemote(stream, ctx.newSucceededFuture());\n }",
" return bytesToReturn;\n } catch (Http2Exception e) {\n // If an exception happened during delivery, the listener may have returned part\n // of the bytes before the error occurred. If that's the case, subtract that from\n // the total processed bytes so that we don't return too many bytes.\n int delta = unconsumedBytes - unconsumedBytes(stream);\n bytesToReturn -= delta;\n throw e;\n } catch (RuntimeException e) {\n // If an exception happened during delivery, the listener may have returned part\n // of the bytes before the error occurred. If that's the case, subtract that from\n // the total processed bytes so that we don't return too many bytes.\n int delta = unconsumedBytes - unconsumedBytes(stream);\n bytesToReturn -= delta;\n throw e;\n } finally {\n // If appropriate, return the processed bytes to the flow controller.\n flowController.consumeBytes(stream, bytesToReturn);\n }\n }",
" @Override\n public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,\n boolean endOfStream) throws Http2Exception {\n onHeadersRead(ctx, streamId, headers, 0, DEFAULT_PRIORITY_WEIGHT, false, padding, endOfStream);\n }",
" @Override\n public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency,\n short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception {\n Http2Stream stream = connection.stream(streamId);\n boolean allowHalfClosedRemote = false;",
"",
" if (stream == null && !connection.streamMayHaveExisted(streamId)) {\n stream = connection.remote().createStream(streamId, endOfStream);\n // Allow the state to be HALF_CLOSE_REMOTE if we're creating it in that state.\n allowHalfClosedRemote = stream.state() == HALF_CLOSED_REMOTE;",
"",
" }",
" if (shouldIgnoreHeadersOrDataFrame(ctx, streamId, stream, \"HEADERS\")) {\n return;\n }",
" boolean isInformational = !connection.isServer() &&\n HttpStatusClass.valueOf(headers.status()) == INFORMATIONAL;\n if ((isInformational || !endOfStream) && stream.isHeadersReceived() || stream.isTrailersReceived()) {\n throw streamError(streamId, PROTOCOL_ERROR,\n \"Stream %d received too many headers EOS: %s state: %s\",\n streamId, endOfStream, stream.state());\n }",
" switch (stream.state()) {\n case RESERVED_REMOTE:\n stream.open(endOfStream);\n break;\n case OPEN:\n case HALF_CLOSED_LOCAL:\n // Allowed to receive headers in these states.\n break;\n case HALF_CLOSED_REMOTE:\n if (!allowHalfClosedRemote) {\n throw streamError(stream.id(), STREAM_CLOSED, \"Stream %d in unexpected state: %s\",\n stream.id(), stream.state());\n }\n break;\n case CLOSED:\n throw streamError(stream.id(), STREAM_CLOSED, \"Stream %d in unexpected state: %s\",\n stream.id(), stream.state());\n default:\n // Connection error.\n throw connectionError(PROTOCOL_ERROR, \"Stream %d in unexpected state: %s\", stream.id(),\n stream.state());\n }\n",
" if (!stream.isHeadersReceived()) {",
" // extract the content-length header\n List<? extends CharSequence> contentLength = headers.getAll(HttpHeaderNames.CONTENT_LENGTH);\n if (contentLength != null && !contentLength.isEmpty()) {\n try {\n long cLength = HttpUtil.normalizeAndGetContentLength(contentLength, false, true);\n if (cLength != -1) {\n headers.setLong(HttpHeaderNames.CONTENT_LENGTH, cLength);\n stream.setProperty(contentLengthKey, new ContentLength(cLength));\n }\n } catch (IllegalArgumentException e) {\n throw streamError(stream.id(), PROTOCOL_ERROR, e,\n \"Multiple content-length headers received\");\n }\n }\n }",
" stream.headersReceived(isInformational);\n verifyContentLength(stream, 0, endOfStream);\n encoder.flowController().updateDependencyTree(streamId, streamDependency, weight, exclusive);\n listener.onHeadersRead(ctx, streamId, headers, streamDependency,\n weight, exclusive, padding, endOfStream);\n // If the headers completes this stream, close it.\n if (endOfStream) {\n lifecycleManager.closeStreamRemote(stream, ctx.newSucceededFuture());\n }\n }",
" @Override\n public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight,\n boolean exclusive) throws Http2Exception {\n encoder.flowController().updateDependencyTree(streamId, streamDependency, weight, exclusive);",
" listener.onPriorityRead(ctx, streamId, streamDependency, weight, exclusive);\n }",
" @Override\n public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) throws Http2Exception {\n Http2Stream stream = connection.stream(streamId);\n if (stream == null) {\n verifyStreamMayHaveExisted(streamId);\n return;\n }",
" switch(stream.state()) {\n case IDLE:\n throw connectionError(PROTOCOL_ERROR, \"RST_STREAM received for IDLE stream %d\", streamId);\n case CLOSED:\n return; // RST_STREAM frames must be ignored for closed streams.\n default:\n break;\n }",
" listener.onRstStreamRead(ctx, streamId, errorCode);",
" lifecycleManager.closeStream(stream, ctx.newSucceededFuture());\n }",
" @Override\n public void onSettingsAckRead(ChannelHandlerContext ctx) throws Http2Exception {\n // Apply oldest outstanding local settings here. This is a synchronization point between endpoints.\n Http2Settings settings = encoder.pollSentSettings();",
" if (settings != null) {\n applyLocalSettings(settings);\n }",
" listener.onSettingsAckRead(ctx);\n }",
" /**\n * Applies settings sent from the local endpoint.\n * <p>\n * This method is only called after the local settings have been acknowledged from the remote endpoint.\n */\n private void applyLocalSettings(Http2Settings settings) throws Http2Exception {\n Boolean pushEnabled = settings.pushEnabled();\n final Http2FrameReader.Configuration config = frameReader.configuration();\n final Http2HeadersDecoder.Configuration headerConfig = config.headersConfiguration();\n final Http2FrameSizePolicy frameSizePolicy = config.frameSizePolicy();\n if (pushEnabled != null) {\n if (connection.isServer()) {\n throw connectionError(PROTOCOL_ERROR, \"Server sending SETTINGS frame with ENABLE_PUSH specified\");\n }\n connection.local().allowPushTo(pushEnabled);\n }",
" Long maxConcurrentStreams = settings.maxConcurrentStreams();\n if (maxConcurrentStreams != null) {\n connection.remote().maxActiveStreams((int) min(maxConcurrentStreams, MAX_VALUE));\n }",
" Long headerTableSize = settings.headerTableSize();\n if (headerTableSize != null) {\n headerConfig.maxHeaderTableSize(headerTableSize);\n }",
" Long maxHeaderListSize = settings.maxHeaderListSize();\n if (maxHeaderListSize != null) {\n headerConfig.maxHeaderListSize(maxHeaderListSize, calculateMaxHeaderListSizeGoAway(maxHeaderListSize));\n }",
" Integer maxFrameSize = settings.maxFrameSize();\n if (maxFrameSize != null) {\n frameSizePolicy.maxFrameSize(maxFrameSize);\n }",
" Integer initialWindowSize = settings.initialWindowSize();\n if (initialWindowSize != null) {\n flowController().initialWindowSize(initialWindowSize);\n }\n }",
" @Override\n public void onSettingsRead(final ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception {\n if (settingsReceivedConsumer == null) {\n // Acknowledge receipt of the settings. We should do this before we process the settings to ensure our\n // remote peer applies these settings before any subsequent frames that we may send which depend upon\n // these new settings. See https://github.com/netty/netty/issues/6520.\n encoder.writeSettingsAck(ctx, ctx.newPromise());",
" encoder.remoteSettings(settings);\n } else {\n settingsReceivedConsumer.consumeReceivedSettings(settings);\n }",
" listener.onSettingsRead(ctx, settings);\n }",
" @Override\n public void onPingRead(ChannelHandlerContext ctx, long data) throws Http2Exception {\n if (autoAckPing) {\n // Send an ack back to the remote client.\n encoder.writePing(ctx, true, data, ctx.newPromise());\n }\n listener.onPingRead(ctx, data);\n }",
" @Override\n public void onPingAckRead(ChannelHandlerContext ctx, long data) throws Http2Exception {\n listener.onPingAckRead(ctx, data);\n }",
" @Override\n public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,\n Http2Headers headers, int padding) throws Http2Exception {\n // A client cannot push.\n if (connection().isServer()) {\n throw connectionError(PROTOCOL_ERROR, \"A client cannot push.\");\n }",
" Http2Stream parentStream = connection.stream(streamId);",
" if (shouldIgnoreHeadersOrDataFrame(ctx, streamId, parentStream, \"PUSH_PROMISE\")) {\n return;\n }",
" switch (parentStream.state()) {\n case OPEN:\n case HALF_CLOSED_LOCAL:\n // Allowed to receive push promise in these states.\n break;\n default:\n // Connection error.\n throw connectionError(PROTOCOL_ERROR,\n \"Stream %d in unexpected state for receiving push promise: %s\",\n parentStream.id(), parentStream.state());\n }",
" if (!requestVerifier.isAuthoritative(ctx, headers)) {\n throw streamError(promisedStreamId, PROTOCOL_ERROR,\n \"Promised request on stream %d for promised stream %d is not authoritative\",\n streamId, promisedStreamId);\n }\n if (!requestVerifier.isCacheable(headers)) {\n throw streamError(promisedStreamId, PROTOCOL_ERROR,\n \"Promised request on stream %d for promised stream %d is not known to be cacheable\",\n streamId, promisedStreamId);\n }\n if (!requestVerifier.isSafe(headers)) {\n throw streamError(promisedStreamId, PROTOCOL_ERROR,\n \"Promised request on stream %d for promised stream %d is not known to be safe\",\n streamId, promisedStreamId);\n }",
" // Reserve the push stream based with a priority based on the current stream's priority.\n connection.remote().reservePushStream(promisedStreamId, parentStream);",
" listener.onPushPromiseRead(ctx, streamId, promisedStreamId, headers, padding);\n }",
" @Override\n public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)\n throws Http2Exception {\n onGoAwayRead0(ctx, lastStreamId, errorCode, debugData);\n }",
" @Override\n public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement)\n throws Http2Exception {\n Http2Stream stream = connection.stream(streamId);\n if (stream == null || stream.state() == CLOSED || streamCreatedAfterGoAwaySent(streamId)) {\n // Ignore this frame.\n verifyStreamMayHaveExisted(streamId);\n return;\n }",
" // Update the outbound flow control window.\n encoder.flowController().incrementWindowSize(stream, windowSizeIncrement);",
" listener.onWindowUpdateRead(ctx, streamId, windowSizeIncrement);\n }",
" @Override\n public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,\n ByteBuf payload) throws Http2Exception {\n onUnknownFrame0(ctx, frameType, streamId, flags, payload);\n }",
" /**\n * Helper method to determine if a frame that has the semantics of headers or data should be ignored for the\n * {@code stream} (which may be {@code null}) associated with {@code streamId}.\n */\n private boolean shouldIgnoreHeadersOrDataFrame(ChannelHandlerContext ctx, int streamId, Http2Stream stream,\n String frameName) throws Http2Exception {\n if (stream == null) {\n if (streamCreatedAfterGoAwaySent(streamId)) {\n logger.info(\"{} ignoring {} frame for stream {}. Stream sent after GOAWAY sent\",\n ctx.channel(), frameName, streamId);\n return true;\n }",
" // Make sure it's not an out-of-order frame, like a rogue DATA frame, for a stream that could\n // never have existed.\n verifyStreamMayHaveExisted(streamId);",
" // Its possible that this frame would result in stream ID out of order creation (PROTOCOL ERROR) and its\n // also possible that this frame is received on a CLOSED stream (STREAM_CLOSED after a RST_STREAM is\n // sent). We don't have enough information to know for sure, so we choose the lesser of the two errors.\n throw streamError(streamId, STREAM_CLOSED, \"Received %s frame for an unknown stream %d\",\n frameName, streamId);\n } else if (stream.isResetSent() || streamCreatedAfterGoAwaySent(streamId)) {\n // If we have sent a reset stream it is assumed the stream will be closed after the write completes.\n // If we have not sent a reset, but the stream was created after a GoAway this is not supported by\n // DefaultHttp2Connection and if a custom Http2Connection is used it is assumed the lifetime is managed\n // elsewhere so we don't close the stream or otherwise modify the stream's state.",
" if (logger.isInfoEnabled()) {\n logger.info(\"{} ignoring {} frame for stream {}\", ctx.channel(), frameName,\n stream.isResetSent() ? \"RST_STREAM sent.\" :\n (\"Stream created after GOAWAY sent. Last known stream by peer \" +\n connection.remote().lastStreamKnownByPeer()));\n }",
" return true;\n }\n return false;\n }",
" /**\n * Helper method for determining whether or not to ignore inbound frames. A stream is considered to be created\n * after a {@code GOAWAY} is sent if the following conditions hold:\n * <p/>\n * <ul>\n * <li>A {@code GOAWAY} must have been sent by the local endpoint</li>\n * <li>The {@code streamId} must identify a legitimate stream id for the remote endpoint to be creating</li>\n * <li>{@code streamId} is greater than the Last Known Stream ID which was sent by the local endpoint\n * in the last {@code GOAWAY} frame</li>\n * </ul>\n * <p/>\n */\n private boolean streamCreatedAfterGoAwaySent(int streamId) {\n Endpoint<?> remote = connection.remote();\n return connection.goAwaySent() && remote.isValidStreamId(streamId) &&\n streamId > remote.lastStreamKnownByPeer();\n }",
" private void verifyStreamMayHaveExisted(int streamId) throws Http2Exception {\n if (!connection.streamMayHaveExisted(streamId)) {\n throw connectionError(PROTOCOL_ERROR, \"Stream %d does not exist\", streamId);\n }\n }\n }",
" private final class PrefaceFrameListener implements Http2FrameListener {\n /**\n * Verifies that the HTTP/2 connection preface has been received from the remote endpoint.\n * It is possible that the current call to\n * {@link Http2FrameReader#readFrame(ChannelHandlerContext, ByteBuf, Http2FrameListener)} will have multiple\n * frames to dispatch. So it may be OK for this class to get legitimate frames for the first readFrame.\n */\n private void verifyPrefaceReceived() throws Http2Exception {\n if (!prefaceReceived()) {\n throw connectionError(PROTOCOL_ERROR, \"Received non-SETTINGS as first frame.\");\n }\n }",
" @Override\n public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream)\n throws Http2Exception {\n verifyPrefaceReceived();\n return internalFrameListener.onDataRead(ctx, streamId, data, padding, endOfStream);\n }",
" @Override\n public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,\n boolean endOfStream) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onHeadersRead(ctx, streamId, headers, padding, endOfStream);\n }",
" @Override\n public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency,\n short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onHeadersRead(ctx, streamId, headers, streamDependency, weight,\n exclusive, padding, endOfStream);\n }",
" @Override\n public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight,\n boolean exclusive) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onPriorityRead(ctx, streamId, streamDependency, weight, exclusive);\n }",
" @Override\n public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onRstStreamRead(ctx, streamId, errorCode);\n }",
" @Override\n public void onSettingsAckRead(ChannelHandlerContext ctx) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onSettingsAckRead(ctx);\n }",
" @Override\n public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception {\n // The first settings should change the internalFrameListener to the \"real\" listener\n // that expects the preface to be verified.\n if (!prefaceReceived()) {\n internalFrameListener = new FrameReadListener();\n }\n internalFrameListener.onSettingsRead(ctx, settings);\n }",
" @Override\n public void onPingRead(ChannelHandlerContext ctx, long data) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onPingRead(ctx, data);\n }",
" @Override\n public void onPingAckRead(ChannelHandlerContext ctx, long data) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onPingAckRead(ctx, data);\n }",
" @Override\n public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,\n Http2Headers headers, int padding) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onPushPromiseRead(ctx, streamId, promisedStreamId, headers, padding);\n }",
" @Override\n public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)\n throws Http2Exception {\n onGoAwayRead0(ctx, lastStreamId, errorCode, debugData);\n }",
" @Override\n public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement)\n throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onWindowUpdateRead(ctx, streamId, windowSizeIncrement);\n }",
" @Override\n public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,\n ByteBuf payload) throws Http2Exception {\n onUnknownFrame0(ctx, frameType, streamId, flags, payload);\n }\n }",
" private static final class ContentLength {\n private final long expected;\n private long seen;",
" ContentLength(long expected) {\n this.expected = expected;\n }",
" void increaseReceivedBytes(boolean server, int streamId, int bytes, boolean isEnd) throws Http2Exception {\n seen += bytes;\n // Check for overflow\n if (seen < 0) {\n throw streamError(streamId, PROTOCOL_ERROR,\n \"Received amount of data did overflow and so not match content-length header %d\", expected);\n }\n // Check if we received more data then what was advertised via the content-length header.\n if (seen > expected) {\n throw streamError(streamId, PROTOCOL_ERROR,\n \"Received amount of data %d does not match content-length header %d\", seen, expected);\n }",
" if (isEnd) {\n if (seen == 0 && !server) {\n // This may be a response to a HEAD request, let's just allow it.\n return;\n }",
" // Check that we really saw what was told via the content-length header.\n if (expected > seen) {\n throw streamError(streamId, PROTOCOL_ERROR,\n \"Received amount of data %d does not match content-length header %d\", seen, expected);\n }\n }\n }\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
0,
1,
1,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [398, 231], "buggy_code_start_loc": [355, 226], "filenames": ["codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionDecoder.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexTest.java"], "fixing_code_end_loc": [401, 274], "fixing_code_start_loc": [356, 227], "message": "Netty is an open-source, asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. In Netty (io.netty:netty-codec-http2) before version 4.1.61.Final there is a vulnerability that enables request smuggling. The content-length header is not correctly validated if the request only uses a single Http2HeaderFrame with the endStream set to to true. This could lead to request smuggling if the request is proxied to a remote peer and translated to HTTP/1.1. This is a followup of GHSA-wm47-8v5p-wjpj/CVE-2021-21295 which did miss to fix this one case. This was fixed as part of 4.1.61.Final.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netty:netty:*:*:*:*:*:*:*:*", "matchCriteriaId": "BC283248-0EB5-46CA-A68C-4FF004D606F8", "versionEndExcluding": "4.1.61", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netapp:oncommand_api_services:-:*:*:*:*:*:*:*", "matchCriteriaId": "5EC98B22-FFAA-4B59-8E63-EBAA4336AD13", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:netapp:oncommand_workflow_automation:-:*:*:*:*:*:*:*", "matchCriteriaId": "5735E553-9731-4AAC-BCFF-989377F817B3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "0CF9A061-2421-426D-9854-0A4E55B2961D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F95EDC3D-54BB-48F9-82F2-7CCF335FCA78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B72B735F-4E52-484A-9C2C-23E6E2070385", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "8B36A1D4-F391-4EE3-9A65-0A10568795BA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "55116032-AAD1-4FEA-9DA8-2C4CBD3D3F61", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "0275F820-40BE-47B8-B167-815A55DF578E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "9E14324D-B9EE-4C06-ACC7-255189ED6300", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "CBEBB60F-6EAB-4AE5-B777-5044C657FBA8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B185C1EA-71E6-4972-8637-08A33CC00841", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:coherence:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "2FF57C7A-92C9-4D71-A7B1-CC9DEFAA8193", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:coherence:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "5FA64A1D-34F9-4441-857A-25C165E6DBB6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_brm_-_elastic_charging_engine:12.0.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "06594847-96ED-4541-B2F4-C7331B603603", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_console:1.7.0:*:*:*:*:*:*:*", "matchCriteriaId": "BC12B43F-30F6-4B05-AB3A-E91D8404D5A5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_policy:1.14.0:*:*:*:*:*:*:*", "matchCriteriaId": "4479F76A-4B67-41CC-98C7-C76B81050F8E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_design_studio:7.4.2.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "040DA31B-2A0C-46F6-8EDF-9B88F9FB0F48", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_messaging_server:8.1:*:*:*:*:*:*:*", "matchCriteriaId": "E1214FDF-357A-4BB9-BADE-50FB2BD16D10", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:helidon:1.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "4E7626D2-D9FF-416A-9581-852CED0D8C24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:helidon:2.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "99344A5D-F4B7-49B4-9AE6-0E2FB3874EA5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jd_edwards_enterpriseone_tools:*:*:*:*:*:*:*:*", "matchCriteriaId": "BE34D4F7-5C18-4578-8D0A-722FDF931333", "versionEndExcluding": "9.2.6.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:nosql_database:*:*:*:*:*:*:*:*", "matchCriteriaId": "7167D144-C4AE-487F-B59A-888E10EA59DF", "versionEndExcluding": "21.1.12", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "8B1C88FD-C2EC-4C96-AC7E-6F95C8763B48", "versionEndExcluding": null, "versionEndIncluding": "17.12.11", "versionStartExcluding": null, "versionStartIncluding": "17.12.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "53E2276C-9515-46F6-A621-213A3047B9A6", "versionEndExcluding": null, "versionEndIncluding": "18.8.11", "versionStartExcluding": null, "versionStartIncluding": "18.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "3EF7E2B4-B741-41E9-8EF6-6C415AB9EF54", "versionEndExcluding": null, "versionEndIncluding": "19.12.10", "versionStartExcluding": null, "versionStartIncluding": "19.12.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:quarkus:quarkus:*:*:*:*:*:*:*:*", "matchCriteriaId": "64839EBF-078E-492A-897C-9AFFB7678ED8", "versionEndExcluding": null, "versionEndIncluding": "1.13.7", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Netty is an open-source, asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. In Netty (io.netty:netty-codec-http2) before version 4.1.61.Final there is a vulnerability that enables request smuggling. The content-length header is not correctly validated if the request only uses a single Http2HeaderFrame with the endStream set to to true. This could lead to request smuggling if the request is proxied to a remote peer and translated to HTTP/1.1. This is a followup of GHSA-wm47-8v5p-wjpj/CVE-2021-21295 which did miss to fix this one case. This was fixed as part of 4.1.61.Final."}, {"lang": "es", "value": "Netty es un framework de aplicaci\u00f3n de red de c\u00f3digo abierto y as\u00edncrono event-driven para el desarrollo r\u00e1pido de servidores y clientes de protocolo de alto rendimiento mantenibles. En Netty (io.netty:netty-codec-http2) versiones anteriores a 4.1.61.Final se presenta una vulnerabilidad que permite el trafico no autorizado de peticiones. El encabezado content-length no es comprobado correctamente si la petici\u00f3n solo usa un \u00fanico Http2HeaderFrame con endStream establecido en verdadero. Esto podr\u00eda conllevar al trafico no autorizado de peticiones si la petici\u00f3n se env\u00eda a un peer remoto y se traduce a HTTP/1.1. Este es un seguimiento de GHSA-wm47-8v5p-wjpj/CVE-2021-21295 que no pudo solucionar este caso. Esto se corrigi\u00f3 como parte de la versi\u00f3n 4.1.61.Final."}], "evaluatorComment": null, "id": "CVE-2021-21409", "lastModified": "2022-05-12T14:35:58.710", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-30T15:15:14.573", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-21295"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/netty/netty/commit/b0fa4d5aab4215f3c22ce6123dd8dd5f38dc0432"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/netty/netty/security/advisories/GHSA-f256-j965-7f32"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/netty/netty/security/advisories/GHSA-wm47-8v5p-wjpj"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r0b09f3e31e004fe583f677f7afa46bd30110904576c13c5ac818ac2c@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r0ca82fec33334e571fe5b388272260778883e307e15415d7b1443de2@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r101f82d8f3b5af0bf79aecbd5b2dd3b404f6bb51d1a54c2c3d29bed9@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r1b3cb056364794f919aaf26ceaf7423de64e7fdd05a914066e7d5219@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r2732aa3884cacfecac4c54cfaa77c279ba815cad44b464a567216f83@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r31044fb995e894749cb821c6fe56f487c16a97028e6e360e59f09d58@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4a98827bb4a7edbd69ef862f2351391845697c40711820d10df52ca5@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4b8be87acf5b9c098a2ee350b5ca5716fe7afeaf0a21a4ee45a90687@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4ea2f1a9d79d4fc1896e085f31fb60a21b1770d0a26a5250f849372d@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r584cf871f188c406d8bd447ff4e2fd9817fca862436c064d0951a071@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5baac01f9e06c40ff7aab209d5751b3b58802c63734e33324b70a06a@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5cbea8614812289a9b98d0cfc54b47f54cef424ac98d5e315b791795@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5f2f120b2b8d099226473db1832ffb4d7c1d6dc2d228a164bf293a8e@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r602e98daacc98934f097f07f2eed6eb07c18bfc1949c8489dc7bfcf5@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r61564d86a75403b854cdafee67fc69c8b88c5f6802c2c838f4282cc8@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r69efd8ef003f612c43e4154e788ca3b1f837feaacd16d97854402355@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r6dac9bd799ceac499c7a7e152a9b0dc7f2fe7f89ec5605d129bb047b@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r70c3a7bfa904f06a1902f4df20ee26e4f09a46b8fd3eb304dc57a2de@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r7879ddcb990c835c6b246654770d836f9d031dee982be836744e50ed@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r7b54563abebe3dbbe421e1ba075c2030d8d460372f8c79b7789684b6@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r823d4b27fcba8dad5fe945bdefce3ca5a0031187966eb6ef3cc22ba9@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r855b4b6814ac829ce2d48dd9d8138d07f33387e710de798ee92c011e@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r967002f0939e69bdec58f070735a19dd57c1f2b8f817949ca17cddae@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r9ec78dc409f3f1edff88f21cab53737f36aad46f582a9825389092e0@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r9fe840c36b74f92b8d4a089ada1f9fd1d6293742efa18b10e06b66d2@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra64d56a8a331ffd7bdcd24a9aaaeeedeacd5d639f5a683389123f898@%3Cdev.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra655e5cec74d1ddf62adacb71d398abd96f3ea2c588f6bbf048348eb@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra66e93703e3f4bd31bdfd0b6fb0c32ae96b528259bb1aa2b6d38e401@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/raa413040db6d2197593cc03edecfd168732e697119e6447b0a25d525@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rac8cf45a1bab9ead5c9a860cbadd6faaeb7792203617b6ec3874736d@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rafc77f9f03031297394f3d372ccea751b23576f8a2ae9b6b053894c5@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rba2a9ef1d0af882ab58fadb336a58818495245dda43d32a7d7837187@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rbde2f13daf4911504f0eaea43eee4f42555241b5f6d9d71564b6c5fa@%3Cjira.kafka.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rca0978b634a0c3ebee4126ec29c7f570b165fae3f8f3658754c1cbd3@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rcae42fba06979934208bbd515584b241d3ad01d1bb8b063512644362@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rd4a6b7dec38ea6cd28b6f94bd4b312629a52b80be3786d5fb0e474bc@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rd8f72411fb75b98d366400ae789966373b5c3eb3f511e717caf3e49e@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rdd206d9dd7eb894cc089b37fe6edde2932de88d63a6d8368b44f5101@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rdd5715f3ee5e3216d5e0083a07994f67da6dbb9731ce9e7a6389b18e@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re1911e05c08f3ec2bab85744d788773519a0afb27272a31ac2a0b4e8@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re39391adcb863f0e9f3f15e7986255948f263f02e4700b82453e7102@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re4b0141939370304d676fe23774d0c6fbc584b648919825402d0cb39@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re7c69756a102bebce8b8681882844a53e2f23975a189363e68ad0324@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re9e6ed60941da831675de2f8f733c026757fb4fa28a7b6c9f3dfb575@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/redef0fb5474fd686781007de9ddb852b24f1b04131a248d9a4789183@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf148b2bf6c2754153a8629bc7495e216bd0bd4c915695486542a10b4@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf38e4dcdefc7c59f7ba0799a399d6d6e37b555d406a1dfc2fcbf0b35@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf521ff2be2e2dd38984174d3451e6ee935c845948845c8fccd86371d@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf934292a4a1c189827f625d567838d2c1001e4739b158638d844105b@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20210604-0003/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4885"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com//security-alerts/cpujul2021.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujan2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuoct2021.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/netty/netty/commit/b0fa4d5aab4215f3c22ce6123dd8dd5f38dc0432"}, "type": "CWE-444"}
| 258
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Copyright 2014 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License, version 2.0 (the\n * \"License\"); you may not use this file except in compliance with the License. You may obtain a\n * copy of the License at:\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\npackage io.netty.handler.codec.http2;",
"import io.netty.buffer.ByteBuf;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.handler.codec.http.HttpHeaderNames;\nimport io.netty.handler.codec.http.HttpStatusClass;\nimport io.netty.handler.codec.http.HttpUtil;\nimport io.netty.handler.codec.http2.Http2Connection.Endpoint;\nimport io.netty.util.internal.SystemPropertyUtil;\nimport io.netty.util.internal.UnstableApi;\nimport io.netty.util.internal.logging.InternalLogger;\nimport io.netty.util.internal.logging.InternalLoggerFactory;",
"import java.util.List;",
"import static io.netty.handler.codec.http.HttpStatusClass.INFORMATIONAL;\nimport static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT;\nimport static io.netty.handler.codec.http2.Http2Error.INTERNAL_ERROR;\nimport static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;\nimport static io.netty.handler.codec.http2.Http2Error.STREAM_CLOSED;\nimport static io.netty.handler.codec.http2.Http2Exception.connectionError;\nimport static io.netty.handler.codec.http2.Http2Exception.streamError;\nimport static io.netty.handler.codec.http2.Http2PromisedRequestVerifier.ALWAYS_VERIFY;\nimport static io.netty.handler.codec.http2.Http2Stream.State.CLOSED;\nimport static io.netty.handler.codec.http2.Http2Stream.State.HALF_CLOSED_REMOTE;\nimport static io.netty.util.internal.ObjectUtil.checkNotNull;\nimport static java.lang.Integer.MAX_VALUE;\nimport static java.lang.Math.min;",
"/**\n * Provides the default implementation for processing inbound frame events and delegates to a\n * {@link Http2FrameListener}\n * <p>\n * This class will read HTTP/2 frames and delegate the events to a {@link Http2FrameListener}\n * <p>\n * This interface enforces inbound flow control functionality through\n * {@link Http2LocalFlowController}\n */\n@UnstableApi\npublic class DefaultHttp2ConnectionDecoder implements Http2ConnectionDecoder {\n private static final boolean VALIDATE_CONTENT_LENGTH =\n SystemPropertyUtil.getBoolean(\"io.netty.http2.validateContentLength\", true);\n private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultHttp2ConnectionDecoder.class);\n private Http2FrameListener internalFrameListener = new PrefaceFrameListener();\n private final Http2Connection connection;\n private Http2LifecycleManager lifecycleManager;\n private final Http2ConnectionEncoder encoder;\n private final Http2FrameReader frameReader;\n private Http2FrameListener listener;\n private final Http2PromisedRequestVerifier requestVerifier;\n private final Http2SettingsReceivedConsumer settingsReceivedConsumer;\n private final boolean autoAckPing;\n private final Http2Connection.PropertyKey contentLengthKey;",
" public DefaultHttp2ConnectionDecoder(Http2Connection connection,\n Http2ConnectionEncoder encoder,\n Http2FrameReader frameReader) {\n this(connection, encoder, frameReader, ALWAYS_VERIFY);\n }",
" public DefaultHttp2ConnectionDecoder(Http2Connection connection,\n Http2ConnectionEncoder encoder,\n Http2FrameReader frameReader,\n Http2PromisedRequestVerifier requestVerifier) {\n this(connection, encoder, frameReader, requestVerifier, true);\n }",
" /**\n * Create a new instance.\n * @param connection The {@link Http2Connection} associated with this decoder.\n * @param encoder The {@link Http2ConnectionEncoder} associated with this decoder.\n * @param frameReader Responsible for reading/parsing the raw frames. As opposed to this object which applies\n * h2 semantics on top of the frames.\n * @param requestVerifier Determines if push promised streams are valid.\n * @param autoAckSettings {@code false} to disable automatically applying and sending settings acknowledge frame.\n * The {@code Http2ConnectionEncoder} is expected to be an instance of {@link Http2SettingsReceivedConsumer} and\n * will apply the earliest received but not yet ACKed SETTINGS when writing the SETTINGS ACKs.\n * {@code true} to enable automatically applying and sending settings acknowledge frame.\n */\n public DefaultHttp2ConnectionDecoder(Http2Connection connection,\n Http2ConnectionEncoder encoder,\n Http2FrameReader frameReader,\n Http2PromisedRequestVerifier requestVerifier,\n boolean autoAckSettings) {\n this(connection, encoder, frameReader, requestVerifier, autoAckSettings, true);\n }",
" /**\n * Create a new instance.\n * @param connection The {@link Http2Connection} associated with this decoder.\n * @param encoder The {@link Http2ConnectionEncoder} associated with this decoder.\n * @param frameReader Responsible for reading/parsing the raw frames. As opposed to this object which applies\n * h2 semantics on top of the frames.\n * @param requestVerifier Determines if push promised streams are valid.\n * @param autoAckSettings {@code false} to disable automatically applying and sending settings acknowledge frame.\n * The {@code Http2ConnectionEncoder} is expected to be an instance of\n * {@link Http2SettingsReceivedConsumer} and will apply the earliest received but not yet\n * ACKed SETTINGS when writing the SETTINGS ACKs. {@code true} to enable automatically\n * applying and sending settings acknowledge frame.\n * @param autoAckPing {@code false} to disable automatically sending ping acknowledge frame. {@code true} to enable\n * automatically sending ping ack frame.\n */\n public DefaultHttp2ConnectionDecoder(Http2Connection connection,\n Http2ConnectionEncoder encoder,\n Http2FrameReader frameReader,\n Http2PromisedRequestVerifier requestVerifier,\n boolean autoAckSettings,\n boolean autoAckPing) {\n this.autoAckPing = autoAckPing;\n if (autoAckSettings) {\n settingsReceivedConsumer = null;\n } else {\n if (!(encoder instanceof Http2SettingsReceivedConsumer)) {\n throw new IllegalArgumentException(\"disabling autoAckSettings requires the encoder to be a \" +\n Http2SettingsReceivedConsumer.class);\n }\n settingsReceivedConsumer = (Http2SettingsReceivedConsumer) encoder;\n }\n this.connection = checkNotNull(connection, \"connection\");\n contentLengthKey = this.connection.newKey();\n this.frameReader = checkNotNull(frameReader, \"frameReader\");\n this.encoder = checkNotNull(encoder, \"encoder\");\n this.requestVerifier = checkNotNull(requestVerifier, \"requestVerifier\");\n if (connection.local().flowController() == null) {\n connection.local().flowController(new DefaultHttp2LocalFlowController(connection));\n }\n connection.local().flowController().frameWriter(encoder.frameWriter());\n }",
" @Override\n public void lifecycleManager(Http2LifecycleManager lifecycleManager) {\n this.lifecycleManager = checkNotNull(lifecycleManager, \"lifecycleManager\");\n }",
" @Override\n public Http2Connection connection() {\n return connection;\n }",
" @Override\n public final Http2LocalFlowController flowController() {\n return connection.local().flowController();\n }",
" @Override\n public void frameListener(Http2FrameListener listener) {\n this.listener = checkNotNull(listener, \"listener\");\n }",
" @Override\n public Http2FrameListener frameListener() {\n return listener;\n }",
" // Visible for testing\n Http2FrameListener internalFrameListener() {\n return internalFrameListener;\n }",
" @Override\n public boolean prefaceReceived() {\n return FrameReadListener.class == internalFrameListener.getClass();\n }",
" @Override\n public void decodeFrame(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Http2Exception {\n frameReader.readFrame(ctx, in, internalFrameListener);\n }",
" @Override\n public Http2Settings localSettings() {\n Http2Settings settings = new Http2Settings();\n Http2FrameReader.Configuration config = frameReader.configuration();\n Http2HeadersDecoder.Configuration headersConfig = config.headersConfiguration();\n Http2FrameSizePolicy frameSizePolicy = config.frameSizePolicy();\n settings.initialWindowSize(flowController().initialWindowSize());\n settings.maxConcurrentStreams(connection.remote().maxActiveStreams());\n settings.headerTableSize(headersConfig.maxHeaderTableSize());\n settings.maxFrameSize(frameSizePolicy.maxFrameSize());\n settings.maxHeaderListSize(headersConfig.maxHeaderListSize());\n if (!connection.isServer()) {\n // Only set the pushEnabled flag if this is a client endpoint.\n settings.pushEnabled(connection.local().allowPushTo());\n }\n return settings;\n }",
" @Override\n public void close() {\n frameReader.close();\n }",
" /**\n * Calculate the threshold in bytes which should trigger a {@code GO_AWAY} if a set of headers exceeds this amount.\n * @param maxHeaderListSize\n * <a href=\"https://tools.ietf.org/html/rfc7540#section-6.5.2\">SETTINGS_MAX_HEADER_LIST_SIZE</a> for the local\n * endpoint.\n * @return the threshold in bytes which should trigger a {@code GO_AWAY} if a set of headers exceeds this amount.\n */\n protected long calculateMaxHeaderListSizeGoAway(long maxHeaderListSize) {\n return Http2CodecUtil.calculateMaxHeaderListSizeGoAway(maxHeaderListSize);\n }",
" private int unconsumedBytes(Http2Stream stream) {\n return flowController().unconsumedBytes(stream);\n }",
" void onGoAwayRead0(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)\n throws Http2Exception {\n listener.onGoAwayRead(ctx, lastStreamId, errorCode, debugData);\n connection.goAwayReceived(lastStreamId, errorCode, debugData);\n }",
" void onUnknownFrame0(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,\n ByteBuf payload) throws Http2Exception {\n listener.onUnknownFrame(ctx, frameType, streamId, flags, payload);\n }",
" // See https://tools.ietf.org/html/rfc7540#section-8.1.2.6\n private void verifyContentLength(Http2Stream stream, int data, boolean isEnd) throws Http2Exception {\n if (!VALIDATE_CONTENT_LENGTH) {\n return;\n }\n ContentLength contentLength = stream.getProperty(contentLengthKey);\n if (contentLength != null) {\n try {\n contentLength.increaseReceivedBytes(connection.isServer(), stream.id(), data, isEnd);\n } finally {\n if (isEnd) {\n stream.removeProperty(contentLengthKey);\n }\n }\n }\n }",
" /**\n * Handles all inbound frames from the network.\n */\n private final class FrameReadListener implements Http2FrameListener {\n @Override\n public int onDataRead(final ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,\n boolean endOfStream) throws Http2Exception {\n Http2Stream stream = connection.stream(streamId);\n Http2LocalFlowController flowController = flowController();\n int readable = data.readableBytes();\n int bytesToReturn = readable + padding;",
" final boolean shouldIgnore;\n try {\n shouldIgnore = shouldIgnoreHeadersOrDataFrame(ctx, streamId, stream, \"DATA\");\n } catch (Http2Exception e) {\n // Ignoring this frame. We still need to count the frame towards the connection flow control\n // window, but we immediately mark all bytes as consumed.\n flowController.receiveFlowControlledFrame(stream, data, padding, endOfStream);\n flowController.consumeBytes(stream, bytesToReturn);\n throw e;\n } catch (Throwable t) {\n throw connectionError(INTERNAL_ERROR, t, \"Unhandled error on data stream id %d\", streamId);\n }",
" if (shouldIgnore) {\n // Ignoring this frame. We still need to count the frame towards the connection flow control\n // window, but we immediately mark all bytes as consumed.\n flowController.receiveFlowControlledFrame(stream, data, padding, endOfStream);\n flowController.consumeBytes(stream, bytesToReturn);",
" // Verify that the stream may have existed after we apply flow control.\n verifyStreamMayHaveExisted(streamId);",
" // All bytes have been consumed.\n return bytesToReturn;\n }\n Http2Exception error = null;\n switch (stream.state()) {\n case OPEN:\n case HALF_CLOSED_LOCAL:\n break;\n case HALF_CLOSED_REMOTE:\n case CLOSED:\n error = streamError(stream.id(), STREAM_CLOSED, \"Stream %d in unexpected state: %s\",\n stream.id(), stream.state());\n break;\n default:\n error = streamError(stream.id(), PROTOCOL_ERROR,\n \"Stream %d in unexpected state: %s\", stream.id(), stream.state());\n break;\n }",
" int unconsumedBytes = unconsumedBytes(stream);\n try {\n flowController.receiveFlowControlledFrame(stream, data, padding, endOfStream);\n // Update the unconsumed bytes after flow control is applied.\n unconsumedBytes = unconsumedBytes(stream);",
" // If the stream is in an invalid state to receive the frame, throw the error.\n if (error != null) {\n throw error;\n }",
" verifyContentLength(stream, readable, endOfStream);",
" // Call back the application and retrieve the number of bytes that have been\n // immediately processed.\n bytesToReturn = listener.onDataRead(ctx, streamId, data, padding, endOfStream);",
" if (endOfStream) {\n lifecycleManager.closeStreamRemote(stream, ctx.newSucceededFuture());\n }",
" return bytesToReturn;\n } catch (Http2Exception e) {\n // If an exception happened during delivery, the listener may have returned part\n // of the bytes before the error occurred. If that's the case, subtract that from\n // the total processed bytes so that we don't return too many bytes.\n int delta = unconsumedBytes - unconsumedBytes(stream);\n bytesToReturn -= delta;\n throw e;\n } catch (RuntimeException e) {\n // If an exception happened during delivery, the listener may have returned part\n // of the bytes before the error occurred. If that's the case, subtract that from\n // the total processed bytes so that we don't return too many bytes.\n int delta = unconsumedBytes - unconsumedBytes(stream);\n bytesToReturn -= delta;\n throw e;\n } finally {\n // If appropriate, return the processed bytes to the flow controller.\n flowController.consumeBytes(stream, bytesToReturn);\n }\n }",
" @Override\n public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,\n boolean endOfStream) throws Http2Exception {\n onHeadersRead(ctx, streamId, headers, 0, DEFAULT_PRIORITY_WEIGHT, false, padding, endOfStream);\n }",
" @Override\n public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency,\n short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception {\n Http2Stream stream = connection.stream(streamId);\n boolean allowHalfClosedRemote = false;",
" boolean isTrailers = false;",
" if (stream == null && !connection.streamMayHaveExisted(streamId)) {\n stream = connection.remote().createStream(streamId, endOfStream);\n // Allow the state to be HALF_CLOSE_REMOTE if we're creating it in that state.\n allowHalfClosedRemote = stream.state() == HALF_CLOSED_REMOTE;",
" } else if (stream != null) {\n isTrailers = stream.isHeadersReceived();",
" }",
" if (shouldIgnoreHeadersOrDataFrame(ctx, streamId, stream, \"HEADERS\")) {\n return;\n }",
" boolean isInformational = !connection.isServer() &&\n HttpStatusClass.valueOf(headers.status()) == INFORMATIONAL;\n if ((isInformational || !endOfStream) && stream.isHeadersReceived() || stream.isTrailersReceived()) {\n throw streamError(streamId, PROTOCOL_ERROR,\n \"Stream %d received too many headers EOS: %s state: %s\",\n streamId, endOfStream, stream.state());\n }",
" switch (stream.state()) {\n case RESERVED_REMOTE:\n stream.open(endOfStream);\n break;\n case OPEN:\n case HALF_CLOSED_LOCAL:\n // Allowed to receive headers in these states.\n break;\n case HALF_CLOSED_REMOTE:\n if (!allowHalfClosedRemote) {\n throw streamError(stream.id(), STREAM_CLOSED, \"Stream %d in unexpected state: %s\",\n stream.id(), stream.state());\n }\n break;\n case CLOSED:\n throw streamError(stream.id(), STREAM_CLOSED, \"Stream %d in unexpected state: %s\",\n stream.id(), stream.state());\n default:\n // Connection error.\n throw connectionError(PROTOCOL_ERROR, \"Stream %d in unexpected state: %s\", stream.id(),\n stream.state());\n }\n",
" if (!isTrailers) {",
" // extract the content-length header\n List<? extends CharSequence> contentLength = headers.getAll(HttpHeaderNames.CONTENT_LENGTH);\n if (contentLength != null && !contentLength.isEmpty()) {\n try {\n long cLength = HttpUtil.normalizeAndGetContentLength(contentLength, false, true);\n if (cLength != -1) {\n headers.setLong(HttpHeaderNames.CONTENT_LENGTH, cLength);\n stream.setProperty(contentLengthKey, new ContentLength(cLength));\n }\n } catch (IllegalArgumentException e) {\n throw streamError(stream.id(), PROTOCOL_ERROR, e,\n \"Multiple content-length headers received\");\n }\n }\n }",
" stream.headersReceived(isInformational);\n verifyContentLength(stream, 0, endOfStream);\n encoder.flowController().updateDependencyTree(streamId, streamDependency, weight, exclusive);\n listener.onHeadersRead(ctx, streamId, headers, streamDependency,\n weight, exclusive, padding, endOfStream);\n // If the headers completes this stream, close it.\n if (endOfStream) {\n lifecycleManager.closeStreamRemote(stream, ctx.newSucceededFuture());\n }\n }",
" @Override\n public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight,\n boolean exclusive) throws Http2Exception {\n encoder.flowController().updateDependencyTree(streamId, streamDependency, weight, exclusive);",
" listener.onPriorityRead(ctx, streamId, streamDependency, weight, exclusive);\n }",
" @Override\n public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) throws Http2Exception {\n Http2Stream stream = connection.stream(streamId);\n if (stream == null) {\n verifyStreamMayHaveExisted(streamId);\n return;\n }",
" switch(stream.state()) {\n case IDLE:\n throw connectionError(PROTOCOL_ERROR, \"RST_STREAM received for IDLE stream %d\", streamId);\n case CLOSED:\n return; // RST_STREAM frames must be ignored for closed streams.\n default:\n break;\n }",
" listener.onRstStreamRead(ctx, streamId, errorCode);",
" lifecycleManager.closeStream(stream, ctx.newSucceededFuture());\n }",
" @Override\n public void onSettingsAckRead(ChannelHandlerContext ctx) throws Http2Exception {\n // Apply oldest outstanding local settings here. This is a synchronization point between endpoints.\n Http2Settings settings = encoder.pollSentSettings();",
" if (settings != null) {\n applyLocalSettings(settings);\n }",
" listener.onSettingsAckRead(ctx);\n }",
" /**\n * Applies settings sent from the local endpoint.\n * <p>\n * This method is only called after the local settings have been acknowledged from the remote endpoint.\n */\n private void applyLocalSettings(Http2Settings settings) throws Http2Exception {\n Boolean pushEnabled = settings.pushEnabled();\n final Http2FrameReader.Configuration config = frameReader.configuration();\n final Http2HeadersDecoder.Configuration headerConfig = config.headersConfiguration();\n final Http2FrameSizePolicy frameSizePolicy = config.frameSizePolicy();\n if (pushEnabled != null) {\n if (connection.isServer()) {\n throw connectionError(PROTOCOL_ERROR, \"Server sending SETTINGS frame with ENABLE_PUSH specified\");\n }\n connection.local().allowPushTo(pushEnabled);\n }",
" Long maxConcurrentStreams = settings.maxConcurrentStreams();\n if (maxConcurrentStreams != null) {\n connection.remote().maxActiveStreams((int) min(maxConcurrentStreams, MAX_VALUE));\n }",
" Long headerTableSize = settings.headerTableSize();\n if (headerTableSize != null) {\n headerConfig.maxHeaderTableSize(headerTableSize);\n }",
" Long maxHeaderListSize = settings.maxHeaderListSize();\n if (maxHeaderListSize != null) {\n headerConfig.maxHeaderListSize(maxHeaderListSize, calculateMaxHeaderListSizeGoAway(maxHeaderListSize));\n }",
" Integer maxFrameSize = settings.maxFrameSize();\n if (maxFrameSize != null) {\n frameSizePolicy.maxFrameSize(maxFrameSize);\n }",
" Integer initialWindowSize = settings.initialWindowSize();\n if (initialWindowSize != null) {\n flowController().initialWindowSize(initialWindowSize);\n }\n }",
" @Override\n public void onSettingsRead(final ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception {\n if (settingsReceivedConsumer == null) {\n // Acknowledge receipt of the settings. We should do this before we process the settings to ensure our\n // remote peer applies these settings before any subsequent frames that we may send which depend upon\n // these new settings. See https://github.com/netty/netty/issues/6520.\n encoder.writeSettingsAck(ctx, ctx.newPromise());",
" encoder.remoteSettings(settings);\n } else {\n settingsReceivedConsumer.consumeReceivedSettings(settings);\n }",
" listener.onSettingsRead(ctx, settings);\n }",
" @Override\n public void onPingRead(ChannelHandlerContext ctx, long data) throws Http2Exception {\n if (autoAckPing) {\n // Send an ack back to the remote client.\n encoder.writePing(ctx, true, data, ctx.newPromise());\n }\n listener.onPingRead(ctx, data);\n }",
" @Override\n public void onPingAckRead(ChannelHandlerContext ctx, long data) throws Http2Exception {\n listener.onPingAckRead(ctx, data);\n }",
" @Override\n public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,\n Http2Headers headers, int padding) throws Http2Exception {\n // A client cannot push.\n if (connection().isServer()) {\n throw connectionError(PROTOCOL_ERROR, \"A client cannot push.\");\n }",
" Http2Stream parentStream = connection.stream(streamId);",
" if (shouldIgnoreHeadersOrDataFrame(ctx, streamId, parentStream, \"PUSH_PROMISE\")) {\n return;\n }",
" switch (parentStream.state()) {\n case OPEN:\n case HALF_CLOSED_LOCAL:\n // Allowed to receive push promise in these states.\n break;\n default:\n // Connection error.\n throw connectionError(PROTOCOL_ERROR,\n \"Stream %d in unexpected state for receiving push promise: %s\",\n parentStream.id(), parentStream.state());\n }",
" if (!requestVerifier.isAuthoritative(ctx, headers)) {\n throw streamError(promisedStreamId, PROTOCOL_ERROR,\n \"Promised request on stream %d for promised stream %d is not authoritative\",\n streamId, promisedStreamId);\n }\n if (!requestVerifier.isCacheable(headers)) {\n throw streamError(promisedStreamId, PROTOCOL_ERROR,\n \"Promised request on stream %d for promised stream %d is not known to be cacheable\",\n streamId, promisedStreamId);\n }\n if (!requestVerifier.isSafe(headers)) {\n throw streamError(promisedStreamId, PROTOCOL_ERROR,\n \"Promised request on stream %d for promised stream %d is not known to be safe\",\n streamId, promisedStreamId);\n }",
" // Reserve the push stream based with a priority based on the current stream's priority.\n connection.remote().reservePushStream(promisedStreamId, parentStream);",
" listener.onPushPromiseRead(ctx, streamId, promisedStreamId, headers, padding);\n }",
" @Override\n public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)\n throws Http2Exception {\n onGoAwayRead0(ctx, lastStreamId, errorCode, debugData);\n }",
" @Override\n public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement)\n throws Http2Exception {\n Http2Stream stream = connection.stream(streamId);\n if (stream == null || stream.state() == CLOSED || streamCreatedAfterGoAwaySent(streamId)) {\n // Ignore this frame.\n verifyStreamMayHaveExisted(streamId);\n return;\n }",
" // Update the outbound flow control window.\n encoder.flowController().incrementWindowSize(stream, windowSizeIncrement);",
" listener.onWindowUpdateRead(ctx, streamId, windowSizeIncrement);\n }",
" @Override\n public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,\n ByteBuf payload) throws Http2Exception {\n onUnknownFrame0(ctx, frameType, streamId, flags, payload);\n }",
" /**\n * Helper method to determine if a frame that has the semantics of headers or data should be ignored for the\n * {@code stream} (which may be {@code null}) associated with {@code streamId}.\n */\n private boolean shouldIgnoreHeadersOrDataFrame(ChannelHandlerContext ctx, int streamId, Http2Stream stream,\n String frameName) throws Http2Exception {\n if (stream == null) {\n if (streamCreatedAfterGoAwaySent(streamId)) {\n logger.info(\"{} ignoring {} frame for stream {}. Stream sent after GOAWAY sent\",\n ctx.channel(), frameName, streamId);\n return true;\n }",
" // Make sure it's not an out-of-order frame, like a rogue DATA frame, for a stream that could\n // never have existed.\n verifyStreamMayHaveExisted(streamId);",
" // Its possible that this frame would result in stream ID out of order creation (PROTOCOL ERROR) and its\n // also possible that this frame is received on a CLOSED stream (STREAM_CLOSED after a RST_STREAM is\n // sent). We don't have enough information to know for sure, so we choose the lesser of the two errors.\n throw streamError(streamId, STREAM_CLOSED, \"Received %s frame for an unknown stream %d\",\n frameName, streamId);\n } else if (stream.isResetSent() || streamCreatedAfterGoAwaySent(streamId)) {\n // If we have sent a reset stream it is assumed the stream will be closed after the write completes.\n // If we have not sent a reset, but the stream was created after a GoAway this is not supported by\n // DefaultHttp2Connection and if a custom Http2Connection is used it is assumed the lifetime is managed\n // elsewhere so we don't close the stream or otherwise modify the stream's state.",
" if (logger.isInfoEnabled()) {\n logger.info(\"{} ignoring {} frame for stream {}\", ctx.channel(), frameName,\n stream.isResetSent() ? \"RST_STREAM sent.\" :\n (\"Stream created after GOAWAY sent. Last known stream by peer \" +\n connection.remote().lastStreamKnownByPeer()));\n }",
" return true;\n }\n return false;\n }",
" /**\n * Helper method for determining whether or not to ignore inbound frames. A stream is considered to be created\n * after a {@code GOAWAY} is sent if the following conditions hold:\n * <p/>\n * <ul>\n * <li>A {@code GOAWAY} must have been sent by the local endpoint</li>\n * <li>The {@code streamId} must identify a legitimate stream id for the remote endpoint to be creating</li>\n * <li>{@code streamId} is greater than the Last Known Stream ID which was sent by the local endpoint\n * in the last {@code GOAWAY} frame</li>\n * </ul>\n * <p/>\n */\n private boolean streamCreatedAfterGoAwaySent(int streamId) {\n Endpoint<?> remote = connection.remote();\n return connection.goAwaySent() && remote.isValidStreamId(streamId) &&\n streamId > remote.lastStreamKnownByPeer();\n }",
" private void verifyStreamMayHaveExisted(int streamId) throws Http2Exception {\n if (!connection.streamMayHaveExisted(streamId)) {\n throw connectionError(PROTOCOL_ERROR, \"Stream %d does not exist\", streamId);\n }\n }\n }",
" private final class PrefaceFrameListener implements Http2FrameListener {\n /**\n * Verifies that the HTTP/2 connection preface has been received from the remote endpoint.\n * It is possible that the current call to\n * {@link Http2FrameReader#readFrame(ChannelHandlerContext, ByteBuf, Http2FrameListener)} will have multiple\n * frames to dispatch. So it may be OK for this class to get legitimate frames for the first readFrame.\n */\n private void verifyPrefaceReceived() throws Http2Exception {\n if (!prefaceReceived()) {\n throw connectionError(PROTOCOL_ERROR, \"Received non-SETTINGS as first frame.\");\n }\n }",
" @Override\n public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream)\n throws Http2Exception {\n verifyPrefaceReceived();\n return internalFrameListener.onDataRead(ctx, streamId, data, padding, endOfStream);\n }",
" @Override\n public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,\n boolean endOfStream) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onHeadersRead(ctx, streamId, headers, padding, endOfStream);\n }",
" @Override\n public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency,\n short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onHeadersRead(ctx, streamId, headers, streamDependency, weight,\n exclusive, padding, endOfStream);\n }",
" @Override\n public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight,\n boolean exclusive) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onPriorityRead(ctx, streamId, streamDependency, weight, exclusive);\n }",
" @Override\n public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onRstStreamRead(ctx, streamId, errorCode);\n }",
" @Override\n public void onSettingsAckRead(ChannelHandlerContext ctx) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onSettingsAckRead(ctx);\n }",
" @Override\n public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception {\n // The first settings should change the internalFrameListener to the \"real\" listener\n // that expects the preface to be verified.\n if (!prefaceReceived()) {\n internalFrameListener = new FrameReadListener();\n }\n internalFrameListener.onSettingsRead(ctx, settings);\n }",
" @Override\n public void onPingRead(ChannelHandlerContext ctx, long data) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onPingRead(ctx, data);\n }",
" @Override\n public void onPingAckRead(ChannelHandlerContext ctx, long data) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onPingAckRead(ctx, data);\n }",
" @Override\n public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,\n Http2Headers headers, int padding) throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onPushPromiseRead(ctx, streamId, promisedStreamId, headers, padding);\n }",
" @Override\n public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)\n throws Http2Exception {\n onGoAwayRead0(ctx, lastStreamId, errorCode, debugData);\n }",
" @Override\n public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement)\n throws Http2Exception {\n verifyPrefaceReceived();\n internalFrameListener.onWindowUpdateRead(ctx, streamId, windowSizeIncrement);\n }",
" @Override\n public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,\n ByteBuf payload) throws Http2Exception {\n onUnknownFrame0(ctx, frameType, streamId, flags, payload);\n }\n }",
" private static final class ContentLength {\n private final long expected;\n private long seen;",
" ContentLength(long expected) {\n this.expected = expected;\n }",
" void increaseReceivedBytes(boolean server, int streamId, int bytes, boolean isEnd) throws Http2Exception {\n seen += bytes;\n // Check for overflow\n if (seen < 0) {\n throw streamError(streamId, PROTOCOL_ERROR,\n \"Received amount of data did overflow and so not match content-length header %d\", expected);\n }\n // Check if we received more data then what was advertised via the content-length header.\n if (seen > expected) {\n throw streamError(streamId, PROTOCOL_ERROR,\n \"Received amount of data %d does not match content-length header %d\", seen, expected);\n }",
" if (isEnd) {\n if (seen == 0 && !server) {\n // This may be a response to a HEAD request, let's just allow it.\n return;\n }",
" // Check that we really saw what was told via the content-length header.\n if (expected > seen) {\n throw streamError(streamId, PROTOCOL_ERROR,\n \"Received amount of data %d does not match content-length header %d\", seen, expected);\n }\n }\n }\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [398, 231], "buggy_code_start_loc": [355, 226], "filenames": ["codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionDecoder.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexTest.java"], "fixing_code_end_loc": [401, 274], "fixing_code_start_loc": [356, 227], "message": "Netty is an open-source, asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. In Netty (io.netty:netty-codec-http2) before version 4.1.61.Final there is a vulnerability that enables request smuggling. The content-length header is not correctly validated if the request only uses a single Http2HeaderFrame with the endStream set to to true. This could lead to request smuggling if the request is proxied to a remote peer and translated to HTTP/1.1. This is a followup of GHSA-wm47-8v5p-wjpj/CVE-2021-21295 which did miss to fix this one case. This was fixed as part of 4.1.61.Final.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netty:netty:*:*:*:*:*:*:*:*", "matchCriteriaId": "BC283248-0EB5-46CA-A68C-4FF004D606F8", "versionEndExcluding": "4.1.61", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netapp:oncommand_api_services:-:*:*:*:*:*:*:*", "matchCriteriaId": "5EC98B22-FFAA-4B59-8E63-EBAA4336AD13", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:netapp:oncommand_workflow_automation:-:*:*:*:*:*:*:*", "matchCriteriaId": "5735E553-9731-4AAC-BCFF-989377F817B3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "0CF9A061-2421-426D-9854-0A4E55B2961D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F95EDC3D-54BB-48F9-82F2-7CCF335FCA78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B72B735F-4E52-484A-9C2C-23E6E2070385", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "8B36A1D4-F391-4EE3-9A65-0A10568795BA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "55116032-AAD1-4FEA-9DA8-2C4CBD3D3F61", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "0275F820-40BE-47B8-B167-815A55DF578E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "9E14324D-B9EE-4C06-ACC7-255189ED6300", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "CBEBB60F-6EAB-4AE5-B777-5044C657FBA8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B185C1EA-71E6-4972-8637-08A33CC00841", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:coherence:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "2FF57C7A-92C9-4D71-A7B1-CC9DEFAA8193", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:coherence:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "5FA64A1D-34F9-4441-857A-25C165E6DBB6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_brm_-_elastic_charging_engine:12.0.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "06594847-96ED-4541-B2F4-C7331B603603", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_console:1.7.0:*:*:*:*:*:*:*", "matchCriteriaId": "BC12B43F-30F6-4B05-AB3A-E91D8404D5A5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_policy:1.14.0:*:*:*:*:*:*:*", "matchCriteriaId": "4479F76A-4B67-41CC-98C7-C76B81050F8E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_design_studio:7.4.2.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "040DA31B-2A0C-46F6-8EDF-9B88F9FB0F48", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_messaging_server:8.1:*:*:*:*:*:*:*", "matchCriteriaId": "E1214FDF-357A-4BB9-BADE-50FB2BD16D10", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:helidon:1.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "4E7626D2-D9FF-416A-9581-852CED0D8C24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:helidon:2.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "99344A5D-F4B7-49B4-9AE6-0E2FB3874EA5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jd_edwards_enterpriseone_tools:*:*:*:*:*:*:*:*", "matchCriteriaId": "BE34D4F7-5C18-4578-8D0A-722FDF931333", "versionEndExcluding": "9.2.6.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:nosql_database:*:*:*:*:*:*:*:*", "matchCriteriaId": "7167D144-C4AE-487F-B59A-888E10EA59DF", "versionEndExcluding": "21.1.12", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "8B1C88FD-C2EC-4C96-AC7E-6F95C8763B48", "versionEndExcluding": null, "versionEndIncluding": "17.12.11", "versionStartExcluding": null, "versionStartIncluding": "17.12.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "53E2276C-9515-46F6-A621-213A3047B9A6", "versionEndExcluding": null, "versionEndIncluding": "18.8.11", "versionStartExcluding": null, "versionStartIncluding": "18.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "3EF7E2B4-B741-41E9-8EF6-6C415AB9EF54", "versionEndExcluding": null, "versionEndIncluding": "19.12.10", "versionStartExcluding": null, "versionStartIncluding": "19.12.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:quarkus:quarkus:*:*:*:*:*:*:*:*", "matchCriteriaId": "64839EBF-078E-492A-897C-9AFFB7678ED8", "versionEndExcluding": null, "versionEndIncluding": "1.13.7", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Netty is an open-source, asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. In Netty (io.netty:netty-codec-http2) before version 4.1.61.Final there is a vulnerability that enables request smuggling. The content-length header is not correctly validated if the request only uses a single Http2HeaderFrame with the endStream set to to true. This could lead to request smuggling if the request is proxied to a remote peer and translated to HTTP/1.1. This is a followup of GHSA-wm47-8v5p-wjpj/CVE-2021-21295 which did miss to fix this one case. This was fixed as part of 4.1.61.Final."}, {"lang": "es", "value": "Netty es un framework de aplicaci\u00f3n de red de c\u00f3digo abierto y as\u00edncrono event-driven para el desarrollo r\u00e1pido de servidores y clientes de protocolo de alto rendimiento mantenibles. En Netty (io.netty:netty-codec-http2) versiones anteriores a 4.1.61.Final se presenta una vulnerabilidad que permite el trafico no autorizado de peticiones. El encabezado content-length no es comprobado correctamente si la petici\u00f3n solo usa un \u00fanico Http2HeaderFrame con endStream establecido en verdadero. Esto podr\u00eda conllevar al trafico no autorizado de peticiones si la petici\u00f3n se env\u00eda a un peer remoto y se traduce a HTTP/1.1. Este es un seguimiento de GHSA-wm47-8v5p-wjpj/CVE-2021-21295 que no pudo solucionar este caso. Esto se corrigi\u00f3 como parte de la versi\u00f3n 4.1.61.Final."}], "evaluatorComment": null, "id": "CVE-2021-21409", "lastModified": "2022-05-12T14:35:58.710", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-30T15:15:14.573", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-21295"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/netty/netty/commit/b0fa4d5aab4215f3c22ce6123dd8dd5f38dc0432"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/netty/netty/security/advisories/GHSA-f256-j965-7f32"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/netty/netty/security/advisories/GHSA-wm47-8v5p-wjpj"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r0b09f3e31e004fe583f677f7afa46bd30110904576c13c5ac818ac2c@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r0ca82fec33334e571fe5b388272260778883e307e15415d7b1443de2@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r101f82d8f3b5af0bf79aecbd5b2dd3b404f6bb51d1a54c2c3d29bed9@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r1b3cb056364794f919aaf26ceaf7423de64e7fdd05a914066e7d5219@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r2732aa3884cacfecac4c54cfaa77c279ba815cad44b464a567216f83@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r31044fb995e894749cb821c6fe56f487c16a97028e6e360e59f09d58@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4a98827bb4a7edbd69ef862f2351391845697c40711820d10df52ca5@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4b8be87acf5b9c098a2ee350b5ca5716fe7afeaf0a21a4ee45a90687@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4ea2f1a9d79d4fc1896e085f31fb60a21b1770d0a26a5250f849372d@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r584cf871f188c406d8bd447ff4e2fd9817fca862436c064d0951a071@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5baac01f9e06c40ff7aab209d5751b3b58802c63734e33324b70a06a@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5cbea8614812289a9b98d0cfc54b47f54cef424ac98d5e315b791795@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5f2f120b2b8d099226473db1832ffb4d7c1d6dc2d228a164bf293a8e@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r602e98daacc98934f097f07f2eed6eb07c18bfc1949c8489dc7bfcf5@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r61564d86a75403b854cdafee67fc69c8b88c5f6802c2c838f4282cc8@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r69efd8ef003f612c43e4154e788ca3b1f837feaacd16d97854402355@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r6dac9bd799ceac499c7a7e152a9b0dc7f2fe7f89ec5605d129bb047b@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r70c3a7bfa904f06a1902f4df20ee26e4f09a46b8fd3eb304dc57a2de@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r7879ddcb990c835c6b246654770d836f9d031dee982be836744e50ed@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r7b54563abebe3dbbe421e1ba075c2030d8d460372f8c79b7789684b6@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r823d4b27fcba8dad5fe945bdefce3ca5a0031187966eb6ef3cc22ba9@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r855b4b6814ac829ce2d48dd9d8138d07f33387e710de798ee92c011e@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r967002f0939e69bdec58f070735a19dd57c1f2b8f817949ca17cddae@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r9ec78dc409f3f1edff88f21cab53737f36aad46f582a9825389092e0@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r9fe840c36b74f92b8d4a089ada1f9fd1d6293742efa18b10e06b66d2@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra64d56a8a331ffd7bdcd24a9aaaeeedeacd5d639f5a683389123f898@%3Cdev.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra655e5cec74d1ddf62adacb71d398abd96f3ea2c588f6bbf048348eb@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra66e93703e3f4bd31bdfd0b6fb0c32ae96b528259bb1aa2b6d38e401@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/raa413040db6d2197593cc03edecfd168732e697119e6447b0a25d525@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rac8cf45a1bab9ead5c9a860cbadd6faaeb7792203617b6ec3874736d@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rafc77f9f03031297394f3d372ccea751b23576f8a2ae9b6b053894c5@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rba2a9ef1d0af882ab58fadb336a58818495245dda43d32a7d7837187@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rbde2f13daf4911504f0eaea43eee4f42555241b5f6d9d71564b6c5fa@%3Cjira.kafka.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rca0978b634a0c3ebee4126ec29c7f570b165fae3f8f3658754c1cbd3@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rcae42fba06979934208bbd515584b241d3ad01d1bb8b063512644362@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rd4a6b7dec38ea6cd28b6f94bd4b312629a52b80be3786d5fb0e474bc@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rd8f72411fb75b98d366400ae789966373b5c3eb3f511e717caf3e49e@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rdd206d9dd7eb894cc089b37fe6edde2932de88d63a6d8368b44f5101@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rdd5715f3ee5e3216d5e0083a07994f67da6dbb9731ce9e7a6389b18e@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re1911e05c08f3ec2bab85744d788773519a0afb27272a31ac2a0b4e8@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re39391adcb863f0e9f3f15e7986255948f263f02e4700b82453e7102@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re4b0141939370304d676fe23774d0c6fbc584b648919825402d0cb39@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re7c69756a102bebce8b8681882844a53e2f23975a189363e68ad0324@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re9e6ed60941da831675de2f8f733c026757fb4fa28a7b6c9f3dfb575@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/redef0fb5474fd686781007de9ddb852b24f1b04131a248d9a4789183@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf148b2bf6c2754153a8629bc7495e216bd0bd4c915695486542a10b4@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf38e4dcdefc7c59f7ba0799a399d6d6e37b555d406a1dfc2fcbf0b35@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf521ff2be2e2dd38984174d3451e6ee935c845948845c8fccd86371d@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf934292a4a1c189827f625d567838d2c1001e4739b158638d844105b@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20210604-0003/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4885"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com//security-alerts/cpujul2021.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujan2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuoct2021.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/netty/netty/commit/b0fa4d5aab4215f3c22ce6123dd8dd5f38dc0432"}, "type": "CWE-444"}
| 258
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Copyright 2016 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License, version 2.0 (the\n * \"License\"); you may not use this file except in compliance with the License. You may obtain a\n * copy of the License at:\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\npackage io.netty.handler.codec.http2;",
"import io.netty.buffer.ByteBuf;\nimport io.netty.buffer.Unpooled;\nimport io.netty.channel.Channel;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.channel.ChannelFutureListener;\nimport io.netty.channel.ChannelHandler;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.channel.ChannelInboundHandlerAdapter;\nimport io.netty.channel.ChannelOutboundHandlerAdapter;\nimport io.netty.channel.ChannelPromise;\nimport io.netty.channel.WriteBufferWaterMark;\nimport io.netty.channel.embedded.EmbeddedChannel;\nimport io.netty.handler.codec.http.HttpHeaderNames;\nimport io.netty.handler.codec.http.HttpMethod;\nimport io.netty.handler.codec.http.HttpScheme;\nimport io.netty.handler.codec.http2.Http2Exception.StreamException;\nimport io.netty.handler.codec.http2.LastInboundHandler.Consumer;\nimport io.netty.util.AsciiString;\nimport io.netty.util.AttributeKey;\nimport org.hamcrest.CoreMatchers;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.mockito.ArgumentMatcher;\nimport org.mockito.Mockito;\nimport org.mockito.invocation.InvocationOnMock;\nimport org.mockito.stubbing.Answer;",
"import java.net.InetSocketAddress;\nimport java.nio.channels.ClosedChannelException;\nimport java.util.ArrayDeque;\nimport java.util.Queue;\nimport java.util.UUID;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;",
"import static io.netty.handler.codec.http2.Http2TestUtil.anyChannelPromise;\nimport static io.netty.handler.codec.http2.Http2TestUtil.anyHttp2Settings;\nimport static io.netty.handler.codec.http2.Http2TestUtil.assertEqualsAndRelease;\nimport static io.netty.handler.codec.http2.Http2TestUtil.bb;\nimport static io.netty.util.ReferenceCountUtil.release;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.ArgumentMatchers.anyBoolean;\nimport static org.mockito.ArgumentMatchers.anyInt;\nimport static org.mockito.ArgumentMatchers.anyLong;\nimport static org.mockito.ArgumentMatchers.argThat;\nimport static org.mockito.ArgumentMatchers.eq;\nimport static org.mockito.Mockito.never;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\nimport static org.hamcrest.MatcherAssert.assertThat;",
"public abstract class Http2MultiplexTest<C extends Http2FrameCodec> {\n private final Http2Headers request = new DefaultHttp2Headers()\n .method(HttpMethod.GET.asciiName()).scheme(HttpScheme.HTTPS.name())\n .authority(new AsciiString(\"example.org\")).path(new AsciiString(\"/foo\"));",
" private EmbeddedChannel parentChannel;\n private Http2FrameWriter frameWriter;\n private Http2FrameInboundWriter frameInboundWriter;\n private TestChannelInitializer childChannelInitializer;\n private C codec;",
" private static final int initialRemoteStreamWindow = 1024;",
" protected abstract C newCodec(TestChannelInitializer childChannelInitializer, Http2FrameWriter frameWriter);\n protected abstract ChannelHandler newMultiplexer(TestChannelInitializer childChannelInitializer);",
" @Before\n public void setUp() {\n childChannelInitializer = new TestChannelInitializer();\n parentChannel = new EmbeddedChannel();\n frameInboundWriter = new Http2FrameInboundWriter(parentChannel);\n parentChannel.connect(new InetSocketAddress(0));\n frameWriter = Http2TestUtil.mockedFrameWriter();\n codec = newCodec(childChannelInitializer, frameWriter);\n parentChannel.pipeline().addLast(codec);\n ChannelHandler multiplexer = newMultiplexer(childChannelInitializer);\n if (multiplexer != null) {\n parentChannel.pipeline().addLast(multiplexer);\n }",
" parentChannel.runPendingTasks();\n parentChannel.pipeline().fireChannelActive();",
" parentChannel.writeInbound(Http2CodecUtil.connectionPrefaceBuf());",
" Http2Settings settings = new Http2Settings().initialWindowSize(initialRemoteStreamWindow);\n frameInboundWriter.writeInboundSettings(settings);",
" verify(frameWriter).writeSettingsAck(eqCodecCtx(), anyChannelPromise());",
" frameInboundWriter.writeInboundSettingsAck();",
" Http2SettingsFrame settingsFrame = parentChannel.readInbound();\n assertNotNull(settingsFrame);\n Http2SettingsAckFrame settingsAckFrame = parentChannel.readInbound();\n assertNotNull(settingsAckFrame);",
" // Handshake\n verify(frameWriter).writeSettings(eqCodecCtx(),\n anyHttp2Settings(), anyChannelPromise());\n }",
" private ChannelHandlerContext eqCodecCtx() {\n return eq(codec.ctx);\n }",
" @After\n public void tearDown() throws Exception {\n if (childChannelInitializer.handler instanceof LastInboundHandler) {\n ((LastInboundHandler) childChannelInitializer.handler).finishAndReleaseAll();\n }\n parentChannel.finishAndReleaseAll();\n codec = null;\n }",
" // TODO(buchgr): Flush from child channel\n // TODO(buchgr): ChildChannel.childReadComplete()\n // TODO(buchgr): GOAWAY Logic\n // TODO(buchgr): Test ChannelConfig.setMaxMessagesPerRead",
" @Test\n public void writeUnknownFrame() {\n Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter() {\n @Override\n public void channelActive(ChannelHandlerContext ctx) {\n ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));\n ctx.writeAndFlush(new DefaultHttp2UnknownFrame((byte) 99, new Http2Flags()));\n ctx.fireChannelActive();\n }\n });\n assertTrue(childChannel.isActive());",
" parentChannel.runPendingTasks();",
" verify(frameWriter).writeFrame(eq(codec.ctx), eq((byte) 99), eqStreamId(childChannel), any(Http2Flags.class),\n any(ByteBuf.class), any(ChannelPromise.class));\n }",
" private Http2StreamChannel newInboundStream(int streamId, boolean endStream, final ChannelHandler childHandler) {\n return newInboundStream(streamId, endStream, null, childHandler);\n }",
" private Http2StreamChannel newInboundStream(int streamId, boolean endStream,\n AtomicInteger maxReads, final ChannelHandler childHandler) {\n final AtomicReference<Http2StreamChannel> streamChannelRef = new AtomicReference<Http2StreamChannel>();\n childChannelInitializer.maxReads = maxReads;\n childChannelInitializer.handler = new ChannelInboundHandlerAdapter() {\n @Override\n public void channelRegistered(ChannelHandlerContext ctx) {\n assertNull(streamChannelRef.get());\n streamChannelRef.set((Http2StreamChannel) ctx.channel());\n ctx.pipeline().addLast(childHandler);\n ctx.fireChannelRegistered();\n }\n };",
" frameInboundWriter.writeInboundHeaders(streamId, request, 0, endStream);\n parentChannel.runPendingTasks();\n Http2StreamChannel channel = streamChannelRef.get();\n assertEquals(streamId, channel.stream().id());\n return channel;\n }",
" @Test\n public void readUnkownFrame() {\n LastInboundHandler handler = new LastInboundHandler();",
" Http2StreamChannel channel = newInboundStream(3, true, handler);\n frameInboundWriter.writeInboundFrame((byte) 99, channel.stream().id(), new Http2Flags(), Unpooled.EMPTY_BUFFER);",
" // header frame and unknown frame\n verifyFramesMultiplexedToCorrectChannel(channel, handler, 2);",
" Channel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter());\n assertTrue(childChannel.isActive());\n }",
" @Test\n public void headerAndDataFramesShouldBeDelivered() {\n LastInboundHandler inboundHandler = new LastInboundHandler();",
" Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);\n Http2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(request).stream(channel.stream());\n Http2DataFrame dataFrame1 = new DefaultHttp2DataFrame(bb(\"hello\")).stream(channel.stream());\n Http2DataFrame dataFrame2 = new DefaultHttp2DataFrame(bb(\"world\")).stream(channel.stream());",
" assertTrue(inboundHandler.isChannelActive());\n frameInboundWriter.writeInboundData(channel.stream().id(), bb(\"hello\"), 0, false);\n frameInboundWriter.writeInboundData(channel.stream().id(), bb(\"world\"), 0, false);",
" assertEquals(headersFrame, inboundHandler.readInbound());",
" assertEqualsAndRelease(dataFrame1, inboundHandler.<Http2Frame>readInbound());\n assertEqualsAndRelease(dataFrame2, inboundHandler.<Http2Frame>readInbound());",
" assertNull(inboundHandler.readInbound());\n }",
" @Test\n public void headerMultipleContentLengthValidationShouldPropagate() {",
"",
" LastInboundHandler inboundHandler = new LastInboundHandler();\n request.addLong(HttpHeaderNames.CONTENT_LENGTH, 0);\n request.addLong(HttpHeaderNames.CONTENT_LENGTH, 1);",
" Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);",
" try {\n inboundHandler.checkException();\n fail();\n } catch (Exception e) {\n assertThat(e, CoreMatchers.<Exception>instanceOf(StreamException.class));\n }\n assertNull(inboundHandler.readInbound());\n assertFalse(channel.isActive());\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagate() {\n headerContentLengthNotMatchValidationShouldPropagate(false, false, false);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateWithEndStream() {\n headerContentLengthNotMatchValidationShouldPropagate(false, true, false);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateCloseLocal() {\n headerContentLengthNotMatchValidationShouldPropagate(true, false, false);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateWithEndStreamCloseLocal() {\n headerContentLengthNotMatchValidationShouldPropagate(true, true, false);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateTrailers() {\n headerContentLengthNotMatchValidationShouldPropagate(false, false, true);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateWithEndStreamTrailers() {\n headerContentLengthNotMatchValidationShouldPropagate(false, true, true);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateCloseLocalTrailers() {\n headerContentLengthNotMatchValidationShouldPropagate(true, false, true);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateWithEndStreamCloseLocalTrailers() {\n headerContentLengthNotMatchValidationShouldPropagate(true, true, true);\n }",
" private void headerContentLengthNotMatchValidationShouldPropagate(\n boolean closeLocal, boolean endStream, boolean trailer) {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n request.addLong(HttpHeaderNames.CONTENT_LENGTH, 1);\n Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);\n assertTrue(channel.isActive());",
" if (closeLocal) {\n channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), true))\n .syncUninterruptibly();\n assertEquals(Http2Stream.State.HALF_CLOSED_LOCAL, channel.stream().state());\n } else {\n assertEquals(Http2Stream.State.OPEN, channel.stream().state());\n }",
" if (trailer) {\n frameInboundWriter.writeInboundHeaders(channel.stream().id(), new DefaultHttp2Headers(), 0, endStream);\n } else {\n frameInboundWriter.writeInboundData(channel.stream().id(), bb(\"foo\"), 0, endStream);\n }\n try {\n inboundHandler.checkException();\n fail();\n } catch (Exception e) {\n assertThat(e, CoreMatchers.<Exception>instanceOf(StreamException.class));\n }\n Http2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(request).stream(channel.stream());\n assertEquals(headersFrame, inboundHandler.readInbound());\n assertNull(inboundHandler.readInbound());\n assertFalse(channel.isActive());\n }",
" @Test\n public void framesShouldBeMultiplexed() {\n LastInboundHandler handler1 = new LastInboundHandler();\n Http2StreamChannel channel1 = newInboundStream(3, false, handler1);\n LastInboundHandler handler2 = new LastInboundHandler();\n Http2StreamChannel channel2 = newInboundStream(5, false, handler2);\n LastInboundHandler handler3 = new LastInboundHandler();\n Http2StreamChannel channel3 = newInboundStream(11, false, handler3);",
" verifyFramesMultiplexedToCorrectChannel(channel1, handler1, 1);\n verifyFramesMultiplexedToCorrectChannel(channel2, handler2, 1);\n verifyFramesMultiplexedToCorrectChannel(channel3, handler3, 1);",
" frameInboundWriter.writeInboundData(channel2.stream().id(), bb(\"hello\"), 0, false);\n frameInboundWriter.writeInboundData(channel1.stream().id(), bb(\"foo\"), 0, true);\n frameInboundWriter.writeInboundData(channel2.stream().id(), bb(\"world\"), 0, true);\n frameInboundWriter.writeInboundData(channel3.stream().id(), bb(\"bar\"), 0, true);",
" verifyFramesMultiplexedToCorrectChannel(channel1, handler1, 1);\n verifyFramesMultiplexedToCorrectChannel(channel2, handler2, 2);\n verifyFramesMultiplexedToCorrectChannel(channel3, handler3, 1);\n }",
" @Test\n public void inboundDataFrameShouldUpdateLocalFlowController() throws Http2Exception {\n Http2LocalFlowController flowController = Mockito.mock(Http2LocalFlowController.class);\n codec.connection().local().flowController(flowController);",
" LastInboundHandler handler = new LastInboundHandler();\n final Http2StreamChannel channel = newInboundStream(3, false, handler);",
" ByteBuf tenBytes = bb(\"0123456789\");",
" frameInboundWriter.writeInboundData(channel.stream().id(), tenBytes, 0, true);",
" // Verify we marked the bytes as consumed\n verify(flowController).consumeBytes(argThat(new ArgumentMatcher<Http2Stream>() {\n @Override\n public boolean matches(Http2Stream http2Stream) {\n return http2Stream.id() == channel.stream().id();\n }\n }), eq(10));",
" // headers and data frame\n verifyFramesMultiplexedToCorrectChannel(channel, handler, 2);\n }",
" @Test\n public void unhandledHttp2FramesShouldBePropagated() {\n Http2PingFrame pingFrame = new DefaultHttp2PingFrame(0);\n frameInboundWriter.writeInboundPing(false, 0);\n assertEquals(parentChannel.readInbound(), pingFrame);",
" DefaultHttp2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame(1,\n parentChannel.alloc().buffer().writeLong(8));\n frameInboundWriter.writeInboundGoAway(0, goAwayFrame.errorCode(), goAwayFrame.content().retainedDuplicate());",
" Http2GoAwayFrame frame = parentChannel.readInbound();\n assertEqualsAndRelease(frame, goAwayFrame);\n }",
" @Test\n public void channelReadShouldRespectAutoRead() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n assertTrue(childChannel.config().isAutoRead());\n Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);",
" childChannel.config().setAutoRead(false);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world\"), 0, false);\n Http2DataFrame dataFrame0 = inboundHandler.readInbound();\n assertNotNull(dataFrame0);\n release(dataFrame0);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, false);",
" assertNull(inboundHandler.readInbound());",
" childChannel.config().setAutoRead(true);\n verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 2);\n }",
" @Test\n public void channelReadShouldRespectAutoReadAndNotProduceNPE() throws Exception {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n assertTrue(childChannel.config().isAutoRead());\n Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);",
" childChannel.config().setAutoRead(false);\n childChannel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {\n private int count;\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n ctx.fireChannelRead(msg);\n // Close channel after 2 reads so there is still something in the inboundBuffer when the close happens.\n if (++count == 2) {\n ctx.close();\n }\n }\n });\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world\"), 0, false);\n Http2DataFrame dataFrame0 = inboundHandler.readInbound();\n assertNotNull(dataFrame0);\n release(dataFrame0);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, false);",
" assertNull(inboundHandler.readInbound());",
" childChannel.config().setAutoRead(true);\n verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 3);\n inboundHandler.checkException();\n }",
" @Test\n public void readInChannelReadWithoutAutoRead() {\n useReadWithoutAutoRead(false);\n }",
" @Test\n public void readInChannelReadCompleteWithoutAutoRead() {\n useReadWithoutAutoRead(true);\n }",
" private void useReadWithoutAutoRead(final boolean readComplete) {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n assertTrue(childChannel.config().isAutoRead());\n childChannel.config().setAutoRead(false);\n assertFalse(childChannel.config().isAutoRead());",
" Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);",
" // Add a handler which will request reads.\n childChannel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) {\n ctx.fireChannelRead(msg);\n if (!readComplete) {\n ctx.read();\n }\n }",
" @Override\n public void channelReadComplete(ChannelHandlerContext ctx) {\n ctx.fireChannelReadComplete();\n if (readComplete) {\n ctx.read();\n }\n }\n });",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, true);",
" verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 6);\n }",
" private Http2StreamChannel newOutboundStream(ChannelHandler handler) {\n return new Http2StreamChannelBootstrap(parentChannel).handler(handler)\n .open().syncUninterruptibly().getNow();\n }",
" /**\n * A child channel for an HTTP/2 stream in IDLE state (that is no headers sent or received),\n * should not emit a RST_STREAM frame on close, as this is a connection error of type protocol error.\n */\n @Test\n public void idleOutboundStreamShouldNotWriteResetFrameOnClose() {\n LastInboundHandler handler = new LastInboundHandler();",
" Channel childChannel = newOutboundStream(handler);\n assertTrue(childChannel.isActive());",
" childChannel.close();\n parentChannel.runPendingTasks();",
" assertFalse(childChannel.isOpen());\n assertFalse(childChannel.isActive());\n assertNull(parentChannel.readOutbound());\n }",
" @Test\n public void outboundStreamShouldWriteResetFrameOnClose_headersSent() {\n ChannelHandler handler = new ChannelInboundHandlerAdapter() {\n @Override\n public void channelActive(ChannelHandlerContext ctx) {\n ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));\n ctx.fireChannelActive();\n }\n };",
" Http2StreamChannel childChannel = newOutboundStream(handler);\n assertTrue(childChannel.isActive());",
" childChannel.close();\n verify(frameWriter).writeRstStream(eqCodecCtx(),\n eqStreamId(childChannel), eq(Http2Error.CANCEL.code()), anyChannelPromise());\n }",
" @Test\n public void outboundStreamShouldNotWriteResetFrameOnClose_IfStreamDidntExist() {\n when(frameWriter.writeHeaders(eqCodecCtx(), anyInt(),\n any(Http2Headers.class), anyInt(), anyBoolean(),\n any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {",
" private boolean headersWritten;\n @Override\n public ChannelFuture answer(InvocationOnMock invocationOnMock) {\n // We want to fail to write the first headers frame. This is what happens if the connection\n // refuses to allocate a new stream due to having received a GOAWAY.\n if (!headersWritten) {\n headersWritten = true;\n return ((ChannelPromise) invocationOnMock.getArgument(5)).setFailure(new Exception(\"boom\"));\n }\n return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();\n }\n });",
" Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter() {\n @Override\n public void channelActive(ChannelHandlerContext ctx) {\n ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));\n ctx.fireChannelActive();\n }\n });",
" assertFalse(childChannel.isActive());",
" childChannel.close();\n parentChannel.runPendingTasks();\n // The channel was never active so we should not generate a RST frame.\n verify(frameWriter, never()).writeRstStream(eqCodecCtx(), eqStreamId(childChannel), anyLong(),\n anyChannelPromise());",
" assertTrue(parentChannel.outboundMessages().isEmpty());\n }",
" @Test\n public void inboundRstStreamFireChannelInactive() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);\n assertTrue(inboundHandler.isChannelActive());\n frameInboundWriter.writeInboundRstStream(channel.stream().id(), Http2Error.INTERNAL_ERROR.code());",
" assertFalse(inboundHandler.isChannelActive());",
" // A RST_STREAM frame should NOT be emitted, as we received a RST_STREAM.\n verify(frameWriter, Mockito.never()).writeRstStream(eqCodecCtx(), eqStreamId(channel),\n anyLong(), anyChannelPromise());\n }",
" @Test(expected = StreamException.class)\n public void streamExceptionTriggersChildChannelExceptionAndClose() throws Exception {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);\n assertTrue(channel.isActive());\n StreamException cause = new StreamException(channel.stream().id(), Http2Error.PROTOCOL_ERROR, \"baaam!\");\n parentChannel.pipeline().fireExceptionCaught(cause);",
" assertFalse(channel.isActive());\n inboundHandler.checkException();\n }",
" @Test(expected = ClosedChannelException.class)\n public void streamClosedErrorTranslatedToClosedChannelExceptionOnWrites() throws Exception {\n LastInboundHandler inboundHandler = new LastInboundHandler();",
" final Http2StreamChannel childChannel = newOutboundStream(inboundHandler);\n assertTrue(childChannel.isActive());",
" Http2Headers headers = new DefaultHttp2Headers();\n when(frameWriter.writeHeaders(eqCodecCtx(), anyInt(),\n eq(headers), anyInt(), anyBoolean(),\n any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {\n @Override\n public ChannelFuture answer(InvocationOnMock invocationOnMock) {\n return ((ChannelPromise) invocationOnMock.getArgument(5)).setFailure(\n new StreamException(childChannel.stream().id(), Http2Error.STREAM_CLOSED, \"Stream Closed\"));\n }\n });\n ChannelFuture future = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));",
" parentChannel.flush();",
" assertFalse(childChannel.isActive());\n assertFalse(childChannel.isOpen());",
" inboundHandler.checkException();",
" future.syncUninterruptibly();\n }",
" @Test\n public void creatingWritingReadingAndClosingOutboundStreamShouldWork() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newOutboundStream(inboundHandler);\n assertTrue(childChannel.isActive());\n assertTrue(inboundHandler.isChannelActive());",
" // Write to the child channel\n Http2Headers headers = new DefaultHttp2Headers().scheme(\"https\").method(\"GET\").path(\"/foo.txt\");\n childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(headers));",
" // Read from the child channel\n frameInboundWriter.writeInboundHeaders(childChannel.stream().id(), headers, 0, false);",
" Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);\n assertEquals(headers, headersFrame.headers());",
" // Close the child channel.\n childChannel.close();",
" parentChannel.runPendingTasks();\n // An active outbound stream should emit a RST_STREAM frame.\n verify(frameWriter).writeRstStream(eqCodecCtx(), eqStreamId(childChannel),\n anyLong(), anyChannelPromise());",
" assertFalse(childChannel.isOpen());\n assertFalse(childChannel.isActive());\n assertFalse(inboundHandler.isChannelActive());\n }",
" // Test failing the promise of the first headers frame of an outbound stream. In practice this error case would most\n // likely happen due to the max concurrent streams limit being hit or the channel running out of stream identifiers.\n //\n @Test(expected = Http2NoMoreStreamIdsException.class)\n public void failedOutboundStreamCreationThrowsAndClosesChannel() throws Exception {\n LastInboundHandler handler = new LastInboundHandler();\n Http2StreamChannel childChannel = newOutboundStream(handler);\n assertTrue(childChannel.isActive());",
" Http2Headers headers = new DefaultHttp2Headers();\n when(frameWriter.writeHeaders(eqCodecCtx(), anyInt(),\n eq(headers), anyInt(), anyBoolean(),\n any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {\n @Override\n public ChannelFuture answer(InvocationOnMock invocationOnMock) {\n return ((ChannelPromise) invocationOnMock.getArgument(5)).setFailure(\n new Http2NoMoreStreamIdsException());\n }\n });",
" ChannelFuture future = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(headers));\n parentChannel.flush();",
" assertFalse(childChannel.isActive());\n assertFalse(childChannel.isOpen());",
" handler.checkException();",
" future.syncUninterruptibly();\n }",
" @Test\n public void channelClosedWhenCloseListenerCompletes() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);",
" assertTrue(childChannel.isOpen());\n assertTrue(childChannel.isActive());",
" final AtomicBoolean channelOpen = new AtomicBoolean(true);\n final AtomicBoolean channelActive = new AtomicBoolean(true);",
" // Create a promise before actually doing the close, because otherwise we would be adding a listener to a future\n // that is already completed because we are using EmbeddedChannel which executes code in the JUnit thread.\n ChannelPromise p = childChannel.newPromise();\n p.addListener(new ChannelFutureListener() {\n @Override\n public void operationComplete(ChannelFuture future) {\n channelOpen.set(future.channel().isOpen());\n channelActive.set(future.channel().isActive());\n }\n });\n childChannel.close(p).syncUninterruptibly();",
" assertFalse(channelOpen.get());\n assertFalse(channelActive.get());\n assertFalse(childChannel.isActive());\n }",
" @Test\n public void channelClosedWhenChannelClosePromiseCompletes() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);",
" assertTrue(childChannel.isOpen());\n assertTrue(childChannel.isActive());",
" final AtomicBoolean channelOpen = new AtomicBoolean(true);\n final AtomicBoolean channelActive = new AtomicBoolean(true);",
" childChannel.closeFuture().addListener(new ChannelFutureListener() {\n @Override\n public void operationComplete(ChannelFuture future) {\n channelOpen.set(future.channel().isOpen());\n channelActive.set(future.channel().isActive());\n }\n });\n childChannel.close().syncUninterruptibly();",
" assertFalse(channelOpen.get());\n assertFalse(channelActive.get());\n assertFalse(childChannel.isActive());\n }",
" @Test\n public void channelClosedWhenWriteFutureFails() {\n final Queue<ChannelPromise> writePromises = new ArrayDeque<ChannelPromise>();",
" LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);",
" assertTrue(childChannel.isOpen());\n assertTrue(childChannel.isActive());",
" final AtomicBoolean channelOpen = new AtomicBoolean(true);\n final AtomicBoolean channelActive = new AtomicBoolean(true);",
" Http2Headers headers = new DefaultHttp2Headers();\n when(frameWriter.writeHeaders(eqCodecCtx(), anyInt(),\n eq(headers), anyInt(), anyBoolean(),\n any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {\n @Override\n public ChannelFuture answer(InvocationOnMock invocationOnMock) {\n ChannelPromise promise = invocationOnMock.getArgument(5);\n writePromises.offer(promise);\n return promise;\n }\n });",
" ChannelFuture f = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(headers));\n assertFalse(f.isDone());\n f.addListener(new ChannelFutureListener() {\n @Override\n public void operationComplete(ChannelFuture future) throws Exception {\n channelOpen.set(future.channel().isOpen());\n channelActive.set(future.channel().isActive());\n }\n });",
" ChannelPromise first = writePromises.poll();\n first.setFailure(new ClosedChannelException());\n f.awaitUninterruptibly();",
" assertFalse(channelOpen.get());\n assertFalse(channelActive.get());\n assertFalse(childChannel.isActive());\n }",
" @Test\n public void channelClosedTwiceMarksPromiseAsSuccessful() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);",
" assertTrue(childChannel.isOpen());\n assertTrue(childChannel.isActive());\n childChannel.close().syncUninterruptibly();\n childChannel.close().syncUninterruptibly();",
" assertFalse(childChannel.isOpen());\n assertFalse(childChannel.isActive());\n }",
" @Test\n public void settingChannelOptsAndAttrs() {\n AttributeKey<String> key = AttributeKey.newInstance(UUID.randomUUID().toString());",
" Channel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter());\n childChannel.config().setAutoRead(false).setWriteSpinCount(1000);\n childChannel.attr(key).set(\"bar\");\n assertFalse(childChannel.config().isAutoRead());\n assertEquals(1000, childChannel.config().getWriteSpinCount());\n assertEquals(\"bar\", childChannel.attr(key).get());\n }",
" @Test\n public void outboundFlowControlWritability() {\n Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter());\n assertTrue(childChannel.isActive());",
" assertTrue(childChannel.isWritable());\n childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));\n parentChannel.flush();",
" // Test for initial window size\n assertTrue(initialRemoteStreamWindow < childChannel.config().getWriteBufferHighWaterMark());",
" assertTrue(childChannel.isWritable());\n childChannel.write(new DefaultHttp2DataFrame(Unpooled.buffer().writeZero(16 * 1024 * 1024)));\n assertEquals(0, childChannel.bytesBeforeUnwritable());\n assertFalse(childChannel.isWritable());\n }",
" @Test\n public void writabilityOfParentIsRespected() {\n Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter());\n childChannel.config().setWriteBufferWaterMark(new WriteBufferWaterMark(2048, 4096));\n parentChannel.config().setWriteBufferWaterMark(new WriteBufferWaterMark(256, 512));\n assertTrue(childChannel.isWritable());\n assertTrue(parentChannel.isActive());",
" childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));\n parentChannel.flush();",
" assertTrue(childChannel.isWritable());\n childChannel.write(new DefaultHttp2DataFrame(Unpooled.buffer().writeZero(256)));\n assertTrue(childChannel.isWritable());\n childChannel.writeAndFlush(new DefaultHttp2DataFrame(Unpooled.buffer().writeZero(512)));",
" long bytesBeforeUnwritable = childChannel.bytesBeforeUnwritable();\n assertNotEquals(0, bytesBeforeUnwritable);\n // Add something to the ChannelOutboundBuffer of the parent to simulate queuing in the parents channel buffer\n // and verify that this only affect the writability of the parent channel while the child stays writable\n // until it used all of its credits.\n parentChannel.unsafe().outboundBuffer().addMessage(\n Unpooled.buffer().writeZero(800), 800, parentChannel.voidPromise());\n assertFalse(parentChannel.isWritable());",
" assertTrue(childChannel.isWritable());\n assertEquals(4096, childChannel.bytesBeforeUnwritable());",
" // Flush everything which simulate writing everything to the socket.\n parentChannel.flush();\n assertTrue(parentChannel.isWritable());\n assertTrue(childChannel.isWritable());\n assertEquals(bytesBeforeUnwritable, childChannel.bytesBeforeUnwritable());",
" ChannelFuture future = childChannel.writeAndFlush(new DefaultHttp2DataFrame(\n Unpooled.buffer().writeZero((int) bytesBeforeUnwritable)));\n assertFalse(childChannel.isWritable());\n assertTrue(parentChannel.isWritable());",
" parentChannel.flush();\n assertFalse(future.isDone());\n assertTrue(parentChannel.isWritable());\n assertFalse(childChannel.isWritable());",
" // Now write an window update frame for the stream which then should ensure we will flush the bytes that were\n // queued in the RemoteFlowController before for the stream.\n frameInboundWriter.writeInboundWindowUpdate(childChannel.stream().id(), (int) bytesBeforeUnwritable);\n assertTrue(childChannel.isWritable());\n assertTrue(future.isDone());\n }",
" @Test\n public void channelClosedWhenInactiveFired() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);",
" final AtomicBoolean channelOpen = new AtomicBoolean(false);\n final AtomicBoolean channelActive = new AtomicBoolean(false);\n assertTrue(childChannel.isOpen());\n assertTrue(childChannel.isActive());",
" childChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {\n @Override\n public void channelInactive(ChannelHandlerContext ctx) throws Exception {\n channelOpen.set(ctx.channel().isOpen());\n channelActive.set(ctx.channel().isActive());",
" super.channelInactive(ctx);\n }\n });",
" childChannel.close().syncUninterruptibly();\n assertFalse(channelOpen.get());\n assertFalse(channelActive.get());\n }",
" @Test\n public void channelInactiveHappensAfterExceptionCaughtEvents() throws Exception {\n final AtomicInteger count = new AtomicInteger(0);\n final AtomicInteger exceptionCaught = new AtomicInteger(-1);\n final AtomicInteger channelInactive = new AtomicInteger(-1);\n final AtomicInteger channelUnregistered = new AtomicInteger(-1);\n Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter() {",
" @Override\n public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {\n ctx.close();\n throw new Exception(\"exception\");\n }\n });",
" childChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {",
" @Override\n public void channelInactive(ChannelHandlerContext ctx) throws Exception {\n channelInactive.set(count.getAndIncrement());\n super.channelInactive(ctx);\n }",
" @Override\n public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {\n exceptionCaught.set(count.getAndIncrement());\n super.exceptionCaught(ctx, cause);\n }",
" @Override\n public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {\n channelUnregistered.set(count.getAndIncrement());\n super.channelUnregistered(ctx);\n }\n });",
" childChannel.pipeline().fireUserEventTriggered(new Object());\n parentChannel.runPendingTasks();",
" // The events should have happened in this order because the inactive and deregistration events\n // get deferred as they do in the AbstractChannel.\n assertEquals(0, exceptionCaught.get());\n assertEquals(1, channelInactive.get());\n assertEquals(2, channelUnregistered.get());\n }",
" @Test\n public void callUnsafeCloseMultipleTimes() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n childChannel.unsafe().close(childChannel.voidPromise());",
" ChannelPromise promise = childChannel.newPromise();\n childChannel.unsafe().close(promise);\n promise.syncUninterruptibly();\n childChannel.closeFuture().syncUninterruptibly();\n }",
" @Test\n public void endOfStreamDoesNotDiscardData() {\n AtomicInteger numReads = new AtomicInteger(1);\n final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean();\n Consumer<ChannelHandlerContext> ctxConsumer = new Consumer<ChannelHandlerContext>() {\n @Override\n public void accept(ChannelHandlerContext obj) {\n if (shouldDisableAutoRead.get()) {\n obj.channel().config().setAutoRead(false);\n }\n }\n };\n LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer);\n Http2StreamChannel childChannel = newInboundStream(3, false, numReads, inboundHandler);\n childChannel.config().setAutoRead(false);",
" Http2DataFrame dataFrame1 = new DefaultHttp2DataFrame(bb(\"1\")).stream(childChannel.stream());\n Http2DataFrame dataFrame2 = new DefaultHttp2DataFrame(bb(\"2\")).stream(childChannel.stream());\n Http2DataFrame dataFrame3 = new DefaultHttp2DataFrame(bb(\"3\")).stream(childChannel.stream());\n Http2DataFrame dataFrame4 = new DefaultHttp2DataFrame(bb(\"4\")).stream(childChannel.stream());",
" assertEquals(new DefaultHttp2HeadersFrame(request).stream(childChannel.stream()), inboundHandler.readInbound());",
" ChannelHandler readCompleteSupressHandler = new ChannelInboundHandlerAdapter() {\n @Override\n public void channelReadComplete(ChannelHandlerContext ctx) {\n // We want to simulate the parent channel calling channelRead and delay calling channelReadComplete.\n }\n };",
" parentChannel.pipeline().addFirst(readCompleteSupressHandler);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"1\"), 0, false);",
" assertEqualsAndRelease(dataFrame1, inboundHandler.<Http2DataFrame>readInbound());",
" // Deliver frames, and then a stream closed while read is inactive.\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"2\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"3\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"4\"), 0, false);",
" shouldDisableAutoRead.set(true);\n childChannel.config().setAutoRead(true);\n numReads.set(1);",
" frameInboundWriter.writeInboundRstStream(childChannel.stream().id(), Http2Error.NO_ERROR.code());",
" // Detecting EOS should flush all pending data regardless of read calls.\n assertEqualsAndRelease(dataFrame2, inboundHandler.<Http2DataFrame>readInbound());\n assertNull(inboundHandler.readInbound());",
" // As we limited the number to 1 we also need to call read() again.\n childChannel.read();",
" assertEqualsAndRelease(dataFrame3, inboundHandler.<Http2DataFrame>readInbound());\n assertEqualsAndRelease(dataFrame4, inboundHandler.<Http2DataFrame>readInbound());",
" Http2ResetFrame resetFrame = useUserEventForResetFrame() ? inboundHandler.<Http2ResetFrame>readUserEvent() :\n inboundHandler.<Http2ResetFrame>readInbound();",
" assertEquals(childChannel.stream(), resetFrame.stream());\n assertEquals(Http2Error.NO_ERROR.code(), resetFrame.errorCode());",
" assertNull(inboundHandler.readInbound());",
" // Now we want to call channelReadComplete and simulate the end of the read loop.\n parentChannel.pipeline().remove(readCompleteSupressHandler);\n parentChannel.flushInbound();",
" childChannel.closeFuture().syncUninterruptibly();\n }",
" protected abstract boolean useUserEventForResetFrame();",
" protected abstract boolean ignoreWindowUpdateFrames();",
" @Test\n public void windowUpdateFrames() {\n AtomicInteger numReads = new AtomicInteger(1);\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, numReads, inboundHandler);",
" assertEquals(new DefaultHttp2HeadersFrame(request).stream(childChannel.stream()), inboundHandler.readInbound());",
" frameInboundWriter.writeInboundWindowUpdate(childChannel.stream().id(), 4);",
" Http2WindowUpdateFrame updateFrame = inboundHandler.readInbound();\n if (ignoreWindowUpdateFrames()) {\n assertNull(updateFrame);\n } else {\n assertEquals(new DefaultHttp2WindowUpdateFrame(4).stream(childChannel.stream()), updateFrame);\n }",
" frameInboundWriter.writeInboundWindowUpdate(Http2CodecUtil.CONNECTION_STREAM_ID, 6);",
" assertNull(parentChannel.readInbound());\n childChannel.close().syncUninterruptibly();\n }",
" @Test\n public void childQueueIsDrainedAndNewDataIsDispatchedInParentReadLoopAutoRead() {\n AtomicInteger numReads = new AtomicInteger(1);\n final AtomicInteger channelReadCompleteCount = new AtomicInteger(0);\n final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean();\n Consumer<ChannelHandlerContext> ctxConsumer = new Consumer<ChannelHandlerContext>() {\n @Override\n public void accept(ChannelHandlerContext obj) {\n channelReadCompleteCount.incrementAndGet();\n if (shouldDisableAutoRead.get()) {\n obj.channel().config().setAutoRead(false);\n }\n }\n };\n LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer);\n Http2StreamChannel childChannel = newInboundStream(3, false, numReads, inboundHandler);\n childChannel.config().setAutoRead(false);",
" Http2DataFrame dataFrame1 = new DefaultHttp2DataFrame(bb(\"1\")).stream(childChannel.stream());\n Http2DataFrame dataFrame2 = new DefaultHttp2DataFrame(bb(\"2\")).stream(childChannel.stream());\n Http2DataFrame dataFrame3 = new DefaultHttp2DataFrame(bb(\"3\")).stream(childChannel.stream());\n Http2DataFrame dataFrame4 = new DefaultHttp2DataFrame(bb(\"4\")).stream(childChannel.stream());",
" assertEquals(new DefaultHttp2HeadersFrame(request).stream(childChannel.stream()), inboundHandler.readInbound());",
" ChannelHandler readCompleteSupressHandler = new ChannelInboundHandlerAdapter() {\n @Override\n public void channelReadComplete(ChannelHandlerContext ctx) {\n // We want to simulate the parent channel calling channelRead and delay calling channelReadComplete.\n }\n };\n parentChannel.pipeline().addFirst(readCompleteSupressHandler);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"1\"), 0, false);",
" assertEqualsAndRelease(dataFrame1, inboundHandler.<Http2DataFrame>readInbound());",
" // We want one item to be in the queue, and allow the numReads to be larger than 1. This will ensure that\n // when beginRead() is called the child channel is added to the readPending queue of the parent channel.\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"2\"), 0, false);",
" numReads.set(10);\n shouldDisableAutoRead.set(true);\n childChannel.config().setAutoRead(true);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"3\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"4\"), 0, false);",
" // Detecting EOS should flush all pending data regardless of read calls.\n assertEqualsAndRelease(dataFrame2, inboundHandler.<Http2DataFrame>readInbound());\n assertEqualsAndRelease(dataFrame3, inboundHandler.<Http2DataFrame>readInbound());\n assertEqualsAndRelease(dataFrame4, inboundHandler.<Http2DataFrame>readInbound());",
" assertNull(inboundHandler.readInbound());",
" // Now we want to call channelReadComplete and simulate the end of the read loop.\n parentChannel.pipeline().remove(readCompleteSupressHandler);\n parentChannel.flushInbound();",
" // 3 = 1 for initialization + 1 for read when auto read was off + 1 for when auto read was back on\n assertEquals(3, channelReadCompleteCount.get());\n }",
" @Test\n public void childQueueIsDrainedAndNewDataIsDispatchedInParentReadLoopNoAutoRead() {\n final AtomicInteger numReads = new AtomicInteger(1);\n final AtomicInteger channelReadCompleteCount = new AtomicInteger(0);\n final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean();\n Consumer<ChannelHandlerContext> ctxConsumer = new Consumer<ChannelHandlerContext>() {\n @Override\n public void accept(ChannelHandlerContext obj) {\n channelReadCompleteCount.incrementAndGet();\n if (shouldDisableAutoRead.get()) {\n obj.channel().config().setAutoRead(false);\n }\n }\n };\n final LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer);\n Http2StreamChannel childChannel = newInboundStream(3, false, numReads, inboundHandler);\n childChannel.config().setAutoRead(false);",
" Http2DataFrame dataFrame1 = new DefaultHttp2DataFrame(bb(\"1\")).stream(childChannel.stream());\n Http2DataFrame dataFrame2 = new DefaultHttp2DataFrame(bb(\"2\")).stream(childChannel.stream());\n Http2DataFrame dataFrame3 = new DefaultHttp2DataFrame(bb(\"3\")).stream(childChannel.stream());\n Http2DataFrame dataFrame4 = new DefaultHttp2DataFrame(bb(\"4\")).stream(childChannel.stream());",
" assertEquals(new DefaultHttp2HeadersFrame(request).stream(childChannel.stream()), inboundHandler.readInbound());",
" ChannelHandler readCompleteSupressHandler = new ChannelInboundHandlerAdapter() {\n @Override\n public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {\n // We want to simulate the parent channel calling channelRead and delay calling channelReadComplete.\n }\n };\n parentChannel.pipeline().addFirst(readCompleteSupressHandler);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"1\"), 0, false);",
" assertEqualsAndRelease(dataFrame1, inboundHandler.<Http2Frame>readInbound());",
" // We want one item to be in the queue, and allow the numReads to be larger than 1. This will ensure that\n // when beginRead() is called the child channel is added to the readPending queue of the parent channel.\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"2\"), 0, false);",
" numReads.set(2);\n childChannel.read();",
" assertEqualsAndRelease(dataFrame2, inboundHandler.<Http2Frame>readInbound());",
" assertNull(inboundHandler.readInbound());",
" // This is the second item that was read, this should be the last until we call read() again. This should also\n // notify of readComplete().\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"3\"), 0, false);",
" assertEqualsAndRelease(dataFrame3, inboundHandler.<Http2Frame>readInbound());",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"4\"), 0, false);\n assertNull(inboundHandler.readInbound());",
" childChannel.read();",
" assertEqualsAndRelease(dataFrame4, inboundHandler.<Http2Frame>readInbound());",
" assertNull(inboundHandler.readInbound());",
" // Now we want to call channelReadComplete and simulate the end of the read loop.\n parentChannel.pipeline().remove(readCompleteSupressHandler);\n parentChannel.flushInbound();",
" // 3 = 1 for initialization + 1 for first read of 2 items + 1 for second read of 2 items +\n // 1 for parent channel readComplete\n assertEquals(4, channelReadCompleteCount.get());\n }",
" @Test\n public void useReadWithoutAutoReadInRead() {\n useReadWithoutAutoReadBuffered(false);\n }",
" @Test\n public void useReadWithoutAutoReadInReadComplete() {\n useReadWithoutAutoReadBuffered(true);\n }",
" private void useReadWithoutAutoReadBuffered(final boolean triggerOnReadComplete) {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n assertTrue(childChannel.config().isAutoRead());\n childChannel.config().setAutoRead(false);\n assertFalse(childChannel.config().isAutoRead());",
" Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);",
" // Write some bytes to get the channel into the idle state with buffered data and also verify we\n // do not dispatch it until we receive a read() call.\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, false);",
" // Add a handler which will request reads.\n childChannel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {",
" @Override\n public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {\n super.channelReadComplete(ctx);\n if (triggerOnReadComplete) {\n ctx.read();\n ctx.read();\n }\n }",
" @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) {\n ctx.fireChannelRead(msg);\n if (!triggerOnReadComplete) {\n ctx.read();\n ctx.read();\n }\n }\n });",
" inboundHandler.channel().read();",
" verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 3);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world2\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo2\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar2\"), 0, true);",
" verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 3);\n }",
" private static final class FlushSniffer extends ChannelOutboundHandlerAdapter {",
" private boolean didFlush;",
" public boolean checkFlush() {\n boolean r = didFlush;\n didFlush = false;\n return r;\n }",
" @Override\n public void flush(ChannelHandlerContext ctx) throws Exception {\n didFlush = true;\n super.flush(ctx);\n }\n }",
" @Test\n public void windowUpdatesAreFlushed() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n FlushSniffer flushSniffer = new FlushSniffer();\n parentChannel.pipeline().addFirst(flushSniffer);",
" Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n assertTrue(childChannel.config().isAutoRead());\n childChannel.config().setAutoRead(false);\n assertFalse(childChannel.config().isAutoRead());",
" Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);",
" assertTrue(flushSniffer.checkFlush());",
" // Write some bytes to get the channel into the idle state with buffered data and also verify we\n // do not dispatch it until we receive a read() call.\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(16 * 1024), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(16 * 1024), 0, false);\n assertTrue(flushSniffer.checkFlush());",
" verify(frameWriter, never()).writeWindowUpdate(eqCodecCtx(), anyInt(), anyInt(), anyChannelPromise());\n // only the first one was read because it was legacy auto-read behavior.\n verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 1);\n assertFalse(flushSniffer.checkFlush());",
" // Trigger a read of the second frame.\n childChannel.read();\n verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 1);\n // We expect a flush here because the StreamChannel will flush the smaller increment but the\n // connection will collect the bytes and decide not to send a wire level frame until more are consumed.\n assertTrue(flushSniffer.checkFlush());\n verify(frameWriter, never()).writeWindowUpdate(eqCodecCtx(), anyInt(), anyInt(), anyChannelPromise());",
" // Call read one more time which should trigger the writing of the flow control update.\n childChannel.read();\n verify(frameWriter).writeWindowUpdate(eqCodecCtx(), eq(0), eq(32 * 1024), anyChannelPromise());\n verify(frameWriter).writeWindowUpdate(\n eqCodecCtx(), eq(childChannel.stream().id()), eq(32 * 1024), anyChannelPromise());\n assertTrue(flushSniffer.checkFlush());\n }",
" private static void verifyFramesMultiplexedToCorrectChannel(Http2StreamChannel streamChannel,\n LastInboundHandler inboundHandler,\n int numFrames) {\n for (int i = 0; i < numFrames; i++) {\n Http2StreamFrame frame = inboundHandler.readInbound();\n assertNotNull(i + \" out of \" + numFrames + \" received\", frame);\n assertEquals(streamChannel.stream(), frame.stream());\n release(frame);\n }\n assertNull(inboundHandler.readInbound());\n }",
" private static int eqStreamId(Http2StreamChannel channel) {\n return eq(channel.stream().id());\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [398, 231], "buggy_code_start_loc": [355, 226], "filenames": ["codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionDecoder.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexTest.java"], "fixing_code_end_loc": [401, 274], "fixing_code_start_loc": [356, 227], "message": "Netty is an open-source, asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. In Netty (io.netty:netty-codec-http2) before version 4.1.61.Final there is a vulnerability that enables request smuggling. The content-length header is not correctly validated if the request only uses a single Http2HeaderFrame with the endStream set to to true. This could lead to request smuggling if the request is proxied to a remote peer and translated to HTTP/1.1. This is a followup of GHSA-wm47-8v5p-wjpj/CVE-2021-21295 which did miss to fix this one case. This was fixed as part of 4.1.61.Final.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netty:netty:*:*:*:*:*:*:*:*", "matchCriteriaId": "BC283248-0EB5-46CA-A68C-4FF004D606F8", "versionEndExcluding": "4.1.61", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netapp:oncommand_api_services:-:*:*:*:*:*:*:*", "matchCriteriaId": "5EC98B22-FFAA-4B59-8E63-EBAA4336AD13", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:netapp:oncommand_workflow_automation:-:*:*:*:*:*:*:*", "matchCriteriaId": "5735E553-9731-4AAC-BCFF-989377F817B3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "0CF9A061-2421-426D-9854-0A4E55B2961D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F95EDC3D-54BB-48F9-82F2-7CCF335FCA78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B72B735F-4E52-484A-9C2C-23E6E2070385", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "8B36A1D4-F391-4EE3-9A65-0A10568795BA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "55116032-AAD1-4FEA-9DA8-2C4CBD3D3F61", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "0275F820-40BE-47B8-B167-815A55DF578E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "9E14324D-B9EE-4C06-ACC7-255189ED6300", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "CBEBB60F-6EAB-4AE5-B777-5044C657FBA8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B185C1EA-71E6-4972-8637-08A33CC00841", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:coherence:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "2FF57C7A-92C9-4D71-A7B1-CC9DEFAA8193", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:coherence:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "5FA64A1D-34F9-4441-857A-25C165E6DBB6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_brm_-_elastic_charging_engine:12.0.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "06594847-96ED-4541-B2F4-C7331B603603", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_console:1.7.0:*:*:*:*:*:*:*", "matchCriteriaId": "BC12B43F-30F6-4B05-AB3A-E91D8404D5A5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_policy:1.14.0:*:*:*:*:*:*:*", "matchCriteriaId": "4479F76A-4B67-41CC-98C7-C76B81050F8E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_design_studio:7.4.2.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "040DA31B-2A0C-46F6-8EDF-9B88F9FB0F48", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_messaging_server:8.1:*:*:*:*:*:*:*", "matchCriteriaId": "E1214FDF-357A-4BB9-BADE-50FB2BD16D10", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:helidon:1.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "4E7626D2-D9FF-416A-9581-852CED0D8C24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:helidon:2.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "99344A5D-F4B7-49B4-9AE6-0E2FB3874EA5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jd_edwards_enterpriseone_tools:*:*:*:*:*:*:*:*", "matchCriteriaId": "BE34D4F7-5C18-4578-8D0A-722FDF931333", "versionEndExcluding": "9.2.6.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:nosql_database:*:*:*:*:*:*:*:*", "matchCriteriaId": "7167D144-C4AE-487F-B59A-888E10EA59DF", "versionEndExcluding": "21.1.12", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "8B1C88FD-C2EC-4C96-AC7E-6F95C8763B48", "versionEndExcluding": null, "versionEndIncluding": "17.12.11", "versionStartExcluding": null, "versionStartIncluding": "17.12.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "53E2276C-9515-46F6-A621-213A3047B9A6", "versionEndExcluding": null, "versionEndIncluding": "18.8.11", "versionStartExcluding": null, "versionStartIncluding": "18.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "3EF7E2B4-B741-41E9-8EF6-6C415AB9EF54", "versionEndExcluding": null, "versionEndIncluding": "19.12.10", "versionStartExcluding": null, "versionStartIncluding": "19.12.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:quarkus:quarkus:*:*:*:*:*:*:*:*", "matchCriteriaId": "64839EBF-078E-492A-897C-9AFFB7678ED8", "versionEndExcluding": null, "versionEndIncluding": "1.13.7", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Netty is an open-source, asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. In Netty (io.netty:netty-codec-http2) before version 4.1.61.Final there is a vulnerability that enables request smuggling. The content-length header is not correctly validated if the request only uses a single Http2HeaderFrame with the endStream set to to true. This could lead to request smuggling if the request is proxied to a remote peer and translated to HTTP/1.1. This is a followup of GHSA-wm47-8v5p-wjpj/CVE-2021-21295 which did miss to fix this one case. This was fixed as part of 4.1.61.Final."}, {"lang": "es", "value": "Netty es un framework de aplicaci\u00f3n de red de c\u00f3digo abierto y as\u00edncrono event-driven para el desarrollo r\u00e1pido de servidores y clientes de protocolo de alto rendimiento mantenibles. En Netty (io.netty:netty-codec-http2) versiones anteriores a 4.1.61.Final se presenta una vulnerabilidad que permite el trafico no autorizado de peticiones. El encabezado content-length no es comprobado correctamente si la petici\u00f3n solo usa un \u00fanico Http2HeaderFrame con endStream establecido en verdadero. Esto podr\u00eda conllevar al trafico no autorizado de peticiones si la petici\u00f3n se env\u00eda a un peer remoto y se traduce a HTTP/1.1. Este es un seguimiento de GHSA-wm47-8v5p-wjpj/CVE-2021-21295 que no pudo solucionar este caso. Esto se corrigi\u00f3 como parte de la versi\u00f3n 4.1.61.Final."}], "evaluatorComment": null, "id": "CVE-2021-21409", "lastModified": "2022-05-12T14:35:58.710", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-30T15:15:14.573", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-21295"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/netty/netty/commit/b0fa4d5aab4215f3c22ce6123dd8dd5f38dc0432"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/netty/netty/security/advisories/GHSA-f256-j965-7f32"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/netty/netty/security/advisories/GHSA-wm47-8v5p-wjpj"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r0b09f3e31e004fe583f677f7afa46bd30110904576c13c5ac818ac2c@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r0ca82fec33334e571fe5b388272260778883e307e15415d7b1443de2@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r101f82d8f3b5af0bf79aecbd5b2dd3b404f6bb51d1a54c2c3d29bed9@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r1b3cb056364794f919aaf26ceaf7423de64e7fdd05a914066e7d5219@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r2732aa3884cacfecac4c54cfaa77c279ba815cad44b464a567216f83@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r31044fb995e894749cb821c6fe56f487c16a97028e6e360e59f09d58@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4a98827bb4a7edbd69ef862f2351391845697c40711820d10df52ca5@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4b8be87acf5b9c098a2ee350b5ca5716fe7afeaf0a21a4ee45a90687@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4ea2f1a9d79d4fc1896e085f31fb60a21b1770d0a26a5250f849372d@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r584cf871f188c406d8bd447ff4e2fd9817fca862436c064d0951a071@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5baac01f9e06c40ff7aab209d5751b3b58802c63734e33324b70a06a@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5cbea8614812289a9b98d0cfc54b47f54cef424ac98d5e315b791795@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5f2f120b2b8d099226473db1832ffb4d7c1d6dc2d228a164bf293a8e@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r602e98daacc98934f097f07f2eed6eb07c18bfc1949c8489dc7bfcf5@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r61564d86a75403b854cdafee67fc69c8b88c5f6802c2c838f4282cc8@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r69efd8ef003f612c43e4154e788ca3b1f837feaacd16d97854402355@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r6dac9bd799ceac499c7a7e152a9b0dc7f2fe7f89ec5605d129bb047b@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r70c3a7bfa904f06a1902f4df20ee26e4f09a46b8fd3eb304dc57a2de@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r7879ddcb990c835c6b246654770d836f9d031dee982be836744e50ed@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r7b54563abebe3dbbe421e1ba075c2030d8d460372f8c79b7789684b6@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r823d4b27fcba8dad5fe945bdefce3ca5a0031187966eb6ef3cc22ba9@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r855b4b6814ac829ce2d48dd9d8138d07f33387e710de798ee92c011e@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r967002f0939e69bdec58f070735a19dd57c1f2b8f817949ca17cddae@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r9ec78dc409f3f1edff88f21cab53737f36aad46f582a9825389092e0@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r9fe840c36b74f92b8d4a089ada1f9fd1d6293742efa18b10e06b66d2@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra64d56a8a331ffd7bdcd24a9aaaeeedeacd5d639f5a683389123f898@%3Cdev.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra655e5cec74d1ddf62adacb71d398abd96f3ea2c588f6bbf048348eb@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra66e93703e3f4bd31bdfd0b6fb0c32ae96b528259bb1aa2b6d38e401@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/raa413040db6d2197593cc03edecfd168732e697119e6447b0a25d525@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rac8cf45a1bab9ead5c9a860cbadd6faaeb7792203617b6ec3874736d@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rafc77f9f03031297394f3d372ccea751b23576f8a2ae9b6b053894c5@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rba2a9ef1d0af882ab58fadb336a58818495245dda43d32a7d7837187@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rbde2f13daf4911504f0eaea43eee4f42555241b5f6d9d71564b6c5fa@%3Cjira.kafka.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rca0978b634a0c3ebee4126ec29c7f570b165fae3f8f3658754c1cbd3@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rcae42fba06979934208bbd515584b241d3ad01d1bb8b063512644362@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rd4a6b7dec38ea6cd28b6f94bd4b312629a52b80be3786d5fb0e474bc@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rd8f72411fb75b98d366400ae789966373b5c3eb3f511e717caf3e49e@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rdd206d9dd7eb894cc089b37fe6edde2932de88d63a6d8368b44f5101@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rdd5715f3ee5e3216d5e0083a07994f67da6dbb9731ce9e7a6389b18e@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re1911e05c08f3ec2bab85744d788773519a0afb27272a31ac2a0b4e8@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re39391adcb863f0e9f3f15e7986255948f263f02e4700b82453e7102@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re4b0141939370304d676fe23774d0c6fbc584b648919825402d0cb39@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re7c69756a102bebce8b8681882844a53e2f23975a189363e68ad0324@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re9e6ed60941da831675de2f8f733c026757fb4fa28a7b6c9f3dfb575@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/redef0fb5474fd686781007de9ddb852b24f1b04131a248d9a4789183@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf148b2bf6c2754153a8629bc7495e216bd0bd4c915695486542a10b4@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf38e4dcdefc7c59f7ba0799a399d6d6e37b555d406a1dfc2fcbf0b35@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf521ff2be2e2dd38984174d3451e6ee935c845948845c8fccd86371d@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf934292a4a1c189827f625d567838d2c1001e4739b158638d844105b@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20210604-0003/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4885"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com//security-alerts/cpujul2021.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujan2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuoct2021.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/netty/netty/commit/b0fa4d5aab4215f3c22ce6123dd8dd5f38dc0432"}, "type": "CWE-444"}
| 258
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Copyright 2016 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License, version 2.0 (the\n * \"License\"); you may not use this file except in compliance with the License. You may obtain a\n * copy of the License at:\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\npackage io.netty.handler.codec.http2;",
"import io.netty.buffer.ByteBuf;\nimport io.netty.buffer.Unpooled;\nimport io.netty.channel.Channel;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.channel.ChannelFutureListener;\nimport io.netty.channel.ChannelHandler;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.channel.ChannelInboundHandlerAdapter;\nimport io.netty.channel.ChannelOutboundHandlerAdapter;\nimport io.netty.channel.ChannelPromise;\nimport io.netty.channel.WriteBufferWaterMark;\nimport io.netty.channel.embedded.EmbeddedChannel;\nimport io.netty.handler.codec.http.HttpHeaderNames;\nimport io.netty.handler.codec.http.HttpMethod;\nimport io.netty.handler.codec.http.HttpScheme;\nimport io.netty.handler.codec.http2.Http2Exception.StreamException;\nimport io.netty.handler.codec.http2.LastInboundHandler.Consumer;\nimport io.netty.util.AsciiString;\nimport io.netty.util.AttributeKey;\nimport org.hamcrest.CoreMatchers;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.mockito.ArgumentMatcher;\nimport org.mockito.Mockito;\nimport org.mockito.invocation.InvocationOnMock;\nimport org.mockito.stubbing.Answer;",
"import java.net.InetSocketAddress;\nimport java.nio.channels.ClosedChannelException;\nimport java.util.ArrayDeque;\nimport java.util.Queue;\nimport java.util.UUID;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;",
"import static io.netty.handler.codec.http2.Http2TestUtil.anyChannelPromise;\nimport static io.netty.handler.codec.http2.Http2TestUtil.anyHttp2Settings;\nimport static io.netty.handler.codec.http2.Http2TestUtil.assertEqualsAndRelease;\nimport static io.netty.handler.codec.http2.Http2TestUtil.bb;\nimport static io.netty.util.ReferenceCountUtil.release;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.ArgumentMatchers.anyBoolean;\nimport static org.mockito.ArgumentMatchers.anyInt;\nimport static org.mockito.ArgumentMatchers.anyLong;\nimport static org.mockito.ArgumentMatchers.argThat;\nimport static org.mockito.ArgumentMatchers.eq;\nimport static org.mockito.Mockito.never;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\nimport static org.hamcrest.MatcherAssert.assertThat;",
"public abstract class Http2MultiplexTest<C extends Http2FrameCodec> {\n private final Http2Headers request = new DefaultHttp2Headers()\n .method(HttpMethod.GET.asciiName()).scheme(HttpScheme.HTTPS.name())\n .authority(new AsciiString(\"example.org\")).path(new AsciiString(\"/foo\"));",
" private EmbeddedChannel parentChannel;\n private Http2FrameWriter frameWriter;\n private Http2FrameInboundWriter frameInboundWriter;\n private TestChannelInitializer childChannelInitializer;\n private C codec;",
" private static final int initialRemoteStreamWindow = 1024;",
" protected abstract C newCodec(TestChannelInitializer childChannelInitializer, Http2FrameWriter frameWriter);\n protected abstract ChannelHandler newMultiplexer(TestChannelInitializer childChannelInitializer);",
" @Before\n public void setUp() {\n childChannelInitializer = new TestChannelInitializer();\n parentChannel = new EmbeddedChannel();\n frameInboundWriter = new Http2FrameInboundWriter(parentChannel);\n parentChannel.connect(new InetSocketAddress(0));\n frameWriter = Http2TestUtil.mockedFrameWriter();\n codec = newCodec(childChannelInitializer, frameWriter);\n parentChannel.pipeline().addLast(codec);\n ChannelHandler multiplexer = newMultiplexer(childChannelInitializer);\n if (multiplexer != null) {\n parentChannel.pipeline().addLast(multiplexer);\n }",
" parentChannel.runPendingTasks();\n parentChannel.pipeline().fireChannelActive();",
" parentChannel.writeInbound(Http2CodecUtil.connectionPrefaceBuf());",
" Http2Settings settings = new Http2Settings().initialWindowSize(initialRemoteStreamWindow);\n frameInboundWriter.writeInboundSettings(settings);",
" verify(frameWriter).writeSettingsAck(eqCodecCtx(), anyChannelPromise());",
" frameInboundWriter.writeInboundSettingsAck();",
" Http2SettingsFrame settingsFrame = parentChannel.readInbound();\n assertNotNull(settingsFrame);\n Http2SettingsAckFrame settingsAckFrame = parentChannel.readInbound();\n assertNotNull(settingsAckFrame);",
" // Handshake\n verify(frameWriter).writeSettings(eqCodecCtx(),\n anyHttp2Settings(), anyChannelPromise());\n }",
" private ChannelHandlerContext eqCodecCtx() {\n return eq(codec.ctx);\n }",
" @After\n public void tearDown() throws Exception {\n if (childChannelInitializer.handler instanceof LastInboundHandler) {\n ((LastInboundHandler) childChannelInitializer.handler).finishAndReleaseAll();\n }\n parentChannel.finishAndReleaseAll();\n codec = null;\n }",
" // TODO(buchgr): Flush from child channel\n // TODO(buchgr): ChildChannel.childReadComplete()\n // TODO(buchgr): GOAWAY Logic\n // TODO(buchgr): Test ChannelConfig.setMaxMessagesPerRead",
" @Test\n public void writeUnknownFrame() {\n Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter() {\n @Override\n public void channelActive(ChannelHandlerContext ctx) {\n ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));\n ctx.writeAndFlush(new DefaultHttp2UnknownFrame((byte) 99, new Http2Flags()));\n ctx.fireChannelActive();\n }\n });\n assertTrue(childChannel.isActive());",
" parentChannel.runPendingTasks();",
" verify(frameWriter).writeFrame(eq(codec.ctx), eq((byte) 99), eqStreamId(childChannel), any(Http2Flags.class),\n any(ByteBuf.class), any(ChannelPromise.class));\n }",
" private Http2StreamChannel newInboundStream(int streamId, boolean endStream, final ChannelHandler childHandler) {\n return newInboundStream(streamId, endStream, null, childHandler);\n }",
" private Http2StreamChannel newInboundStream(int streamId, boolean endStream,\n AtomicInteger maxReads, final ChannelHandler childHandler) {\n final AtomicReference<Http2StreamChannel> streamChannelRef = new AtomicReference<Http2StreamChannel>();\n childChannelInitializer.maxReads = maxReads;\n childChannelInitializer.handler = new ChannelInboundHandlerAdapter() {\n @Override\n public void channelRegistered(ChannelHandlerContext ctx) {\n assertNull(streamChannelRef.get());\n streamChannelRef.set((Http2StreamChannel) ctx.channel());\n ctx.pipeline().addLast(childHandler);\n ctx.fireChannelRegistered();\n }\n };",
" frameInboundWriter.writeInboundHeaders(streamId, request, 0, endStream);\n parentChannel.runPendingTasks();\n Http2StreamChannel channel = streamChannelRef.get();\n assertEquals(streamId, channel.stream().id());\n return channel;\n }",
" @Test\n public void readUnkownFrame() {\n LastInboundHandler handler = new LastInboundHandler();",
" Http2StreamChannel channel = newInboundStream(3, true, handler);\n frameInboundWriter.writeInboundFrame((byte) 99, channel.stream().id(), new Http2Flags(), Unpooled.EMPTY_BUFFER);",
" // header frame and unknown frame\n verifyFramesMultiplexedToCorrectChannel(channel, handler, 2);",
" Channel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter());\n assertTrue(childChannel.isActive());\n }",
" @Test\n public void headerAndDataFramesShouldBeDelivered() {\n LastInboundHandler inboundHandler = new LastInboundHandler();",
" Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);\n Http2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(request).stream(channel.stream());\n Http2DataFrame dataFrame1 = new DefaultHttp2DataFrame(bb(\"hello\")).stream(channel.stream());\n Http2DataFrame dataFrame2 = new DefaultHttp2DataFrame(bb(\"world\")).stream(channel.stream());",
" assertTrue(inboundHandler.isChannelActive());\n frameInboundWriter.writeInboundData(channel.stream().id(), bb(\"hello\"), 0, false);\n frameInboundWriter.writeInboundData(channel.stream().id(), bb(\"world\"), 0, false);",
" assertEquals(headersFrame, inboundHandler.readInbound());",
" assertEqualsAndRelease(dataFrame1, inboundHandler.<Http2Frame>readInbound());\n assertEqualsAndRelease(dataFrame2, inboundHandler.<Http2Frame>readInbound());",
" assertNull(inboundHandler.readInbound());\n }",
" @Test\n public void headerMultipleContentLengthValidationShouldPropagate() {",
" headerMultipleContentLengthValidationShouldPropagate(false);\n }",
" @Test\n public void headerMultipleContentLengthValidationShouldPropagateWithEndStream() {\n headerMultipleContentLengthValidationShouldPropagate(true);\n }",
" private void headerMultipleContentLengthValidationShouldPropagate(boolean endStream) {",
" LastInboundHandler inboundHandler = new LastInboundHandler();\n request.addLong(HttpHeaderNames.CONTENT_LENGTH, 0);\n request.addLong(HttpHeaderNames.CONTENT_LENGTH, 1);",
" Http2StreamChannel channel = newInboundStream(3, endStream, inboundHandler);\n try {\n inboundHandler.checkException();\n fail();\n } catch (Exception e) {\n assertThat(e, CoreMatchers.<Exception>instanceOf(StreamException.class));\n }\n assertNull(inboundHandler.readInbound());\n assertFalse(channel.isActive());\n }",
" @Test\n public void headerPlusSignContentLengthValidationShouldPropagate() {\n headerSignContentLengthValidationShouldPropagateWithEndStream(false, false);\n }",
" @Test\n public void headerPlusSignContentLengthValidationShouldPropagateWithEndStream() {\n headerSignContentLengthValidationShouldPropagateWithEndStream(false, true);\n }",
" @Test\n public void headerMinusSignContentLengthValidationShouldPropagate() {\n headerSignContentLengthValidationShouldPropagateWithEndStream(true, false);\n }",
" @Test\n public void headerMinusSignContentLengthValidationShouldPropagateWithEndStream() {\n headerSignContentLengthValidationShouldPropagateWithEndStream(true, true);\n }",
" private void headerSignContentLengthValidationShouldPropagateWithEndStream(boolean minus, boolean endStream) {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n request.add(HttpHeaderNames.CONTENT_LENGTH, (minus ? \"-\" : \"+\") + 1);\n Http2StreamChannel channel = newInboundStream(3, endStream, inboundHandler);",
" try {\n inboundHandler.checkException();\n fail();\n } catch (Exception e) {\n assertThat(e, CoreMatchers.<Exception>instanceOf(StreamException.class));\n }\n assertNull(inboundHandler.readInbound());\n assertFalse(channel.isActive());\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagate() {\n headerContentLengthNotMatchValidationShouldPropagate(false, false, false);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateWithEndStream() {\n headerContentLengthNotMatchValidationShouldPropagate(false, true, false);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateCloseLocal() {\n headerContentLengthNotMatchValidationShouldPropagate(true, false, false);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateWithEndStreamCloseLocal() {\n headerContentLengthNotMatchValidationShouldPropagate(true, true, false);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateTrailers() {\n headerContentLengthNotMatchValidationShouldPropagate(false, false, true);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateWithEndStreamTrailers() {\n headerContentLengthNotMatchValidationShouldPropagate(false, true, true);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateCloseLocalTrailers() {\n headerContentLengthNotMatchValidationShouldPropagate(true, false, true);\n }",
" @Test\n public void headerContentLengthNotMatchValidationShouldPropagateWithEndStreamCloseLocalTrailers() {\n headerContentLengthNotMatchValidationShouldPropagate(true, true, true);\n }",
" private void headerContentLengthNotMatchValidationShouldPropagate(\n boolean closeLocal, boolean endStream, boolean trailer) {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n request.addLong(HttpHeaderNames.CONTENT_LENGTH, 1);\n Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);\n assertTrue(channel.isActive());",
" if (closeLocal) {\n channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), true))\n .syncUninterruptibly();\n assertEquals(Http2Stream.State.HALF_CLOSED_LOCAL, channel.stream().state());\n } else {\n assertEquals(Http2Stream.State.OPEN, channel.stream().state());\n }",
" if (trailer) {\n frameInboundWriter.writeInboundHeaders(channel.stream().id(), new DefaultHttp2Headers(), 0, endStream);\n } else {\n frameInboundWriter.writeInboundData(channel.stream().id(), bb(\"foo\"), 0, endStream);\n }\n try {\n inboundHandler.checkException();\n fail();\n } catch (Exception e) {\n assertThat(e, CoreMatchers.<Exception>instanceOf(StreamException.class));\n }\n Http2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(request).stream(channel.stream());\n assertEquals(headersFrame, inboundHandler.readInbound());\n assertNull(inboundHandler.readInbound());\n assertFalse(channel.isActive());\n }",
" @Test\n public void framesShouldBeMultiplexed() {\n LastInboundHandler handler1 = new LastInboundHandler();\n Http2StreamChannel channel1 = newInboundStream(3, false, handler1);\n LastInboundHandler handler2 = new LastInboundHandler();\n Http2StreamChannel channel2 = newInboundStream(5, false, handler2);\n LastInboundHandler handler3 = new LastInboundHandler();\n Http2StreamChannel channel3 = newInboundStream(11, false, handler3);",
" verifyFramesMultiplexedToCorrectChannel(channel1, handler1, 1);\n verifyFramesMultiplexedToCorrectChannel(channel2, handler2, 1);\n verifyFramesMultiplexedToCorrectChannel(channel3, handler3, 1);",
" frameInboundWriter.writeInboundData(channel2.stream().id(), bb(\"hello\"), 0, false);\n frameInboundWriter.writeInboundData(channel1.stream().id(), bb(\"foo\"), 0, true);\n frameInboundWriter.writeInboundData(channel2.stream().id(), bb(\"world\"), 0, true);\n frameInboundWriter.writeInboundData(channel3.stream().id(), bb(\"bar\"), 0, true);",
" verifyFramesMultiplexedToCorrectChannel(channel1, handler1, 1);\n verifyFramesMultiplexedToCorrectChannel(channel2, handler2, 2);\n verifyFramesMultiplexedToCorrectChannel(channel3, handler3, 1);\n }",
" @Test\n public void inboundDataFrameShouldUpdateLocalFlowController() throws Http2Exception {\n Http2LocalFlowController flowController = Mockito.mock(Http2LocalFlowController.class);\n codec.connection().local().flowController(flowController);",
" LastInboundHandler handler = new LastInboundHandler();\n final Http2StreamChannel channel = newInboundStream(3, false, handler);",
" ByteBuf tenBytes = bb(\"0123456789\");",
" frameInboundWriter.writeInboundData(channel.stream().id(), tenBytes, 0, true);",
" // Verify we marked the bytes as consumed\n verify(flowController).consumeBytes(argThat(new ArgumentMatcher<Http2Stream>() {\n @Override\n public boolean matches(Http2Stream http2Stream) {\n return http2Stream.id() == channel.stream().id();\n }\n }), eq(10));",
" // headers and data frame\n verifyFramesMultiplexedToCorrectChannel(channel, handler, 2);\n }",
" @Test\n public void unhandledHttp2FramesShouldBePropagated() {\n Http2PingFrame pingFrame = new DefaultHttp2PingFrame(0);\n frameInboundWriter.writeInboundPing(false, 0);\n assertEquals(parentChannel.readInbound(), pingFrame);",
" DefaultHttp2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame(1,\n parentChannel.alloc().buffer().writeLong(8));\n frameInboundWriter.writeInboundGoAway(0, goAwayFrame.errorCode(), goAwayFrame.content().retainedDuplicate());",
" Http2GoAwayFrame frame = parentChannel.readInbound();\n assertEqualsAndRelease(frame, goAwayFrame);\n }",
" @Test\n public void channelReadShouldRespectAutoRead() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n assertTrue(childChannel.config().isAutoRead());\n Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);",
" childChannel.config().setAutoRead(false);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world\"), 0, false);\n Http2DataFrame dataFrame0 = inboundHandler.readInbound();\n assertNotNull(dataFrame0);\n release(dataFrame0);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, false);",
" assertNull(inboundHandler.readInbound());",
" childChannel.config().setAutoRead(true);\n verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 2);\n }",
" @Test\n public void channelReadShouldRespectAutoReadAndNotProduceNPE() throws Exception {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n assertTrue(childChannel.config().isAutoRead());\n Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);",
" childChannel.config().setAutoRead(false);\n childChannel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {\n private int count;\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n ctx.fireChannelRead(msg);\n // Close channel after 2 reads so there is still something in the inboundBuffer when the close happens.\n if (++count == 2) {\n ctx.close();\n }\n }\n });\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world\"), 0, false);\n Http2DataFrame dataFrame0 = inboundHandler.readInbound();\n assertNotNull(dataFrame0);\n release(dataFrame0);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, false);",
" assertNull(inboundHandler.readInbound());",
" childChannel.config().setAutoRead(true);\n verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 3);\n inboundHandler.checkException();\n }",
" @Test\n public void readInChannelReadWithoutAutoRead() {\n useReadWithoutAutoRead(false);\n }",
" @Test\n public void readInChannelReadCompleteWithoutAutoRead() {\n useReadWithoutAutoRead(true);\n }",
" private void useReadWithoutAutoRead(final boolean readComplete) {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n assertTrue(childChannel.config().isAutoRead());\n childChannel.config().setAutoRead(false);\n assertFalse(childChannel.config().isAutoRead());",
" Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);",
" // Add a handler which will request reads.\n childChannel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) {\n ctx.fireChannelRead(msg);\n if (!readComplete) {\n ctx.read();\n }\n }",
" @Override\n public void channelReadComplete(ChannelHandlerContext ctx) {\n ctx.fireChannelReadComplete();\n if (readComplete) {\n ctx.read();\n }\n }\n });",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, true);",
" verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 6);\n }",
" private Http2StreamChannel newOutboundStream(ChannelHandler handler) {\n return new Http2StreamChannelBootstrap(parentChannel).handler(handler)\n .open().syncUninterruptibly().getNow();\n }",
" /**\n * A child channel for an HTTP/2 stream in IDLE state (that is no headers sent or received),\n * should not emit a RST_STREAM frame on close, as this is a connection error of type protocol error.\n */\n @Test\n public void idleOutboundStreamShouldNotWriteResetFrameOnClose() {\n LastInboundHandler handler = new LastInboundHandler();",
" Channel childChannel = newOutboundStream(handler);\n assertTrue(childChannel.isActive());",
" childChannel.close();\n parentChannel.runPendingTasks();",
" assertFalse(childChannel.isOpen());\n assertFalse(childChannel.isActive());\n assertNull(parentChannel.readOutbound());\n }",
" @Test\n public void outboundStreamShouldWriteResetFrameOnClose_headersSent() {\n ChannelHandler handler = new ChannelInboundHandlerAdapter() {\n @Override\n public void channelActive(ChannelHandlerContext ctx) {\n ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));\n ctx.fireChannelActive();\n }\n };",
" Http2StreamChannel childChannel = newOutboundStream(handler);\n assertTrue(childChannel.isActive());",
" childChannel.close();\n verify(frameWriter).writeRstStream(eqCodecCtx(),\n eqStreamId(childChannel), eq(Http2Error.CANCEL.code()), anyChannelPromise());\n }",
" @Test\n public void outboundStreamShouldNotWriteResetFrameOnClose_IfStreamDidntExist() {\n when(frameWriter.writeHeaders(eqCodecCtx(), anyInt(),\n any(Http2Headers.class), anyInt(), anyBoolean(),\n any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {",
" private boolean headersWritten;\n @Override\n public ChannelFuture answer(InvocationOnMock invocationOnMock) {\n // We want to fail to write the first headers frame. This is what happens if the connection\n // refuses to allocate a new stream due to having received a GOAWAY.\n if (!headersWritten) {\n headersWritten = true;\n return ((ChannelPromise) invocationOnMock.getArgument(5)).setFailure(new Exception(\"boom\"));\n }\n return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();\n }\n });",
" Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter() {\n @Override\n public void channelActive(ChannelHandlerContext ctx) {\n ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));\n ctx.fireChannelActive();\n }\n });",
" assertFalse(childChannel.isActive());",
" childChannel.close();\n parentChannel.runPendingTasks();\n // The channel was never active so we should not generate a RST frame.\n verify(frameWriter, never()).writeRstStream(eqCodecCtx(), eqStreamId(childChannel), anyLong(),\n anyChannelPromise());",
" assertTrue(parentChannel.outboundMessages().isEmpty());\n }",
" @Test\n public void inboundRstStreamFireChannelInactive() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);\n assertTrue(inboundHandler.isChannelActive());\n frameInboundWriter.writeInboundRstStream(channel.stream().id(), Http2Error.INTERNAL_ERROR.code());",
" assertFalse(inboundHandler.isChannelActive());",
" // A RST_STREAM frame should NOT be emitted, as we received a RST_STREAM.\n verify(frameWriter, Mockito.never()).writeRstStream(eqCodecCtx(), eqStreamId(channel),\n anyLong(), anyChannelPromise());\n }",
" @Test(expected = StreamException.class)\n public void streamExceptionTriggersChildChannelExceptionAndClose() throws Exception {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);\n assertTrue(channel.isActive());\n StreamException cause = new StreamException(channel.stream().id(), Http2Error.PROTOCOL_ERROR, \"baaam!\");\n parentChannel.pipeline().fireExceptionCaught(cause);",
" assertFalse(channel.isActive());\n inboundHandler.checkException();\n }",
" @Test(expected = ClosedChannelException.class)\n public void streamClosedErrorTranslatedToClosedChannelExceptionOnWrites() throws Exception {\n LastInboundHandler inboundHandler = new LastInboundHandler();",
" final Http2StreamChannel childChannel = newOutboundStream(inboundHandler);\n assertTrue(childChannel.isActive());",
" Http2Headers headers = new DefaultHttp2Headers();\n when(frameWriter.writeHeaders(eqCodecCtx(), anyInt(),\n eq(headers), anyInt(), anyBoolean(),\n any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {\n @Override\n public ChannelFuture answer(InvocationOnMock invocationOnMock) {\n return ((ChannelPromise) invocationOnMock.getArgument(5)).setFailure(\n new StreamException(childChannel.stream().id(), Http2Error.STREAM_CLOSED, \"Stream Closed\"));\n }\n });\n ChannelFuture future = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));",
" parentChannel.flush();",
" assertFalse(childChannel.isActive());\n assertFalse(childChannel.isOpen());",
" inboundHandler.checkException();",
" future.syncUninterruptibly();\n }",
" @Test\n public void creatingWritingReadingAndClosingOutboundStreamShouldWork() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newOutboundStream(inboundHandler);\n assertTrue(childChannel.isActive());\n assertTrue(inboundHandler.isChannelActive());",
" // Write to the child channel\n Http2Headers headers = new DefaultHttp2Headers().scheme(\"https\").method(\"GET\").path(\"/foo.txt\");\n childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(headers));",
" // Read from the child channel\n frameInboundWriter.writeInboundHeaders(childChannel.stream().id(), headers, 0, false);",
" Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);\n assertEquals(headers, headersFrame.headers());",
" // Close the child channel.\n childChannel.close();",
" parentChannel.runPendingTasks();\n // An active outbound stream should emit a RST_STREAM frame.\n verify(frameWriter).writeRstStream(eqCodecCtx(), eqStreamId(childChannel),\n anyLong(), anyChannelPromise());",
" assertFalse(childChannel.isOpen());\n assertFalse(childChannel.isActive());\n assertFalse(inboundHandler.isChannelActive());\n }",
" // Test failing the promise of the first headers frame of an outbound stream. In practice this error case would most\n // likely happen due to the max concurrent streams limit being hit or the channel running out of stream identifiers.\n //\n @Test(expected = Http2NoMoreStreamIdsException.class)\n public void failedOutboundStreamCreationThrowsAndClosesChannel() throws Exception {\n LastInboundHandler handler = new LastInboundHandler();\n Http2StreamChannel childChannel = newOutboundStream(handler);\n assertTrue(childChannel.isActive());",
" Http2Headers headers = new DefaultHttp2Headers();\n when(frameWriter.writeHeaders(eqCodecCtx(), anyInt(),\n eq(headers), anyInt(), anyBoolean(),\n any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {\n @Override\n public ChannelFuture answer(InvocationOnMock invocationOnMock) {\n return ((ChannelPromise) invocationOnMock.getArgument(5)).setFailure(\n new Http2NoMoreStreamIdsException());\n }\n });",
" ChannelFuture future = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(headers));\n parentChannel.flush();",
" assertFalse(childChannel.isActive());\n assertFalse(childChannel.isOpen());",
" handler.checkException();",
" future.syncUninterruptibly();\n }",
" @Test\n public void channelClosedWhenCloseListenerCompletes() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);",
" assertTrue(childChannel.isOpen());\n assertTrue(childChannel.isActive());",
" final AtomicBoolean channelOpen = new AtomicBoolean(true);\n final AtomicBoolean channelActive = new AtomicBoolean(true);",
" // Create a promise before actually doing the close, because otherwise we would be adding a listener to a future\n // that is already completed because we are using EmbeddedChannel which executes code in the JUnit thread.\n ChannelPromise p = childChannel.newPromise();\n p.addListener(new ChannelFutureListener() {\n @Override\n public void operationComplete(ChannelFuture future) {\n channelOpen.set(future.channel().isOpen());\n channelActive.set(future.channel().isActive());\n }\n });\n childChannel.close(p).syncUninterruptibly();",
" assertFalse(channelOpen.get());\n assertFalse(channelActive.get());\n assertFalse(childChannel.isActive());\n }",
" @Test\n public void channelClosedWhenChannelClosePromiseCompletes() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);",
" assertTrue(childChannel.isOpen());\n assertTrue(childChannel.isActive());",
" final AtomicBoolean channelOpen = new AtomicBoolean(true);\n final AtomicBoolean channelActive = new AtomicBoolean(true);",
" childChannel.closeFuture().addListener(new ChannelFutureListener() {\n @Override\n public void operationComplete(ChannelFuture future) {\n channelOpen.set(future.channel().isOpen());\n channelActive.set(future.channel().isActive());\n }\n });\n childChannel.close().syncUninterruptibly();",
" assertFalse(channelOpen.get());\n assertFalse(channelActive.get());\n assertFalse(childChannel.isActive());\n }",
" @Test\n public void channelClosedWhenWriteFutureFails() {\n final Queue<ChannelPromise> writePromises = new ArrayDeque<ChannelPromise>();",
" LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);",
" assertTrue(childChannel.isOpen());\n assertTrue(childChannel.isActive());",
" final AtomicBoolean channelOpen = new AtomicBoolean(true);\n final AtomicBoolean channelActive = new AtomicBoolean(true);",
" Http2Headers headers = new DefaultHttp2Headers();\n when(frameWriter.writeHeaders(eqCodecCtx(), anyInt(),\n eq(headers), anyInt(), anyBoolean(),\n any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {\n @Override\n public ChannelFuture answer(InvocationOnMock invocationOnMock) {\n ChannelPromise promise = invocationOnMock.getArgument(5);\n writePromises.offer(promise);\n return promise;\n }\n });",
" ChannelFuture f = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(headers));\n assertFalse(f.isDone());\n f.addListener(new ChannelFutureListener() {\n @Override\n public void operationComplete(ChannelFuture future) throws Exception {\n channelOpen.set(future.channel().isOpen());\n channelActive.set(future.channel().isActive());\n }\n });",
" ChannelPromise first = writePromises.poll();\n first.setFailure(new ClosedChannelException());\n f.awaitUninterruptibly();",
" assertFalse(channelOpen.get());\n assertFalse(channelActive.get());\n assertFalse(childChannel.isActive());\n }",
" @Test\n public void channelClosedTwiceMarksPromiseAsSuccessful() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);",
" assertTrue(childChannel.isOpen());\n assertTrue(childChannel.isActive());\n childChannel.close().syncUninterruptibly();\n childChannel.close().syncUninterruptibly();",
" assertFalse(childChannel.isOpen());\n assertFalse(childChannel.isActive());\n }",
" @Test\n public void settingChannelOptsAndAttrs() {\n AttributeKey<String> key = AttributeKey.newInstance(UUID.randomUUID().toString());",
" Channel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter());\n childChannel.config().setAutoRead(false).setWriteSpinCount(1000);\n childChannel.attr(key).set(\"bar\");\n assertFalse(childChannel.config().isAutoRead());\n assertEquals(1000, childChannel.config().getWriteSpinCount());\n assertEquals(\"bar\", childChannel.attr(key).get());\n }",
" @Test\n public void outboundFlowControlWritability() {\n Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter());\n assertTrue(childChannel.isActive());",
" assertTrue(childChannel.isWritable());\n childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));\n parentChannel.flush();",
" // Test for initial window size\n assertTrue(initialRemoteStreamWindow < childChannel.config().getWriteBufferHighWaterMark());",
" assertTrue(childChannel.isWritable());\n childChannel.write(new DefaultHttp2DataFrame(Unpooled.buffer().writeZero(16 * 1024 * 1024)));\n assertEquals(0, childChannel.bytesBeforeUnwritable());\n assertFalse(childChannel.isWritable());\n }",
" @Test\n public void writabilityOfParentIsRespected() {\n Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter());\n childChannel.config().setWriteBufferWaterMark(new WriteBufferWaterMark(2048, 4096));\n parentChannel.config().setWriteBufferWaterMark(new WriteBufferWaterMark(256, 512));\n assertTrue(childChannel.isWritable());\n assertTrue(parentChannel.isActive());",
" childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));\n parentChannel.flush();",
" assertTrue(childChannel.isWritable());\n childChannel.write(new DefaultHttp2DataFrame(Unpooled.buffer().writeZero(256)));\n assertTrue(childChannel.isWritable());\n childChannel.writeAndFlush(new DefaultHttp2DataFrame(Unpooled.buffer().writeZero(512)));",
" long bytesBeforeUnwritable = childChannel.bytesBeforeUnwritable();\n assertNotEquals(0, bytesBeforeUnwritable);\n // Add something to the ChannelOutboundBuffer of the parent to simulate queuing in the parents channel buffer\n // and verify that this only affect the writability of the parent channel while the child stays writable\n // until it used all of its credits.\n parentChannel.unsafe().outboundBuffer().addMessage(\n Unpooled.buffer().writeZero(800), 800, parentChannel.voidPromise());\n assertFalse(parentChannel.isWritable());",
" assertTrue(childChannel.isWritable());\n assertEquals(4096, childChannel.bytesBeforeUnwritable());",
" // Flush everything which simulate writing everything to the socket.\n parentChannel.flush();\n assertTrue(parentChannel.isWritable());\n assertTrue(childChannel.isWritable());\n assertEquals(bytesBeforeUnwritable, childChannel.bytesBeforeUnwritable());",
" ChannelFuture future = childChannel.writeAndFlush(new DefaultHttp2DataFrame(\n Unpooled.buffer().writeZero((int) bytesBeforeUnwritable)));\n assertFalse(childChannel.isWritable());\n assertTrue(parentChannel.isWritable());",
" parentChannel.flush();\n assertFalse(future.isDone());\n assertTrue(parentChannel.isWritable());\n assertFalse(childChannel.isWritable());",
" // Now write an window update frame for the stream which then should ensure we will flush the bytes that were\n // queued in the RemoteFlowController before for the stream.\n frameInboundWriter.writeInboundWindowUpdate(childChannel.stream().id(), (int) bytesBeforeUnwritable);\n assertTrue(childChannel.isWritable());\n assertTrue(future.isDone());\n }",
" @Test\n public void channelClosedWhenInactiveFired() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);",
" final AtomicBoolean channelOpen = new AtomicBoolean(false);\n final AtomicBoolean channelActive = new AtomicBoolean(false);\n assertTrue(childChannel.isOpen());\n assertTrue(childChannel.isActive());",
" childChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {\n @Override\n public void channelInactive(ChannelHandlerContext ctx) throws Exception {\n channelOpen.set(ctx.channel().isOpen());\n channelActive.set(ctx.channel().isActive());",
" super.channelInactive(ctx);\n }\n });",
" childChannel.close().syncUninterruptibly();\n assertFalse(channelOpen.get());\n assertFalse(channelActive.get());\n }",
" @Test\n public void channelInactiveHappensAfterExceptionCaughtEvents() throws Exception {\n final AtomicInteger count = new AtomicInteger(0);\n final AtomicInteger exceptionCaught = new AtomicInteger(-1);\n final AtomicInteger channelInactive = new AtomicInteger(-1);\n final AtomicInteger channelUnregistered = new AtomicInteger(-1);\n Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter() {",
" @Override\n public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {\n ctx.close();\n throw new Exception(\"exception\");\n }\n });",
" childChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {",
" @Override\n public void channelInactive(ChannelHandlerContext ctx) throws Exception {\n channelInactive.set(count.getAndIncrement());\n super.channelInactive(ctx);\n }",
" @Override\n public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {\n exceptionCaught.set(count.getAndIncrement());\n super.exceptionCaught(ctx, cause);\n }",
" @Override\n public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {\n channelUnregistered.set(count.getAndIncrement());\n super.channelUnregistered(ctx);\n }\n });",
" childChannel.pipeline().fireUserEventTriggered(new Object());\n parentChannel.runPendingTasks();",
" // The events should have happened in this order because the inactive and deregistration events\n // get deferred as they do in the AbstractChannel.\n assertEquals(0, exceptionCaught.get());\n assertEquals(1, channelInactive.get());\n assertEquals(2, channelUnregistered.get());\n }",
" @Test\n public void callUnsafeCloseMultipleTimes() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n childChannel.unsafe().close(childChannel.voidPromise());",
" ChannelPromise promise = childChannel.newPromise();\n childChannel.unsafe().close(promise);\n promise.syncUninterruptibly();\n childChannel.closeFuture().syncUninterruptibly();\n }",
" @Test\n public void endOfStreamDoesNotDiscardData() {\n AtomicInteger numReads = new AtomicInteger(1);\n final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean();\n Consumer<ChannelHandlerContext> ctxConsumer = new Consumer<ChannelHandlerContext>() {\n @Override\n public void accept(ChannelHandlerContext obj) {\n if (shouldDisableAutoRead.get()) {\n obj.channel().config().setAutoRead(false);\n }\n }\n };\n LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer);\n Http2StreamChannel childChannel = newInboundStream(3, false, numReads, inboundHandler);\n childChannel.config().setAutoRead(false);",
" Http2DataFrame dataFrame1 = new DefaultHttp2DataFrame(bb(\"1\")).stream(childChannel.stream());\n Http2DataFrame dataFrame2 = new DefaultHttp2DataFrame(bb(\"2\")).stream(childChannel.stream());\n Http2DataFrame dataFrame3 = new DefaultHttp2DataFrame(bb(\"3\")).stream(childChannel.stream());\n Http2DataFrame dataFrame4 = new DefaultHttp2DataFrame(bb(\"4\")).stream(childChannel.stream());",
" assertEquals(new DefaultHttp2HeadersFrame(request).stream(childChannel.stream()), inboundHandler.readInbound());",
" ChannelHandler readCompleteSupressHandler = new ChannelInboundHandlerAdapter() {\n @Override\n public void channelReadComplete(ChannelHandlerContext ctx) {\n // We want to simulate the parent channel calling channelRead and delay calling channelReadComplete.\n }\n };",
" parentChannel.pipeline().addFirst(readCompleteSupressHandler);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"1\"), 0, false);",
" assertEqualsAndRelease(dataFrame1, inboundHandler.<Http2DataFrame>readInbound());",
" // Deliver frames, and then a stream closed while read is inactive.\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"2\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"3\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"4\"), 0, false);",
" shouldDisableAutoRead.set(true);\n childChannel.config().setAutoRead(true);\n numReads.set(1);",
" frameInboundWriter.writeInboundRstStream(childChannel.stream().id(), Http2Error.NO_ERROR.code());",
" // Detecting EOS should flush all pending data regardless of read calls.\n assertEqualsAndRelease(dataFrame2, inboundHandler.<Http2DataFrame>readInbound());\n assertNull(inboundHandler.readInbound());",
" // As we limited the number to 1 we also need to call read() again.\n childChannel.read();",
" assertEqualsAndRelease(dataFrame3, inboundHandler.<Http2DataFrame>readInbound());\n assertEqualsAndRelease(dataFrame4, inboundHandler.<Http2DataFrame>readInbound());",
" Http2ResetFrame resetFrame = useUserEventForResetFrame() ? inboundHandler.<Http2ResetFrame>readUserEvent() :\n inboundHandler.<Http2ResetFrame>readInbound();",
" assertEquals(childChannel.stream(), resetFrame.stream());\n assertEquals(Http2Error.NO_ERROR.code(), resetFrame.errorCode());",
" assertNull(inboundHandler.readInbound());",
" // Now we want to call channelReadComplete and simulate the end of the read loop.\n parentChannel.pipeline().remove(readCompleteSupressHandler);\n parentChannel.flushInbound();",
" childChannel.closeFuture().syncUninterruptibly();\n }",
" protected abstract boolean useUserEventForResetFrame();",
" protected abstract boolean ignoreWindowUpdateFrames();",
" @Test\n public void windowUpdateFrames() {\n AtomicInteger numReads = new AtomicInteger(1);\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, numReads, inboundHandler);",
" assertEquals(new DefaultHttp2HeadersFrame(request).stream(childChannel.stream()), inboundHandler.readInbound());",
" frameInboundWriter.writeInboundWindowUpdate(childChannel.stream().id(), 4);",
" Http2WindowUpdateFrame updateFrame = inboundHandler.readInbound();\n if (ignoreWindowUpdateFrames()) {\n assertNull(updateFrame);\n } else {\n assertEquals(new DefaultHttp2WindowUpdateFrame(4).stream(childChannel.stream()), updateFrame);\n }",
" frameInboundWriter.writeInboundWindowUpdate(Http2CodecUtil.CONNECTION_STREAM_ID, 6);",
" assertNull(parentChannel.readInbound());\n childChannel.close().syncUninterruptibly();\n }",
" @Test\n public void childQueueIsDrainedAndNewDataIsDispatchedInParentReadLoopAutoRead() {\n AtomicInteger numReads = new AtomicInteger(1);\n final AtomicInteger channelReadCompleteCount = new AtomicInteger(0);\n final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean();\n Consumer<ChannelHandlerContext> ctxConsumer = new Consumer<ChannelHandlerContext>() {\n @Override\n public void accept(ChannelHandlerContext obj) {\n channelReadCompleteCount.incrementAndGet();\n if (shouldDisableAutoRead.get()) {\n obj.channel().config().setAutoRead(false);\n }\n }\n };\n LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer);\n Http2StreamChannel childChannel = newInboundStream(3, false, numReads, inboundHandler);\n childChannel.config().setAutoRead(false);",
" Http2DataFrame dataFrame1 = new DefaultHttp2DataFrame(bb(\"1\")).stream(childChannel.stream());\n Http2DataFrame dataFrame2 = new DefaultHttp2DataFrame(bb(\"2\")).stream(childChannel.stream());\n Http2DataFrame dataFrame3 = new DefaultHttp2DataFrame(bb(\"3\")).stream(childChannel.stream());\n Http2DataFrame dataFrame4 = new DefaultHttp2DataFrame(bb(\"4\")).stream(childChannel.stream());",
" assertEquals(new DefaultHttp2HeadersFrame(request).stream(childChannel.stream()), inboundHandler.readInbound());",
" ChannelHandler readCompleteSupressHandler = new ChannelInboundHandlerAdapter() {\n @Override\n public void channelReadComplete(ChannelHandlerContext ctx) {\n // We want to simulate the parent channel calling channelRead and delay calling channelReadComplete.\n }\n };\n parentChannel.pipeline().addFirst(readCompleteSupressHandler);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"1\"), 0, false);",
" assertEqualsAndRelease(dataFrame1, inboundHandler.<Http2DataFrame>readInbound());",
" // We want one item to be in the queue, and allow the numReads to be larger than 1. This will ensure that\n // when beginRead() is called the child channel is added to the readPending queue of the parent channel.\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"2\"), 0, false);",
" numReads.set(10);\n shouldDisableAutoRead.set(true);\n childChannel.config().setAutoRead(true);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"3\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"4\"), 0, false);",
" // Detecting EOS should flush all pending data regardless of read calls.\n assertEqualsAndRelease(dataFrame2, inboundHandler.<Http2DataFrame>readInbound());\n assertEqualsAndRelease(dataFrame3, inboundHandler.<Http2DataFrame>readInbound());\n assertEqualsAndRelease(dataFrame4, inboundHandler.<Http2DataFrame>readInbound());",
" assertNull(inboundHandler.readInbound());",
" // Now we want to call channelReadComplete and simulate the end of the read loop.\n parentChannel.pipeline().remove(readCompleteSupressHandler);\n parentChannel.flushInbound();",
" // 3 = 1 for initialization + 1 for read when auto read was off + 1 for when auto read was back on\n assertEquals(3, channelReadCompleteCount.get());\n }",
" @Test\n public void childQueueIsDrainedAndNewDataIsDispatchedInParentReadLoopNoAutoRead() {\n final AtomicInteger numReads = new AtomicInteger(1);\n final AtomicInteger channelReadCompleteCount = new AtomicInteger(0);\n final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean();\n Consumer<ChannelHandlerContext> ctxConsumer = new Consumer<ChannelHandlerContext>() {\n @Override\n public void accept(ChannelHandlerContext obj) {\n channelReadCompleteCount.incrementAndGet();\n if (shouldDisableAutoRead.get()) {\n obj.channel().config().setAutoRead(false);\n }\n }\n };\n final LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer);\n Http2StreamChannel childChannel = newInboundStream(3, false, numReads, inboundHandler);\n childChannel.config().setAutoRead(false);",
" Http2DataFrame dataFrame1 = new DefaultHttp2DataFrame(bb(\"1\")).stream(childChannel.stream());\n Http2DataFrame dataFrame2 = new DefaultHttp2DataFrame(bb(\"2\")).stream(childChannel.stream());\n Http2DataFrame dataFrame3 = new DefaultHttp2DataFrame(bb(\"3\")).stream(childChannel.stream());\n Http2DataFrame dataFrame4 = new DefaultHttp2DataFrame(bb(\"4\")).stream(childChannel.stream());",
" assertEquals(new DefaultHttp2HeadersFrame(request).stream(childChannel.stream()), inboundHandler.readInbound());",
" ChannelHandler readCompleteSupressHandler = new ChannelInboundHandlerAdapter() {\n @Override\n public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {\n // We want to simulate the parent channel calling channelRead and delay calling channelReadComplete.\n }\n };\n parentChannel.pipeline().addFirst(readCompleteSupressHandler);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"1\"), 0, false);",
" assertEqualsAndRelease(dataFrame1, inboundHandler.<Http2Frame>readInbound());",
" // We want one item to be in the queue, and allow the numReads to be larger than 1. This will ensure that\n // when beginRead() is called the child channel is added to the readPending queue of the parent channel.\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"2\"), 0, false);",
" numReads.set(2);\n childChannel.read();",
" assertEqualsAndRelease(dataFrame2, inboundHandler.<Http2Frame>readInbound());",
" assertNull(inboundHandler.readInbound());",
" // This is the second item that was read, this should be the last until we call read() again. This should also\n // notify of readComplete().\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"3\"), 0, false);",
" assertEqualsAndRelease(dataFrame3, inboundHandler.<Http2Frame>readInbound());",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"4\"), 0, false);\n assertNull(inboundHandler.readInbound());",
" childChannel.read();",
" assertEqualsAndRelease(dataFrame4, inboundHandler.<Http2Frame>readInbound());",
" assertNull(inboundHandler.readInbound());",
" // Now we want to call channelReadComplete and simulate the end of the read loop.\n parentChannel.pipeline().remove(readCompleteSupressHandler);\n parentChannel.flushInbound();",
" // 3 = 1 for initialization + 1 for first read of 2 items + 1 for second read of 2 items +\n // 1 for parent channel readComplete\n assertEquals(4, channelReadCompleteCount.get());\n }",
" @Test\n public void useReadWithoutAutoReadInRead() {\n useReadWithoutAutoReadBuffered(false);\n }",
" @Test\n public void useReadWithoutAutoReadInReadComplete() {\n useReadWithoutAutoReadBuffered(true);\n }",
" private void useReadWithoutAutoReadBuffered(final boolean triggerOnReadComplete) {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n assertTrue(childChannel.config().isAutoRead());\n childChannel.config().setAutoRead(false);\n assertFalse(childChannel.config().isAutoRead());",
" Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);",
" // Write some bytes to get the channel into the idle state with buffered data and also verify we\n // do not dispatch it until we receive a read() call.\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar\"), 0, false);",
" // Add a handler which will request reads.\n childChannel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {",
" @Override\n public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {\n super.channelReadComplete(ctx);\n if (triggerOnReadComplete) {\n ctx.read();\n ctx.read();\n }\n }",
" @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) {\n ctx.fireChannelRead(msg);\n if (!triggerOnReadComplete) {\n ctx.read();\n ctx.read();\n }\n }\n });",
" inboundHandler.channel().read();",
" verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 3);",
" frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"hello world2\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"foo2\"), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(\"bar2\"), 0, true);",
" verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 3);\n }",
" private static final class FlushSniffer extends ChannelOutboundHandlerAdapter {",
" private boolean didFlush;",
" public boolean checkFlush() {\n boolean r = didFlush;\n didFlush = false;\n return r;\n }",
" @Override\n public void flush(ChannelHandlerContext ctx) throws Exception {\n didFlush = true;\n super.flush(ctx);\n }\n }",
" @Test\n public void windowUpdatesAreFlushed() {\n LastInboundHandler inboundHandler = new LastInboundHandler();\n FlushSniffer flushSniffer = new FlushSniffer();\n parentChannel.pipeline().addFirst(flushSniffer);",
" Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);\n assertTrue(childChannel.config().isAutoRead());\n childChannel.config().setAutoRead(false);\n assertFalse(childChannel.config().isAutoRead());",
" Http2HeadersFrame headersFrame = inboundHandler.readInbound();\n assertNotNull(headersFrame);",
" assertTrue(flushSniffer.checkFlush());",
" // Write some bytes to get the channel into the idle state with buffered data and also verify we\n // do not dispatch it until we receive a read() call.\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(16 * 1024), 0, false);\n frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(16 * 1024), 0, false);\n assertTrue(flushSniffer.checkFlush());",
" verify(frameWriter, never()).writeWindowUpdate(eqCodecCtx(), anyInt(), anyInt(), anyChannelPromise());\n // only the first one was read because it was legacy auto-read behavior.\n verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 1);\n assertFalse(flushSniffer.checkFlush());",
" // Trigger a read of the second frame.\n childChannel.read();\n verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 1);\n // We expect a flush here because the StreamChannel will flush the smaller increment but the\n // connection will collect the bytes and decide not to send a wire level frame until more are consumed.\n assertTrue(flushSniffer.checkFlush());\n verify(frameWriter, never()).writeWindowUpdate(eqCodecCtx(), anyInt(), anyInt(), anyChannelPromise());",
" // Call read one more time which should trigger the writing of the flow control update.\n childChannel.read();\n verify(frameWriter).writeWindowUpdate(eqCodecCtx(), eq(0), eq(32 * 1024), anyChannelPromise());\n verify(frameWriter).writeWindowUpdate(\n eqCodecCtx(), eq(childChannel.stream().id()), eq(32 * 1024), anyChannelPromise());\n assertTrue(flushSniffer.checkFlush());\n }",
" private static void verifyFramesMultiplexedToCorrectChannel(Http2StreamChannel streamChannel,\n LastInboundHandler inboundHandler,\n int numFrames) {\n for (int i = 0; i < numFrames; i++) {\n Http2StreamFrame frame = inboundHandler.readInbound();\n assertNotNull(i + \" out of \" + numFrames + \" received\", frame);\n assertEquals(streamChannel.stream(), frame.stream());\n release(frame);\n }\n assertNull(inboundHandler.readInbound());\n }",
" private static int eqStreamId(Http2StreamChannel channel) {\n return eq(channel.stream().id());\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [398, 231], "buggy_code_start_loc": [355, 226], "filenames": ["codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionDecoder.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexTest.java"], "fixing_code_end_loc": [401, 274], "fixing_code_start_loc": [356, 227], "message": "Netty is an open-source, asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. In Netty (io.netty:netty-codec-http2) before version 4.1.61.Final there is a vulnerability that enables request smuggling. The content-length header is not correctly validated if the request only uses a single Http2HeaderFrame with the endStream set to to true. This could lead to request smuggling if the request is proxied to a remote peer and translated to HTTP/1.1. This is a followup of GHSA-wm47-8v5p-wjpj/CVE-2021-21295 which did miss to fix this one case. This was fixed as part of 4.1.61.Final.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netty:netty:*:*:*:*:*:*:*:*", "matchCriteriaId": "BC283248-0EB5-46CA-A68C-4FF004D606F8", "versionEndExcluding": "4.1.61", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netapp:oncommand_api_services:-:*:*:*:*:*:*:*", "matchCriteriaId": "5EC98B22-FFAA-4B59-8E63-EBAA4336AD13", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:netapp:oncommand_workflow_automation:-:*:*:*:*:*:*:*", "matchCriteriaId": "5735E553-9731-4AAC-BCFF-989377F817B3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "0CF9A061-2421-426D-9854-0A4E55B2961D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F95EDC3D-54BB-48F9-82F2-7CCF335FCA78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_corporate_lending_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B72B735F-4E52-484A-9C2C-23E6E2070385", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "8B36A1D4-F391-4EE3-9A65-0A10568795BA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "55116032-AAD1-4FEA-9DA8-2C4CBD3D3F61", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_credit_facilities_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "0275F820-40BE-47B8-B167-815A55DF578E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "9E14324D-B9EE-4C06-ACC7-255189ED6300", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "CBEBB60F-6EAB-4AE5-B777-5044C657FBA8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_trade_finance_process_management:14.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B185C1EA-71E6-4972-8637-08A33CC00841", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:coherence:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "2FF57C7A-92C9-4D71-A7B1-CC9DEFAA8193", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:coherence:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "5FA64A1D-34F9-4441-857A-25C165E6DBB6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_brm_-_elastic_charging_engine:12.0.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "06594847-96ED-4541-B2F4-C7331B603603", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_console:1.7.0:*:*:*:*:*:*:*", "matchCriteriaId": "BC12B43F-30F6-4B05-AB3A-E91D8404D5A5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_policy:1.14.0:*:*:*:*:*:*:*", "matchCriteriaId": "4479F76A-4B67-41CC-98C7-C76B81050F8E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_design_studio:7.4.2.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "040DA31B-2A0C-46F6-8EDF-9B88F9FB0F48", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_messaging_server:8.1:*:*:*:*:*:*:*", "matchCriteriaId": "E1214FDF-357A-4BB9-BADE-50FB2BD16D10", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:helidon:1.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "4E7626D2-D9FF-416A-9581-852CED0D8C24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:helidon:2.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "99344A5D-F4B7-49B4-9AE6-0E2FB3874EA5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jd_edwards_enterpriseone_tools:*:*:*:*:*:*:*:*", "matchCriteriaId": "BE34D4F7-5C18-4578-8D0A-722FDF931333", "versionEndExcluding": "9.2.6.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:nosql_database:*:*:*:*:*:*:*:*", "matchCriteriaId": "7167D144-C4AE-487F-B59A-888E10EA59DF", "versionEndExcluding": "21.1.12", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "8B1C88FD-C2EC-4C96-AC7E-6F95C8763B48", "versionEndExcluding": null, "versionEndIncluding": "17.12.11", "versionStartExcluding": null, "versionStartIncluding": "17.12.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "53E2276C-9515-46F6-A621-213A3047B9A6", "versionEndExcluding": null, "versionEndIncluding": "18.8.11", "versionStartExcluding": null, "versionStartIncluding": "18.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_gateway:*:*:*:*:*:*:*:*", "matchCriteriaId": "3EF7E2B4-B741-41E9-8EF6-6C415AB9EF54", "versionEndExcluding": null, "versionEndIncluding": "19.12.10", "versionStartExcluding": null, "versionStartIncluding": "19.12.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:quarkus:quarkus:*:*:*:*:*:*:*:*", "matchCriteriaId": "64839EBF-078E-492A-897C-9AFFB7678ED8", "versionEndExcluding": null, "versionEndIncluding": "1.13.7", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Netty is an open-source, asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. In Netty (io.netty:netty-codec-http2) before version 4.1.61.Final there is a vulnerability that enables request smuggling. The content-length header is not correctly validated if the request only uses a single Http2HeaderFrame with the endStream set to to true. This could lead to request smuggling if the request is proxied to a remote peer and translated to HTTP/1.1. This is a followup of GHSA-wm47-8v5p-wjpj/CVE-2021-21295 which did miss to fix this one case. This was fixed as part of 4.1.61.Final."}, {"lang": "es", "value": "Netty es un framework de aplicaci\u00f3n de red de c\u00f3digo abierto y as\u00edncrono event-driven para el desarrollo r\u00e1pido de servidores y clientes de protocolo de alto rendimiento mantenibles. En Netty (io.netty:netty-codec-http2) versiones anteriores a 4.1.61.Final se presenta una vulnerabilidad que permite el trafico no autorizado de peticiones. El encabezado content-length no es comprobado correctamente si la petici\u00f3n solo usa un \u00fanico Http2HeaderFrame con endStream establecido en verdadero. Esto podr\u00eda conllevar al trafico no autorizado de peticiones si la petici\u00f3n se env\u00eda a un peer remoto y se traduce a HTTP/1.1. Este es un seguimiento de GHSA-wm47-8v5p-wjpj/CVE-2021-21295 que no pudo solucionar este caso. Esto se corrigi\u00f3 como parte de la versi\u00f3n 4.1.61.Final."}], "evaluatorComment": null, "id": "CVE-2021-21409", "lastModified": "2022-05-12T14:35:58.710", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-30T15:15:14.573", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-21295"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/netty/netty/commit/b0fa4d5aab4215f3c22ce6123dd8dd5f38dc0432"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/netty/netty/security/advisories/GHSA-f256-j965-7f32"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/netty/netty/security/advisories/GHSA-wm47-8v5p-wjpj"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r0b09f3e31e004fe583f677f7afa46bd30110904576c13c5ac818ac2c@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r0ca82fec33334e571fe5b388272260778883e307e15415d7b1443de2@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r101f82d8f3b5af0bf79aecbd5b2dd3b404f6bb51d1a54c2c3d29bed9@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r1b3cb056364794f919aaf26ceaf7423de64e7fdd05a914066e7d5219@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r2732aa3884cacfecac4c54cfaa77c279ba815cad44b464a567216f83@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r31044fb995e894749cb821c6fe56f487c16a97028e6e360e59f09d58@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4a98827bb4a7edbd69ef862f2351391845697c40711820d10df52ca5@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4b8be87acf5b9c098a2ee350b5ca5716fe7afeaf0a21a4ee45a90687@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r4ea2f1a9d79d4fc1896e085f31fb60a21b1770d0a26a5250f849372d@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r584cf871f188c406d8bd447ff4e2fd9817fca862436c064d0951a071@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5baac01f9e06c40ff7aab209d5751b3b58802c63734e33324b70a06a@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5cbea8614812289a9b98d0cfc54b47f54cef424ac98d5e315b791795@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r5f2f120b2b8d099226473db1832ffb4d7c1d6dc2d228a164bf293a8e@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r602e98daacc98934f097f07f2eed6eb07c18bfc1949c8489dc7bfcf5@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r61564d86a75403b854cdafee67fc69c8b88c5f6802c2c838f4282cc8@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r69efd8ef003f612c43e4154e788ca3b1f837feaacd16d97854402355@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r6dac9bd799ceac499c7a7e152a9b0dc7f2fe7f89ec5605d129bb047b@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r70c3a7bfa904f06a1902f4df20ee26e4f09a46b8fd3eb304dc57a2de@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r7879ddcb990c835c6b246654770d836f9d031dee982be836744e50ed@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r7b54563abebe3dbbe421e1ba075c2030d8d460372f8c79b7789684b6@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r823d4b27fcba8dad5fe945bdefce3ca5a0031187966eb6ef3cc22ba9@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r855b4b6814ac829ce2d48dd9d8138d07f33387e710de798ee92c011e@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r967002f0939e69bdec58f070735a19dd57c1f2b8f817949ca17cddae@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r9ec78dc409f3f1edff88f21cab53737f36aad46f582a9825389092e0@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/r9fe840c36b74f92b8d4a089ada1f9fd1d6293742efa18b10e06b66d2@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra64d56a8a331ffd7bdcd24a9aaaeeedeacd5d639f5a683389123f898@%3Cdev.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra655e5cec74d1ddf62adacb71d398abd96f3ea2c588f6bbf048348eb@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ra66e93703e3f4bd31bdfd0b6fb0c32ae96b528259bb1aa2b6d38e401@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/raa413040db6d2197593cc03edecfd168732e697119e6447b0a25d525@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rac8cf45a1bab9ead5c9a860cbadd6faaeb7792203617b6ec3874736d@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rafc77f9f03031297394f3d372ccea751b23576f8a2ae9b6b053894c5@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rba2a9ef1d0af882ab58fadb336a58818495245dda43d32a7d7837187@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rbde2f13daf4911504f0eaea43eee4f42555241b5f6d9d71564b6c5fa@%3Cjira.kafka.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rca0978b634a0c3ebee4126ec29c7f570b165fae3f8f3658754c1cbd3@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rcae42fba06979934208bbd515584b241d3ad01d1bb8b063512644362@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rd4a6b7dec38ea6cd28b6f94bd4b312629a52b80be3786d5fb0e474bc@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rd8f72411fb75b98d366400ae789966373b5c3eb3f511e717caf3e49e@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rdd206d9dd7eb894cc089b37fe6edde2932de88d63a6d8368b44f5101@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rdd5715f3ee5e3216d5e0083a07994f67da6dbb9731ce9e7a6389b18e@%3Ccommits.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re1911e05c08f3ec2bab85744d788773519a0afb27272a31ac2a0b4e8@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re39391adcb863f0e9f3f15e7986255948f263f02e4700b82453e7102@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re4b0141939370304d676fe23774d0c6fbc584b648919825402d0cb39@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re7c69756a102bebce8b8681882844a53e2f23975a189363e68ad0324@%3Cissues.flink.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/re9e6ed60941da831675de2f8f733c026757fb4fa28a7b6c9f3dfb575@%3Cdev.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/redef0fb5474fd686781007de9ddb852b24f1b04131a248d9a4789183@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf148b2bf6c2754153a8629bc7495e216bd0bd4c915695486542a10b4@%3Cnotifications.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf38e4dcdefc7c59f7ba0799a399d6d6e37b555d406a1dfc2fcbf0b35@%3Ccommits.pulsar.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf521ff2be2e2dd38984174d3451e6ee935c845948845c8fccd86371d@%3Cissues.zookeeper.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf934292a4a1c189827f625d567838d2c1001e4739b158638d844105b@%3Cissues.kudu.apache.org%3E"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20210604-0003/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4885"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com//security-alerts/cpujul2021.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujan2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuoct2021.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/netty/netty/commit/b0fa4d5aab4215f3c22ce6123dd8dd5f38dc0432"}, "type": "CWE-444"}
| 258
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*********************************************************************\n class.staff.php",
" Everything about staff.",
" Peter Rotich <peter@osticket.com>\n Copyright (c) 2006-2013 osTicket\n http://www.osticket.com",
" Released under the GNU General Public License WITHOUT ANY WARRANTY.\n See LICENSE.TXT for details.",
" vim: expandtab sw=4 ts=4 sts=4:\n**********************************************************************/\ninclude_once(INCLUDE_DIR.'class.ticket.php');\ninclude_once(INCLUDE_DIR.'class.dept.php');\ninclude_once(INCLUDE_DIR.'class.error.php');\ninclude_once(INCLUDE_DIR.'class.team.php');\ninclude_once(INCLUDE_DIR.'class.role.php');\ninclude_once(INCLUDE_DIR.'class.passwd.php');\ninclude_once(INCLUDE_DIR.'class.user.php');\ninclude_once(INCLUDE_DIR.'class.auth.php');",
"class Staff extends VerySimpleModel\nimplements AuthenticatedUser, EmailContact, TemplateVariable, Searchable {",
" static $meta = array(\n 'table' => STAFF_TABLE,\n 'pk' => array('staff_id'),\n 'joins' => array(\n 'dept' => array(\n 'constraint' => array('dept_id' => 'Dept.id'),\n ),\n 'role' => array(\n 'constraint' => array('role_id' => 'Role.id'),\n ),\n 'dept_access' => array(\n 'reverse' => 'StaffDeptAccess.staff',\n ),\n 'teams' => array(\n 'reverse' => 'TeamMember.staff',\n ),\n ),\n );",
" var $authkey;\n var $departments;\n var $stats = array();\n var $_extra;\n var $passwd_change;\n var $_roles = null;\n var $_teams = null;\n var $_config = null;\n var $_perm;",
" function __onload() {",
" // WE have to patch info here to support upgrading from old versions.\n $time = null;\n if (isset($this->passwdreset) && $this->passwdreset)\n $time=strtotime($this->passwdreset);\n elseif (isset($this->added) && $this->added)\n $time=strtotime($this->added);",
" if ($time)\n $this->passwd_change = time()-$time; //XXX: check timezone issues.\n }",
" function get($field, $default=false) {",
" // Check primary fields\n try {\n return parent::get($field, $default);\n } catch (Exception $e) {}",
" // Autoload config if not loaded already\n if (!isset($this->_config))\n $this->getConfig();",
" if (isset($this->_config[$field]))\n return $this->_config[$field];\n }",
" function getConfig() {",
" if (!isset($this->_config) && $this->getId()) {\n $_config = new Config('staff.'.$this->getId(),\n // Defaults\n array(\n 'default_from_name' => '',\n 'datetime_format' => '',\n 'thread_view_order' => '',\n 'default_ticket_queue_id' => 0,\n 'reply_redirect' => 'Ticket',\n 'img_att_view' => 'download',\n 'editor_spacing' => 'double',\n ));\n $this->_config = $_config->getInfo();\n }",
" return $this->_config;\n }",
" function __toString() {\n return (string) $this->getName();\n }",
" function asVar() {\n return $this->__toString();\n }",
" static function getVarScope() {\n return array(\n 'dept' => array('class' => 'Dept', 'desc' => __('Department')),\n 'email' => __('Email Address'),\n 'name' => array(\n 'class' => 'PersonsName', 'desc' => __('Agent name'),\n ),\n 'mobile' => __('Mobile Number'),\n 'phone' => __('Phone Number'),\n 'signature' => __('Signature'),\n 'timezone' => \"Agent's configured timezone\",\n 'username' => 'Access username',\n );\n }",
" function getVar($tag) {\n switch ($tag) {\n case 'mobile':\n return Format::phone($this->ht['mobile']);\n case 'phone':\n return Format::phone($this->ht['phone']);\n }\n }",
" static function getSearchableFields() {\n return array(\n 'email' => new TextboxField(array(\n 'label' => __('Email Address'),\n )),\n );\n }",
" static function supportsCustomData() {\n return false;\n }",
" function getHashtable() {\n $base = $this->ht;\n unset($base['teams']);\n unset($base['dept_access']);",
" if ($this->getConfig())\n $base += $this->getConfig();",
" return $base;\n }",
" function getInfo() {\n return $this->getHashtable();\n }",
" // AuthenticatedUser implementation...\n // TODO: Move to an abstract class that extends Staff\n function getUserType() {\n return 'staff';\n }",
" function getAuthBackend() {\n list($bk, ) = explode(':', $this->getAuthKey());",
" // If administering a user other than yourself, fallback to the\n // agent's declared backend, if any\n if (!$bk && $this->backend)\n $bk = $this->backend;",
" return StaffAuthenticationBackend::getBackend($bk);\n }",
" function setAuthKey($key) {\n $this->authkey = $key;\n }",
" function getAuthKey() {\n return $this->authkey;\n }",
" // logOut the user\n function logOut() {",
" if ($bk = $this->getAuthBackend())\n return $bk->signOut($this);",
" return false;\n }",
" /*compares user password*/\n function check_passwd($password, $autoupdate=true) {",
" /*bcrypt based password match*/\n if(Passwd::cmp($password, $this->getPasswd()))\n return true;",
" //Fall back to MD5\n if(!$password || strcmp($this->getPasswd(), MD5($password)))\n return false;",
" //Password is a MD5 hash: rehash it (if enabled) otherwise force passwd change.\n $this->passwd = Passwd::hash($password);",
" if(!$autoupdate || !$this->save())\n $this->forcePasswdRest();",
" return true;\n }",
" function cmp_passwd($password) {\n return $this->check_passwd($password, false);\n }",
" function hasPassword() {\n return (bool) $this->passwd;\n }",
" function forcePasswdRest() {\n $this->change_passwd = 1;\n return $this->save();\n }",
" /* check if passwd reset is due. */\n function isPasswdResetDue() {\n global $cfg;\n return ($cfg && $cfg->getPasswdResetPeriod()\n && $this->passwd_change>($cfg->getPasswdResetPeriod()*30*24*60*60));\n }",
" function setPassword($new, $current=false) {\n global $thisstaff;",
" // Allow the backend to update the password. This is the preferred\n // method as it allows for integration with password policies and\n // also allows for remotely updating the password where possible and\n // supported.\n if (!($bk = $this->getAuthBackend())\n || !$bk instanceof AuthBackend\n ) {\n // Fallback to osTicket authentication token udpates\n $bk = new osTicketAuthentication();\n }",
" // And now for the magic\n if (!$bk->supportsPasswordChange()) {\n throw new PasswordUpdateFailed(\n __('Authentication backend does not support password updates'));\n }\n // Backend should throw PasswordUpdateFailed directly\n $rv = $bk->setPassword($this, $new, $current);",
" // Successfully updated authentication tokens\n $this->change_passwd = 0;\n $this->cancelResetTokens();\n $this->passwdreset = SqlFunction::NOW();",
" // Clean sessions\n Signal::send('auth.clean', $this, $thisstaff);",
" return $rv;\n }",
" function canAccess($something) {\n if ($something instanceof RestrictedAccess)\n return $something->checkStaffPerm($this);",
" return true;\n }",
" function isPasswdChangeDue() {\n return $this->isPasswdResetDue();\n }",
" function getRefreshRate() {\n return $this->auto_refresh_rate;\n }",
" function getPageLimit() {\n return $this->max_page_size;\n }",
" function getId() {\n return $this->staff_id;\n }\n function getUserId() {\n return $this->getId();\n }",
" function getEmail() {\n return $this->email;\n }",
" function getAvatar($size=null) {\n global $cfg;\n $source = $cfg->getStaffAvatarSource();\n $avatar = $source->getAvatar($this);\n if (isset($size))\n $avatar->setSize($size);\n return $avatar;\n }",
" function getUserName() {\n return $this->username;\n }",
" function getPasswd() {\n return $this->passwd;\n }",
" function getName() {\n return new AgentsName(array('first' => $this->ht['firstname'], 'last' => $this->ht['lastname']));\n }",
" function getAvatarAndName() {\n return $this->getAvatar().Format::htmlchars((string) $this->getName());\n }",
" function getFirstName() {\n return $this->firstname;\n }",
" function getLastName() {\n return $this->lastname;\n }",
" function getSignature() {\n return $this->signature;\n }",
" function getDefaultTicketQueueId() {\n return $this->default_ticket_queue_id;\n }",
" function getDefaultSignatureType() {\n return $this->default_signature_type;\n }",
" function getReplyFromNameType() {\n return $this->default_from_name;\n }",
" function getDefaultPaperSize() {\n return $this->default_paper_size;\n }",
" function getReplyRedirect() {\n return $this->reply_redirect;\n }",
" function getImageAttachmentView() {\n return $this->img_att_view;\n }",
" function editorSpacing() {\n return $this->editor_spacing;\n }",
" function forcePasswdChange() {\n return $this->change_passwd;\n }",
" function getDepartments() {\n // TODO: Cache this in the agent's session as it is unlikely to\n // change while logged in",
" if (!isset($this->departments)) {",
" // Departments the staff is \"allowed\" to access...\n // based on the group they belong to + user's primary dept + user's managed depts.\n $sql='SELECT DISTINCT d.id FROM '.STAFF_TABLE.' s '\n .' LEFT JOIN '.STAFF_DEPT_TABLE.' g ON (s.staff_id=g.staff_id) '\n .' INNER JOIN '.DEPT_TABLE.' d ON (LOCATE(CONCAT(\"/\", s.dept_id, \"/\"), d.path) OR d.manager_id=s.staff_id OR LOCATE(CONCAT(\"/\", g.dept_id, \"/\"), d.path)) '\n .' WHERE s.staff_id='.db_input($this->getId());\n $depts = array();\n if (($res=db_query($sql)) && db_num_rows($res)) {\n while(list($id)=db_fetch_row($res))\n $depts[] = (int) $id;\n }",
" /* ORM method — about 2.0ms slower\n $q = Q::any(array(\n 'path__contains' => '/'.$this->dept_id.'/',\n 'manager_id' => $this->getId(),\n ));\n // Add in extended access\n foreach ($this->dept_access->depts->values_flat('dept_id') as $row) {\n // Skip primary dept\n if ($row[0] == $this->dept_id)\n continue;\n $q->add(new Q(array('path__contains'=>'/'.$row[0].'/')));\n }",
" $dept_ids = Dept::objects()\n ->filter($q)\n ->distinct('id')\n ->values_flat('id');",
" foreach ($dept_ids as $row)\n $depts[] = $row[0];\n */",
" $this->departments = $depts;\n }",
" return $this->departments;\n }",
" function getDepts() {\n return $this->getDepartments();\n }",
" function getManagedDepartments() {",
" return ($depts=Dept::getDepartments(\n array('manager' => $this->getId())\n ))?array_keys($depts):array();\n }",
" function getDeptId() {\n return $this->dept_id;\n }",
" function getDept() {\n return $this->dept;\n }",
" function setDepartmentId($dept_id, $eavesdrop=false) {\n // Grant access to the current department\n $old = $this->dept_id;\n if ($eavesdrop) {\n $da = new StaffDeptAccess(array(\n 'dept_id' => $old,\n 'role_id' => $this->role_id,\n ));\n $da->setAlerts(true);\n $this->dept_access->add($da);\n }",
" // Drop extended access to new department\n $this->dept_id = $dept_id;\n if ($da = $this->dept_access->findFirst(array(\n 'dept_id' => $dept_id))\n ) {\n $this->dept_access->remove($da);\n }",
" $this->save();\n }",
" function usePrimaryRoleOnAssignment() {\n return $this->getExtraAttr('def_assn_role', true);\n }",
" function getLanguage() {\n return (isset($this->lang)) ? $this->lang : false;\n }",
" function getTimezone() {\n if (isset($this->timezone))\n return $this->timezone;\n }",
" function getLocale() {\n //XXX: isset is required here to avoid possible crash when upgrading\n // installation where locale column doesn't exist yet.\n return isset($this->locale) ? $this->locale : 0;\n }",
" function getRoles() {\n if (!isset($this->_roles)) {\n $this->_roles = array($this->dept_id => $this->role);\n foreach($this->dept_access as $da)\n $this->_roles[$da->dept_id] = $da->role;\n }",
" return $this->_roles;\n }",
" function getRole($dept=null, $assigned=false) {",
" if (is_null($dept))\n return $this->role;",
" if (is_numeric($dept))\n $deptId = $dept;\n elseif($dept instanceof Dept)\n $deptId = $dept->getId();\n else\n return null;",
" $roles = $this->getRoles();\n if (isset($roles[$deptId]))\n return $roles[$deptId];",
" // Default to primary role.\n if ($assigned && $this->usePrimaryRoleOnAssignment())\n return $this->role;",
" // Ticket Create & View only access\n $perms = JSONDataEncoder::encode(array(\n Ticket::PERM_CREATE => 1));\n return new Role(array('permissions' => $perms));\n }",
" function hasPerm($perm, $global=true) {\n if ($global)\n return $this->getPermission()->has($perm);\n if ($this->getRole()->hasPerm($perm))\n return true;\n foreach ($this->dept_access as $da)\n if ($da->role->hasPerm($perm))\n return true;\n return false;\n }",
" function canSearchEverything() {\n return $this->hasPerm(SearchBackend::PERM_EVERYTHING);\n }",
" function canManageTickets() {\n return $this->hasPerm(Ticket::PERM_DELETE, false)\n || $this->hasPerm(Ticket::PERM_TRANSFER, false)\n || $this->hasPerm(Ticket::PERM_ASSIGN, false)\n || $this->hasPerm(Ticket::PERM_CLOSE, false);\n }",
" function isManager($dept=null) {\n return (($dept=$dept?:$this->getDept()) && $dept->getManagerId()==$this->getId());\n }",
" function isStaff() {\n return TRUE;\n }",
" function isActive() {\n return $this->isactive;\n }",
" function getStatus() {\n return $this->isActive() ? __('Active') : __('Locked');\n }",
" function isVisible() {\n return $this->isvisible;\n }",
" function onVacation() {\n return $this->onvacation;\n }",
" function isAvailable() {\n return ($this->isActive() && !$this->onVacation());\n }",
" function showAssignedOnly() {\n return $this->assigned_only;\n }",
" function isAccessLimited() {\n return $this->showAssignedOnly();\n }",
" function isAdmin() {\n return $this->isadmin;\n }",
" function isTeamMember($teamId) {\n return ($teamId && in_array($teamId, $this->getTeams()));\n }",
" function canAccessDept($dept) {",
" if (!$dept instanceof Dept)\n return false;",
" return (!$this->isAccessLimited()\n && in_array($dept->getId(), $this->getDepts()));\n }",
" function getTeams() {",
" if (!isset($this->_teams)) {\n $this->_teams = array();\n foreach ($this->teams as $team)\n $this->_teams[] = (int) $team->team_id;\n }",
" return $this->_teams;\n }",
" function getTicketsVisibility($exclude_archived=false) {\n // -- Open and assigned to me\n $assigned = Q::any(array(\n 'staff_id' => $this->getId(),\n ));\n $assigned->add(array('thread__referrals__agent__staff_id' => $this->getId()));\n $childRefAgent = Q::all(new Q(array('child_thread__object_type' => 'C',\n 'child_thread__referrals__agent__staff_id' => $this->getId())));\n $assigned->add($childRefAgent);\n // -- Open and assigned to a team of mine\n if (($teams = array_filter($this->getTeams()))) {\n $assigned->add(array('team_id__in' => $teams));\n $assigned->add(array('thread__referrals__team__team_id__in' => $teams));\n $childRefTeam = Q::all(new Q(array('child_thread__object_type' => 'C',\n 'child_thread__referrals__team__team_id__in' => $teams)));\n $assigned->add($childRefTeam);\n }\n $visibility = Q::any(new Q(array('status__state'=>'open', $assigned)));\n // -- If access is limited to assigned only, return assigned\n if ($this->isAccessLimited())\n return $visibility;\n // -- Routed to a department of mine\n if (($depts=$this->getDepts()) && count($depts)) {\n $in_dept = Q::any(array(\n 'dept_id__in' => $depts,\n 'thread__referrals__dept__id__in' => $depts,\n ));\n if ($exclude_archived) {\n $in_dept = Q::all(array(\n 'status__state__in' => ['open', 'closed'],\n $in_dept,\n ));\n }\n $visibility->add($in_dept);\n $childRefDept = Q::all(new Q(array('child_thread__object_type' => 'C',\n 'child_thread__referrals__dept__id__in' => $depts)));\n $visibility->add($childRefDept);\n }\n return $visibility;\n }",
" function applyVisibility($query, $exclude_archived=false) {\n return $query->filter($this->getTicketsVisibility($exclude_archived));\n }",
" /* stats */\n function resetStats() {\n $this->stats = array();\n }",
" function getTasksStats() {",
" if (!$this->stats['tasks'])\n $this->stats['tasks'] = Task::getStaffStats($this);",
" return $this->stats['tasks'];\n }",
" function getNumAssignedTasks() {\n return ($stats=$this->getTasksStats()) ? $stats['assigned'] : 0;\n }",
" function getNumClosedTasks() {\n return ($stats=$this->getTasksStats()) ? $stats['closed'] : 0;\n }",
" function getExtraAttr($attr=false, $default=null) {\n if (!isset($this->_extra) && isset($this->extra))\n $this->_extra = JsonDataParser::decode($this->extra);",
" return $attr\n ? (isset($this->_extra[$attr]) ? $this->_extra[$attr] : $default)\n : $this->_extra;\n }",
" function setExtraAttr($attr, $value, $commit=true) {\n $this->getExtraAttr();\n $this->_extra[$attr] = $value;\n $this->extra = JsonDataEncoder::encode($this->_extra);",
" if ($commit) {\n $this->save();\n }\n }",
" function getPermission() {\n if (!isset($this->_perm)) {\n $this->_perm = new RolePermission($this->permissions);\n }\n return $this->_perm;\n }",
" function getPermissionInfo() {\n return $this->getPermission()->getInfo();\n }",
" function onLogin($bk) {\n // Update last apparent language preference\n $this->setExtraAttr('browser_lang',\n Internationalization::getCurrentLanguage(),\n false);",
" $this->lastlogin = SqlFunction::NOW();\n $this->save();\n }",
" //Staff profile update...unfortunately we have to separate it from admin update to avoid potential issues\n function updateProfile($vars, &$errors) {\n global $cfg;",
" $vars['firstname']=Format::striptags($vars['firstname']);\n $vars['lastname']=Format::striptags($vars['lastname']);",
" if (isset($this->staff_id) && $this->getId() != $vars['id'])\n $errors['err']=__('Internal error occurred');",
" if(!$vars['firstname'])\n $errors['firstname']=__('First name is required');",
" if(!$vars['lastname'])\n $errors['lastname']=__('Last name is required');",
" if(!$vars['email'] || !Validator::is_valid_email($vars['email']))\n $errors['email']=__('Valid email is required');\n elseif(Email::getIdByEmail($vars['email']))\n $errors['email']=__('Already in-use as system email');\n elseif (($uid=static::getIdByEmail($vars['email']))\n && (!isset($this->staff_id) || $uid!=$this->getId()))\n $errors['email']=__('Email already in use by another agent');",
" if($vars['phone'] && !Validator::is_phone($vars['phone']))\n $errors['phone']=__('Valid phone number is required');",
" if($vars['mobile'] && !Validator::is_phone($vars['mobile']))\n $errors['mobile']=__('Valid phone number is required');",
" if($vars['default_signature_type']=='mine' && !$vars['signature'])\n $errors['default_signature_type'] = __(\"You don't have a signature\");",
" // Update the user's password if requested\n if ($vars['passwd1']) {\n try {\n $this->setPassword($vars['passwd1'], $vars['cpasswd']);\n }\n catch (BadPassword $ex) {\n $errors['passwd1'] = $ex->getMessage();\n }\n catch (PasswordUpdateFailed $ex) {\n // TODO: Add a warning banner or crash the update\n }\n }",
" $vars['onvacation'] = isset($vars['onvacation']) ? 1 : 0;\n $this->firstname = $vars['firstname'];\n $this->lastname = $vars['lastname'];\n $this->email = $vars['email'];\n $this->phone = Format::phone($vars['phone']);\n $this->phone_ext = $vars['phone_ext'];\n $this->mobile = Format::phone($vars['mobile']);\n $this->signature = Format::sanitize($vars['signature']);\n $this->timezone = $vars['timezone'];\n $this->locale = $vars['locale'];\n $this->max_page_size = $vars['max_page_size'];\n $this->auto_refresh_rate = $vars['auto_refresh_rate'];\n $this->default_signature_type = $vars['default_signature_type'];\n $this->default_paper_size = $vars['default_paper_size'];\n $this->lang = $vars['lang'];\n $this->onvacation = $vars['onvacation'];",
" if (isset($vars['avatar_code']))\n $this->setExtraAttr('avatar', $vars['avatar_code']);",
" if ($errors)\n return false;",
" $_SESSION['::lang'] = null;\n TextDomain::configureForUser($this);",
" // Update the config information\n $_config = new Config('staff.'.$this->getId());\n $_config->updateAll(array(\n 'datetime_format' => $vars['datetime_format'],\n 'default_from_name' => $vars['default_from_name'],\n 'thread_view_order' => $vars['thread_view_order'],\n 'default_ticket_queue_id' => $vars['default_ticket_queue_id'],\n 'reply_redirect' => ($vars['reply_redirect'] == 'Queue') ? 'Queue' : 'Ticket',\n 'img_att_view' => ($vars['img_att_view'] == 'inline') ? 'inline' : 'download',\n 'editor_spacing' => ($vars['editor_spacing'] == 'double') ? 'double' : 'single'\n )\n );\n $this->_config = $_config->getInfo();",
" return $this->save();\n }",
" function updateTeams($membership, &$errors) {\n $dropped = array();\n foreach ($this->teams as $TM)\n $dropped[$TM->team_id] = 1;",
" reset($membership);\n while(list(, list($team_id, $alerts)) = each($membership)) {\n $member = $this->teams->findFirst(array('team_id' => $team_id));\n if (!$member) {\n $this->teams->add($member = new TeamMember(array(\n 'team_id' => $team_id,\n )));\n }\n $member->setAlerts($alerts);\n if (!$errors)\n $member->save();\n unset($dropped[$member->team_id]);\n }\n if (!$errors && $dropped) {\n $member = $this->teams\n ->filter(array('team_id__in' => array_keys($dropped)))\n ->delete();\n $this->teams->reset();\n }\n return true;\n }",
" function delete() {\n global $thisstaff;",
" if (!$thisstaff || $this->getId() == $thisstaff->getId())\n return false;",
" if (!parent::delete())\n return false;",
" $type = array('type' => 'deleted');\n Signal::send('object.deleted', $this, $type);",
" // DO SOME HOUSE CLEANING\n //Move remove any ticket assignments...TODO: send alert to Dept. manager?\n Ticket::objects()\n ->filter(array('staff_id' => $this->getId()))\n ->update(array('staff_id' => 0));",
" //Update the poster and clear staff_id on ticket thread table.\n ThreadEntry::objects()\n ->filter(array('staff_id' => $this->getId()))\n ->update(array(\n 'staff_id' => 0,\n 'poster' => $this->getName()->getOriginal(),\n ));",
" // Cleanup Team membership table.\n TeamMember::objects()\n ->filter(array('staff_id'=>$this->getId()))\n ->delete();",
" // Cleanup staff dept access\n StaffDeptAccess::objects()\n ->filter(array('staff_id'=>$this->getId()))\n ->delete();",
" return true;\n }",
" /**** Static functions ********/\n static function lookup($var) {\n if (is_array($var))\n return parent::lookup($var);\n elseif (is_numeric($var))",
" return parent::lookup(array('staff_id'=>$var));",
" elseif (Validator::is_email($var))",
" return parent::lookup(array('email'=>$var));\n elseif (is_string($var))\n return parent::lookup(array('username'=>$var));",
" else\n return null;\n }",
" static function getStaffMembers($criteria=array()) {\n global $cfg;",
" $members = static::objects();",
" if (isset($criteria['available'])) {\n $members = $members->filter(array(\n 'onvacation' => 0,\n 'isactive' => 1,\n ));\n }",
" $members = self::nsort($members);",
" $users=array();\n foreach ($members as $M) {\n $users[$M->getId()] = $M->getName();\n }",
" return $users;\n }",
" static function getAvailableStaffMembers() {\n return self::getStaffMembers(array('available'=>true));\n }",
" static function getsortby($path='', $format=null) {\n global $cfg;",
" $format = $format ?: $cfg->getAgentNameFormat();\n switch ($format) {\n case 'last':\n case 'lastfirst':\n case 'legal':\n $fields = array(\"{$path}lastname\", \"{$path}firstname\");\n break;\n default:\n $fields = array(\"${path}firstname\", \"${path}lastname\");\n }",
" return $fields;\n }",
" static function nsort(QuerySet $qs, $path='', $format=null) {\n $fields = self::getsortby($path, $format);\n $qs->order_by($fields);\n return $qs;\n }",
" static function getIdByUsername($username) {\n $row = static::objects()->filter(array('username' => $username))\n ->values_flat('staff_id')->first();\n return $row ? $row[0] : 0;\n }",
" static function getIdByEmail($email) {\n $row = static::objects()->filter(array('email' => $email))\n ->values_flat('staff_id')->first();\n return $row ? $row[0] : 0;\n }",
"\n static function create($vars=false) {\n $staff = new static($vars);\n $staff->created = SqlFunction::NOW();\n return $staff;\n }",
" function cancelResetTokens() {\n // TODO: Drop password-reset tokens from the config table for\n // this user id\n $sql = 'DELETE FROM '.CONFIG_TABLE.' WHERE `namespace`=\"pwreset\"\n AND `value`='.db_input($this->getId());\n db_query($sql, false);\n unset($_SESSION['_staff']['reset-token']);\n }",
" function sendResetEmail($template='pwreset-staff', $log=true) {\n global $ost, $cfg;",
" $content = Page::lookupByType($template);\n $token = Misc::randCode(48); // 290-bits",
" if (!$content)\n return new BaseError(/* @trans */ 'Unable to retrieve password reset email template');",
" $vars = array(\n 'url' => $ost->getConfig()->getBaseUrl(),\n 'token' => $token,\n 'staff' => $this,\n 'recipient' => $this,\n 'reset_link' => sprintf(\n \"%s/scp/pwreset.php?token=%s\",\n $ost->getConfig()->getBaseUrl(),\n $token),\n );\n $vars['link'] = &$vars['reset_link'];",
" if (!($email = $cfg->getAlertEmail()))\n $email = $cfg->getDefaultEmail();",
" $info = array('email' => $email, 'vars' => &$vars, 'log'=>$log);\n Signal::send('auth.pwreset.email', $this, $info);",
" if ($info['log'])\n $ost->logWarning(_S('Agent Password Reset'), sprintf(\n _S('Password reset was attempted for agent: %1$s<br><br>\n Requested-User-Id: %2$s<br>\n Source-Ip: %3$s<br>\n Email-Sent-To: %4$s<br>\n Email-Sent-Via: %5$s'),\n $this->getName(),\n $_POST['userid'],\n $_SERVER['REMOTE_ADDR'],\n $this->getEmail(),\n $email->getEmail()\n ), false);",
" $lang = $this->lang ?: $this->getExtraAttr('browser_lang');\n $msg = $ost->replaceTemplateVariables(array(\n 'subj' => $content->getLocalName($lang),\n 'body' => $content->getLocalBody($lang),\n ), $vars);",
" $_config = new Config('pwreset');\n $_config->set($vars['token'], $this->getId());",
" $email->send($this->getEmail(), Format::striptags($msg['subj']),\n $msg['body']);\n }",
" static function importCsv($stream, $defaults=array(), $callback=false) {\n require_once INCLUDE_DIR . 'class.import.php';",
" $importer = new CsvImporter($stream);\n $imported = 0;\n $fields = array(\n 'firstname' => new TextboxField(array(\n 'label' => __('First Name'),\n )),\n 'lastname' => new TextboxField(array(\n 'label' => __('Last Name'),\n )),\n 'email' => new TextboxField(array(\n 'label' => __('Email Address'),\n 'configuration' => array(\n 'validator' => 'email',\n ),\n )),\n 'username' => new TextboxField(array(\n 'label' => __('Username'),\n 'validators' => function($self, $value) {\n if (!Validator::is_username($value))\n $self->addError('Not a valid username');\n },\n )),\n );\n $form = new SimpleForm($fields);",
" try {\n db_autocommit(false);\n $errors = array();\n $records = $importer->importCsv($form->getFields(), $defaults);\n foreach ($records as $data) {\n if (!isset($data['email']) || !isset($data['username']))\n throw new ImportError('Both `username` and `email` fields are required');",
" if ($agent = self::lookup(array('username' => $data['username']))) {\n // TODO: Update the user\n }\n elseif ($agent = self::create($data, $errors)) {\n if ($callback)\n $callback($agent, $data);\n $agent->save();\n }\n else {\n throw new ImportError(sprintf(__('Unable to import (%s): %s'),\n Format::htmlchars($data['username']),\n print_r(Format::htmlchars($errors), true)\n ));\n }\n $imported++;\n }\n db_autocommit(true);\n }\n catch (Exception $ex) {\n db_rollback();\n return $ex->getMessage();\n }\n return $imported;\n }",
" function save($refetch=false) {\n if ($this->dirty)\n $this->updated = SqlFunction::NOW();\n return parent::save($refetch || $this->dirty);\n }",
" function update($vars, &$errors) {\n $vars['username']=Format::striptags($vars['username']);\n $vars['firstname']=Format::striptags($vars['firstname']);\n $vars['lastname']=Format::striptags($vars['lastname']);",
" if (isset($this->staff_id) && $this->getId() != $vars['id'])\n $errors['err']=__('Internal error occurred');",
" if(!$vars['firstname'])\n $errors['firstname']=__('First name required');\n if(!$vars['lastname'])\n $errors['lastname']=__('Last name required');",
" $error = '';\n if(!$vars['username'] || !Validator::is_username($vars['username'], $error))\n $errors['username']=($error) ? $error : __('Username is required');\n elseif (($uid=static::getIdByUsername($vars['username']))\n && (!isset($this->staff_id) || $uid!=$this->getId()))\n $errors['username']=__('Username already in use');",
" if(!$vars['email'] || !Validator::is_valid_email($vars['email']))\n $errors['email']=__('Valid email is required');\n elseif(Email::getIdByEmail($vars['email']))\n $errors['email']=__('Already in use system email');\n elseif (($uid=static::getIdByEmail($vars['email']))\n && (!isset($this->staff_id) || $uid!=$this->getId()))\n $errors['email']=__('Email already in use by another agent');",
" if($vars['phone'] && !Validator::is_phone($vars['phone']))\n $errors['phone']=__('Valid phone number is required');",
" if($vars['mobile'] && !Validator::is_phone($vars['mobile']))\n $errors['mobile']=__('Valid phone number is required');",
" if(!$vars['dept_id'])\n $errors['dept_id']=__('Department is required');\n if(!$vars['role_id'])\n $errors['role_id']=__('Role for primary department is required');",
" $dept = Dept::lookup($vars['dept_id']);\n if($dept && !$dept->isActive())\n $errors['dept_id'] = sprintf(__('%s selected must be active'), __('Department'));",
" // Ensure we will still have an administrator with access\n if ($vars['isadmin'] !== '1' || $vars['islocked'] === '1') {\n $sql = 'select count(*), max(staff_id) from '.STAFF_TABLE\n .' WHERE isadmin=1 and isactive=1';\n if (($res = db_query($sql))\n && (list($count, $sid) = db_fetch_row($res))) {\n if ($count == 1 && $sid == $uid) {\n $errors['isadmin'] = __(\n 'Cowardly refusing to remove or lock out the only active administrator'\n );\n }\n }\n }",
" // Update the local permissions\n $this->updatePerms($vars['perms'], $errors);",
" //checkboxes\n $vars['isadmin'] = isset($vars['isadmin']) ? 1 : 0;\n $vars['islocked'] = isset($vars['islocked']) ? 0 : 1;\n $vars['isvisible'] = isset($vars['isvisible']) ? 1 : 0;\n $vars['onvacation'] = isset($vars['onvacation']) ? 1 : 0;\n $vars['assigned_only'] = isset($vars['assigned_only']) ? 1 : 0;",
" $this->isadmin = $vars['isadmin'];\n $this->isactive = $vars['islocked'];\n $this->isvisible = $vars['isvisible'];\n $this->onvacation = $vars['onvacation'];\n $this->assigned_only = $vars['assigned_only'];\n $this->role_id = $vars['role_id'];\n $this->username = $vars['username'];\n $this->firstname = $vars['firstname'];\n $this->lastname = $vars['lastname'];\n $this->email = $vars['email'];\n $this->backend = $vars['backend'];\n $this->phone = Format::phone($vars['phone']);\n $this->phone_ext = $vars['phone_ext'];\n $this->mobile = Format::phone($vars['mobile']);\n $this->notes = Format::sanitize($vars['notes']);",
" // Set staff password if exists\n if (!$vars['welcome_email'] && $vars['passwd1']) {\n $this->setPassword($vars['passwd1'], null);\n $this->change_passwd = $vars['change_passwd'] ? 1 : 0;\n }",
" if ($errors)\n return false;",
" if ($this->save()) {\n // Update some things for ::updateAccess to inspect\n $this->setDepartmentId($vars['dept_id']);",
" // Format access update as [array(dept_id, role_id, alerts?)]\n $access = array();\n if (isset($vars['dept_access'])) {\n foreach (@$vars['dept_access'] as $dept_id) {\n $access[] = array($dept_id, $vars['dept_access_role'][$dept_id],\n @$vars['dept_access_alerts'][$dept_id]);\n }\n }\n $this->updateAccess($access, $errors);\n $this->setExtraAttr('def_assn_role',\n isset($vars['assign_use_pri_role']), true);",
" // Format team membership as [array(team_id, alerts?)]\n $teams = array();\n if (isset($vars['teams'])) {\n foreach (@$vars['teams'] as $team_id) {\n $teams[] = array($team_id, @$vars['team_alerts'][$team_id]);\n }\n }\n $this->updateTeams($teams, $errors);",
" if ($vars['welcome_email'])\n $this->sendResetEmail('registration-staff', false);\n return true;\n }",
" if (isset($this->staff_id)) {\n $errors['err']=sprintf(__('Unable to update %s.'), __('this agent'))\n .' '.__('Internal error occurred');\n } else {\n $errors['err']=sprintf(__('Unable to create %s.'), __('this agent'))\n .' '.__('Internal error occurred');\n }\n return false;\n }",
" /**\n * Parameters:\n * $access - (<array($dept_id, $role_id, $alerts)>) a list of the complete,\n * extended access for this agent. Any the agent currently has, which\n * is not listed will be removed.\n * $errors - (<array>) list of error messages from the process, which will\n * be indexed by the dept_id number.\n */\n function updateAccess($access, &$errors) {\n reset($access);\n $dropped = array();\n foreach ($this->dept_access as $DA)\n $dropped[$DA->dept_id] = 1;\n while (list(, list($dept_id, $role_id, $alerts)) = each($access)) {\n unset($dropped[$dept_id]);\n if (!$role_id || !Role::lookup($role_id))\n $errors['dept_access'][$dept_id] = __('Select a valid role');\n if (!$dept_id || !($dept=Dept::lookup($dept_id)))\n $errors['dept_access'][$dept_id] = __('Select a valid department');\n if ($dept_id == $this->getDeptId())\n $errors['dept_access'][$dept_id] = sprintf(__('Agent already has access to %s'), __('this department'));\n $da = $this->dept_access->findFirst(array('dept_id' => $dept_id));\n if (!isset($da)) {\n $da = new StaffDeptAccess(array(\n 'dept_id' => $dept_id, 'role_id' => $role_id\n ));\n $this->dept_access->add($da);\n $type = array('type' => 'edited',\n 'key' => sprintf('%s Department Access Added', $dept->getName()));\n Signal::send('object.edited', $this, $type);\n }\n else {\n $da->role_id = $role_id;\n }\n $da->setAlerts($alerts);\n if (!$errors)\n $da->save();\n }\n if (!$errors && $dropped) {\n $this->dept_access\n ->filter(array('dept_id__in' => array_keys($dropped)))\n ->delete();\n $this->dept_access->reset();\n foreach (array_keys($dropped) as $dept_id) {\n $deptName = Dept::getNameById($dept_id);\n $type = array('type' => 'edited',\n 'key' => sprintf('%s Department Access Removed', $deptName));\n Signal::send('object.edited', $this, $type);\n }\n }\n return !$errors;\n }",
" function updatePerms($vars, &$errors=array()) {\n if (!$vars) {\n $this->permissions = '';\n return;\n }\n $permissions = $this->getPermission();\n foreach ($vars as $k => $val) {\n if (!$permissions->exists($val)) {\n $type = array('type' => 'edited', 'key' => $val);\n Signal::send('object.edited', $this, $type);\n }\n }",
" foreach (RolePermission::allPermissions() as $g => $perms) {\n foreach ($perms as $k => $v) {\n if (!in_array($k, $vars) && $permissions->exists($k)) {\n $type = array('type' => 'edited', 'key' => $k);\n Signal::send('object.edited', $this, $type);\n }\n $permissions->set($k, in_array($k, $vars) ? 1 : 0);\n }\n }\n $this->permissions = $permissions->toJson();\n return true;\n }",
" static function export($criteria=null, $filename='') {\n include_once(INCLUDE_DIR.'class.error.php');",
" $agents = Staff::objects();\n // Sort based on name formating\n $agents = self::nsort($agents);\n Export::agents($agents, $filename);\n }",
"}",
"interface RestrictedAccess {\n function checkStaffPerm($staff);\n}",
"class StaffDeptAccess extends VerySimpleModel {\n static $meta = array(\n 'table' => STAFF_DEPT_TABLE,\n 'pk' => array('staff_id', 'dept_id'),\n 'select_related' => array('dept', 'role'),\n 'joins' => array(\n 'dept' => array(\n 'constraint' => array('dept_id' => 'Dept.id'),\n ),\n 'staff' => array(\n 'constraint' => array('staff_id' => 'Staff.staff_id'),\n ),\n 'role' => array(\n 'constraint' => array('role_id' => 'Role.id'),\n ),\n ),\n );",
" const FLAG_ALERTS = 0x0001;",
" function isAlertsEnabled() {\n return $this->flags & self::FLAG_ALERTS != 0;\n }",
" function setFlag($flag, $value) {\n if ($value)\n $this->flags |= $flag;\n else\n $this->flags &= ~$flag;\n }",
" function setAlerts($value) {\n $this->setFlag(self::FLAG_ALERTS, $value);\n }\n}",
"/**\n * This form is used to administratively change the password. The\n * ChangePasswordForm is used for an agent to change their own password.\n */\nclass PasswordResetForm\nextends AbstractForm {\n function buildFields() {\n return array(\n 'welcome_email' => new BooleanField(array(\n 'default' => true,\n 'configuration' => array(\n 'desc' => __('Send the agent a password reset email'),\n ),\n )),\n 'passwd1' => new PasswordField(array(\n 'placeholder' => __('New Password'),\n 'required' => true,\n 'configuration' => array(\n 'classes' => 'span12',\n ),\n 'visibility' => new VisibilityConstraint(\n new Q(array('welcome_email' => false)),\n VisibilityConstraint::HIDDEN\n ),\n )),\n 'passwd2' => new PasswordField(array(\n 'placeholder' => __('Confirm Password'),\n 'required' => true,\n 'configuration' => array(\n 'classes' => 'span12',\n ),\n 'visibility' => new VisibilityConstraint(\n new Q(array('welcome_email' => false)),\n VisibilityConstraint::HIDDEN\n ),\n )),\n 'change_passwd' => new BooleanField(array(\n 'default' => true,\n 'configuration' => array(\n 'desc' => __('Require password change at next login'),\n 'classes' => 'form footer',\n ),\n 'visibility' => new VisibilityConstraint(\n new Q(array('welcome_email' => false)),\n VisibilityConstraint::HIDDEN\n ),\n )),\n );\n }",
" function validate($clean) {\n if ($clean['passwd1'] != $clean['passwd2'])\n $this->getField('passwd1')->addError(__('Passwords do not match'));\n }\n}",
"class PasswordChangeForm\nextends AbstractForm {\n function buildFields() {\n $fields = array(\n 'current' => new PasswordField(array(\n 'placeholder' => __('Current Password'),\n 'required' => true,\n 'configuration' => array(\n 'autofocus' => true,\n ),\n )),\n 'passwd1' => new PasswordField(array(\n 'label' => __('Enter a new password'),\n 'placeholder' => __('New Password'),\n 'required' => true,\n )),\n 'passwd2' => new PasswordField(array(\n 'placeholder' => __('Confirm Password'),\n 'required' => true,\n )),\n );",
" // When using the password reset system, the current password is not\n // required for agents.\n if (isset($_SESSION['_staff']['reset-token'])) {\n unset($fields['current']);\n $fields['passwd1']->set('configuration', array('autofocus' => true));\n }\n else {\n $fields['passwd1']->set('layout',\n new GridFluidCell(12, array('style' => 'padding-top: 20px'))\n );\n }\n return $fields;\n }",
" function getInstructions() {\n return __('Confirm your current password and enter a new password to continue');\n }",
" function validate($clean) {\n if ($clean['passwd1'] != $clean['passwd2'])\n $this->getField('passwd1')->addError(__('Passwords do not match'));\n }\n}",
"class ResetAgentPermissionsForm\nextends AbstractForm {\n function buildFields() {\n $permissions = array();\n foreach (RolePermission::allPermissions() as $g => $perms) {\n foreach ($perms as $k => $v) {\n if (!$v['primary'])\n continue;\n $permissions[$g][$k] = \"{$v['title']} — {$v['desc']}\";\n }\n }\n return array(\n 'clone' => new ChoiceField(array(\n 'default' => 0,\n 'choices' =>\n array(0 => '— '.__('Clone an existing agent').' —')\n + Staff::getStaffMembers(),\n 'configuration' => array(\n 'classes' => 'span12',\n ),\n )),\n 'perms' => new ChoiceField(array(\n 'choices' => $permissions,\n 'widget' => 'TabbedBoxChoicesWidget',\n 'configuration' => array(\n 'multiple' => true,\n ),\n )),\n );\n }",
" function getClean($validate = true) {\n $clean = parent::getClean();\n // Index permissions as ['ticket.edit' => 1]\n $clean['perms'] = array_keys($clean['perms']);\n return $clean;\n }",
" function render($staff=true, $title=false, $options=array()) {\n return parent::render($staff, $title, $options + array('template' => 'dynamic-form-simple.tmpl.php'));\n }\n}",
"class ChangeDepartmentForm\nextends AbstractForm {\n function buildFields() {\n return array(\n 'dept_id' => new ChoiceField(array(\n 'default' => 0,\n 'required' => true,\n 'label' => __('Primary Department'),\n 'choices' =>\n array(0 => '— '.__('Primary Department').' —')\n + Dept::getDepartments(),\n 'configuration' => array(\n 'classes' => 'span12',\n ),\n )),\n 'role_id' => new ChoiceField(array(\n 'default' => 0,\n 'required' => true,\n 'label' => __('Primary Role'),\n 'choices' =>\n array(0 => '— '.__('Corresponding Role').' —')\n + Role::getRoles(),\n 'configuration' => array(\n 'classes' => 'span12',\n ),\n )),\n 'eavesdrop' => new BooleanField(array(\n 'configuration' => array(\n 'desc' => __('Maintain access to current primary department'),\n 'classes' => 'form footer',\n ),\n )),\n // alerts?\n );\n }",
" function getInstructions() {\n return __('Change the primary department and primary role of the selected agents');\n }",
" function getClean($validate = true) {\n $clean = parent::getClean();\n $clean['eavesdrop'] = $clean['eavesdrop'] ? 1 : 0;\n return $clean;\n }",
" function render($staff=true, $title=false, $options=array()) {\n return parent::render($staff, $title, $options + array('template' => 'dynamic-form-simple.tmpl.php'));\n }\n}",
"class StaffQuickAddForm\nextends AbstractForm {\n static $layout = 'GridFormLayout';",
" function buildFields() {\n global $cfg;",
" return array(\n 'firstname' => new TextboxField(array(\n 'required' => true,\n 'configuration' => array(\n 'placeholder' => __(\"First Name\"),\n 'autofocus' => true,\n ),\n 'layout' => new GridFluidCell(6),\n )),\n 'lastname' => new TextboxField(array(\n 'required' => true,\n 'configuration' => array(\n 'placeholder' => __(\"Last Name\"),\n ),\n 'layout' => new GridFluidCell(6),\n )),\n 'email' => new TextboxField(array(\n 'required' => true,\n 'configuration' => array(\n 'validator' => 'email',\n 'placeholder' => __('Email Address — e.g. me@mycompany.com'),\n 'length' => 128,\n 'autocomplete' => 'email',\n ),\n )),\n 'dept_id' => new ChoiceField(array(\n 'label' => __('Department'),\n 'required' => true,\n 'choices' => Dept::getDepartments(),\n 'default' => $cfg->getDefaultDeptId(),\n 'layout' => new GridFluidCell(6),\n )),\n 'role_id' => new ChoiceField(array(\n 'label' => __('Primary Role'),\n 'required' => true,\n 'choices' =>\n array(0 => __('Select Role'))\n + Role::getRoles(),\n 'layout' => new GridFluidCell(6),\n )),\n 'isadmin' => new BooleanField(array(\n 'label' => __('Account Type'),\n 'configuration' => array(\n 'desc' => __('Agent has access to the admin panel'),\n ),\n 'layout' => new GridFluidCell(6),\n )),\n 'welcome_email' => new BooleanField(array(\n 'configuration' => array(\n 'desc' => __('Send a welcome email with login information'),\n ),\n 'default' => true,\n 'layout' => new GridFluidCell(12, array('style' => 'padding-top: 50px')),\n )),\n 'passwd1' => new PasswordField(array(\n 'required' => true,\n 'configuration' => array(\n 'placeholder' => __(\"Temporary Password\"),\n 'autocomplete' => 'new-password',\n ),\n 'visibility' => new VisibilityConstraint(\n new Q(array('welcome_email' => false))\n ),\n 'layout' => new GridFluidCell(6),\n )),\n 'passwd2' => new PasswordField(array(\n 'required' => true,\n 'configuration' => array(\n 'placeholder' => __(\"Confirm Password\"),\n 'autocomplete' => 'new-password',\n ),\n 'visibility' => new VisibilityConstraint(\n new Q(array('welcome_email' => false))\n ),\n 'layout' => new GridFluidCell(6),\n )),\n // TODO: Add role_id drop-down\n );\n }",
" function getClean($validate = true) {\n $clean = parent::getClean();\n list($clean['username'],) = preg_split('/[^\\w.-]/u', $clean['email'], 2);\n if (mb_strlen($clean['username']) < 3 || Staff::lookup($clean['username']))\n $clean['username'] = mb_strtolower($clean['firstname']);",
"\n // Inherit default dept's role as primary role\n $clean['assign_use_pri_role'] = true;",
" // Default permissions\n $clean['perms'] = array(\n User::PERM_CREATE,\n User::PERM_EDIT,\n User::PERM_DELETE,\n User::PERM_MANAGE,\n User::PERM_DIRECTORY,\n Organization::PERM_CREATE,\n Organization::PERM_EDIT,\n Organization::PERM_DELETE,\n FAQ::PERM_MANAGE,\n );\n return $clean;\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [870, 1348, 224, 19, 76], "buggy_code_start_loc": [865, 1344, 223, 18, 42], "filenames": ["include/class.staff.php", "include/class.user.php", "include/class.validator.php", "pwreset.php", "scp/pwreset.php"], "fixing_code_end_loc": [870, 1348, 232, 21, 79], "fixing_code_start_loc": [865, 1344, 223, 18, 42], "message": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "2ACCEE58-8958-4EBE-BF9E-37DD119DBD44", "versionEndExcluding": "1.14.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "22F26EC6-59B4-4CCA-9A7E-FD8DD0D0ECE9", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.15", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality."}, {"lang": "es", "value": "Una inyecci\u00f3n SQL en el proceso de inicio de sesi\u00f3n y restablecimiento de contrase\u00f1a de osTicket versiones anteriores a 1.14.8 y 1.15.4, permite a atacantes acceder a la funcionalidad osTicket administration profile"}], "evaluatorComment": null, "id": "CVE-2021-42235", "lastModified": "2022-05-13T17:13:06.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-04T17:15:08.087", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}, "type": "CWE-89"}
| 259
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*********************************************************************\n class.staff.php",
" Everything about staff.",
" Peter Rotich <peter@osticket.com>\n Copyright (c) 2006-2013 osTicket\n http://www.osticket.com",
" Released under the GNU General Public License WITHOUT ANY WARRANTY.\n See LICENSE.TXT for details.",
" vim: expandtab sw=4 ts=4 sts=4:\n**********************************************************************/\ninclude_once(INCLUDE_DIR.'class.ticket.php');\ninclude_once(INCLUDE_DIR.'class.dept.php');\ninclude_once(INCLUDE_DIR.'class.error.php');\ninclude_once(INCLUDE_DIR.'class.team.php');\ninclude_once(INCLUDE_DIR.'class.role.php');\ninclude_once(INCLUDE_DIR.'class.passwd.php');\ninclude_once(INCLUDE_DIR.'class.user.php');\ninclude_once(INCLUDE_DIR.'class.auth.php');",
"class Staff extends VerySimpleModel\nimplements AuthenticatedUser, EmailContact, TemplateVariable, Searchable {",
" static $meta = array(\n 'table' => STAFF_TABLE,\n 'pk' => array('staff_id'),\n 'joins' => array(\n 'dept' => array(\n 'constraint' => array('dept_id' => 'Dept.id'),\n ),\n 'role' => array(\n 'constraint' => array('role_id' => 'Role.id'),\n ),\n 'dept_access' => array(\n 'reverse' => 'StaffDeptAccess.staff',\n ),\n 'teams' => array(\n 'reverse' => 'TeamMember.staff',\n ),\n ),\n );",
" var $authkey;\n var $departments;\n var $stats = array();\n var $_extra;\n var $passwd_change;\n var $_roles = null;\n var $_teams = null;\n var $_config = null;\n var $_perm;",
" function __onload() {",
" // WE have to patch info here to support upgrading from old versions.\n $time = null;\n if (isset($this->passwdreset) && $this->passwdreset)\n $time=strtotime($this->passwdreset);\n elseif (isset($this->added) && $this->added)\n $time=strtotime($this->added);",
" if ($time)\n $this->passwd_change = time()-$time; //XXX: check timezone issues.\n }",
" function get($field, $default=false) {",
" // Check primary fields\n try {\n return parent::get($field, $default);\n } catch (Exception $e) {}",
" // Autoload config if not loaded already\n if (!isset($this->_config))\n $this->getConfig();",
" if (isset($this->_config[$field]))\n return $this->_config[$field];\n }",
" function getConfig() {",
" if (!isset($this->_config) && $this->getId()) {\n $_config = new Config('staff.'.$this->getId(),\n // Defaults\n array(\n 'default_from_name' => '',\n 'datetime_format' => '',\n 'thread_view_order' => '',\n 'default_ticket_queue_id' => 0,\n 'reply_redirect' => 'Ticket',\n 'img_att_view' => 'download',\n 'editor_spacing' => 'double',\n ));\n $this->_config = $_config->getInfo();\n }",
" return $this->_config;\n }",
" function __toString() {\n return (string) $this->getName();\n }",
" function asVar() {\n return $this->__toString();\n }",
" static function getVarScope() {\n return array(\n 'dept' => array('class' => 'Dept', 'desc' => __('Department')),\n 'email' => __('Email Address'),\n 'name' => array(\n 'class' => 'PersonsName', 'desc' => __('Agent name'),\n ),\n 'mobile' => __('Mobile Number'),\n 'phone' => __('Phone Number'),\n 'signature' => __('Signature'),\n 'timezone' => \"Agent's configured timezone\",\n 'username' => 'Access username',\n );\n }",
" function getVar($tag) {\n switch ($tag) {\n case 'mobile':\n return Format::phone($this->ht['mobile']);\n case 'phone':\n return Format::phone($this->ht['phone']);\n }\n }",
" static function getSearchableFields() {\n return array(\n 'email' => new TextboxField(array(\n 'label' => __('Email Address'),\n )),\n );\n }",
" static function supportsCustomData() {\n return false;\n }",
" function getHashtable() {\n $base = $this->ht;\n unset($base['teams']);\n unset($base['dept_access']);",
" if ($this->getConfig())\n $base += $this->getConfig();",
" return $base;\n }",
" function getInfo() {\n return $this->getHashtable();\n }",
" // AuthenticatedUser implementation...\n // TODO: Move to an abstract class that extends Staff\n function getUserType() {\n return 'staff';\n }",
" function getAuthBackend() {\n list($bk, ) = explode(':', $this->getAuthKey());",
" // If administering a user other than yourself, fallback to the\n // agent's declared backend, if any\n if (!$bk && $this->backend)\n $bk = $this->backend;",
" return StaffAuthenticationBackend::getBackend($bk);\n }",
" function setAuthKey($key) {\n $this->authkey = $key;\n }",
" function getAuthKey() {\n return $this->authkey;\n }",
" // logOut the user\n function logOut() {",
" if ($bk = $this->getAuthBackend())\n return $bk->signOut($this);",
" return false;\n }",
" /*compares user password*/\n function check_passwd($password, $autoupdate=true) {",
" /*bcrypt based password match*/\n if(Passwd::cmp($password, $this->getPasswd()))\n return true;",
" //Fall back to MD5\n if(!$password || strcmp($this->getPasswd(), MD5($password)))\n return false;",
" //Password is a MD5 hash: rehash it (if enabled) otherwise force passwd change.\n $this->passwd = Passwd::hash($password);",
" if(!$autoupdate || !$this->save())\n $this->forcePasswdRest();",
" return true;\n }",
" function cmp_passwd($password) {\n return $this->check_passwd($password, false);\n }",
" function hasPassword() {\n return (bool) $this->passwd;\n }",
" function forcePasswdRest() {\n $this->change_passwd = 1;\n return $this->save();\n }",
" /* check if passwd reset is due. */\n function isPasswdResetDue() {\n global $cfg;\n return ($cfg && $cfg->getPasswdResetPeriod()\n && $this->passwd_change>($cfg->getPasswdResetPeriod()*30*24*60*60));\n }",
" function setPassword($new, $current=false) {\n global $thisstaff;",
" // Allow the backend to update the password. This is the preferred\n // method as it allows for integration with password policies and\n // also allows for remotely updating the password where possible and\n // supported.\n if (!($bk = $this->getAuthBackend())\n || !$bk instanceof AuthBackend\n ) {\n // Fallback to osTicket authentication token udpates\n $bk = new osTicketAuthentication();\n }",
" // And now for the magic\n if (!$bk->supportsPasswordChange()) {\n throw new PasswordUpdateFailed(\n __('Authentication backend does not support password updates'));\n }\n // Backend should throw PasswordUpdateFailed directly\n $rv = $bk->setPassword($this, $new, $current);",
" // Successfully updated authentication tokens\n $this->change_passwd = 0;\n $this->cancelResetTokens();\n $this->passwdreset = SqlFunction::NOW();",
" // Clean sessions\n Signal::send('auth.clean', $this, $thisstaff);",
" return $rv;\n }",
" function canAccess($something) {\n if ($something instanceof RestrictedAccess)\n return $something->checkStaffPerm($this);",
" return true;\n }",
" function isPasswdChangeDue() {\n return $this->isPasswdResetDue();\n }",
" function getRefreshRate() {\n return $this->auto_refresh_rate;\n }",
" function getPageLimit() {\n return $this->max_page_size;\n }",
" function getId() {\n return $this->staff_id;\n }\n function getUserId() {\n return $this->getId();\n }",
" function getEmail() {\n return $this->email;\n }",
" function getAvatar($size=null) {\n global $cfg;\n $source = $cfg->getStaffAvatarSource();\n $avatar = $source->getAvatar($this);\n if (isset($size))\n $avatar->setSize($size);\n return $avatar;\n }",
" function getUserName() {\n return $this->username;\n }",
" function getPasswd() {\n return $this->passwd;\n }",
" function getName() {\n return new AgentsName(array('first' => $this->ht['firstname'], 'last' => $this->ht['lastname']));\n }",
" function getAvatarAndName() {\n return $this->getAvatar().Format::htmlchars((string) $this->getName());\n }",
" function getFirstName() {\n return $this->firstname;\n }",
" function getLastName() {\n return $this->lastname;\n }",
" function getSignature() {\n return $this->signature;\n }",
" function getDefaultTicketQueueId() {\n return $this->default_ticket_queue_id;\n }",
" function getDefaultSignatureType() {\n return $this->default_signature_type;\n }",
" function getReplyFromNameType() {\n return $this->default_from_name;\n }",
" function getDefaultPaperSize() {\n return $this->default_paper_size;\n }",
" function getReplyRedirect() {\n return $this->reply_redirect;\n }",
" function getImageAttachmentView() {\n return $this->img_att_view;\n }",
" function editorSpacing() {\n return $this->editor_spacing;\n }",
" function forcePasswdChange() {\n return $this->change_passwd;\n }",
" function getDepartments() {\n // TODO: Cache this in the agent's session as it is unlikely to\n // change while logged in",
" if (!isset($this->departments)) {",
" // Departments the staff is \"allowed\" to access...\n // based on the group they belong to + user's primary dept + user's managed depts.\n $sql='SELECT DISTINCT d.id FROM '.STAFF_TABLE.' s '\n .' LEFT JOIN '.STAFF_DEPT_TABLE.' g ON (s.staff_id=g.staff_id) '\n .' INNER JOIN '.DEPT_TABLE.' d ON (LOCATE(CONCAT(\"/\", s.dept_id, \"/\"), d.path) OR d.manager_id=s.staff_id OR LOCATE(CONCAT(\"/\", g.dept_id, \"/\"), d.path)) '\n .' WHERE s.staff_id='.db_input($this->getId());\n $depts = array();\n if (($res=db_query($sql)) && db_num_rows($res)) {\n while(list($id)=db_fetch_row($res))\n $depts[] = (int) $id;\n }",
" /* ORM method — about 2.0ms slower\n $q = Q::any(array(\n 'path__contains' => '/'.$this->dept_id.'/',\n 'manager_id' => $this->getId(),\n ));\n // Add in extended access\n foreach ($this->dept_access->depts->values_flat('dept_id') as $row) {\n // Skip primary dept\n if ($row[0] == $this->dept_id)\n continue;\n $q->add(new Q(array('path__contains'=>'/'.$row[0].'/')));\n }",
" $dept_ids = Dept::objects()\n ->filter($q)\n ->distinct('id')\n ->values_flat('id');",
" foreach ($dept_ids as $row)\n $depts[] = $row[0];\n */",
" $this->departments = $depts;\n }",
" return $this->departments;\n }",
" function getDepts() {\n return $this->getDepartments();\n }",
" function getManagedDepartments() {",
" return ($depts=Dept::getDepartments(\n array('manager' => $this->getId())\n ))?array_keys($depts):array();\n }",
" function getDeptId() {\n return $this->dept_id;\n }",
" function getDept() {\n return $this->dept;\n }",
" function setDepartmentId($dept_id, $eavesdrop=false) {\n // Grant access to the current department\n $old = $this->dept_id;\n if ($eavesdrop) {\n $da = new StaffDeptAccess(array(\n 'dept_id' => $old,\n 'role_id' => $this->role_id,\n ));\n $da->setAlerts(true);\n $this->dept_access->add($da);\n }",
" // Drop extended access to new department\n $this->dept_id = $dept_id;\n if ($da = $this->dept_access->findFirst(array(\n 'dept_id' => $dept_id))\n ) {\n $this->dept_access->remove($da);\n }",
" $this->save();\n }",
" function usePrimaryRoleOnAssignment() {\n return $this->getExtraAttr('def_assn_role', true);\n }",
" function getLanguage() {\n return (isset($this->lang)) ? $this->lang : false;\n }",
" function getTimezone() {\n if (isset($this->timezone))\n return $this->timezone;\n }",
" function getLocale() {\n //XXX: isset is required here to avoid possible crash when upgrading\n // installation where locale column doesn't exist yet.\n return isset($this->locale) ? $this->locale : 0;\n }",
" function getRoles() {\n if (!isset($this->_roles)) {\n $this->_roles = array($this->dept_id => $this->role);\n foreach($this->dept_access as $da)\n $this->_roles[$da->dept_id] = $da->role;\n }",
" return $this->_roles;\n }",
" function getRole($dept=null, $assigned=false) {",
" if (is_null($dept))\n return $this->role;",
" if (is_numeric($dept))\n $deptId = $dept;\n elseif($dept instanceof Dept)\n $deptId = $dept->getId();\n else\n return null;",
" $roles = $this->getRoles();\n if (isset($roles[$deptId]))\n return $roles[$deptId];",
" // Default to primary role.\n if ($assigned && $this->usePrimaryRoleOnAssignment())\n return $this->role;",
" // Ticket Create & View only access\n $perms = JSONDataEncoder::encode(array(\n Ticket::PERM_CREATE => 1));\n return new Role(array('permissions' => $perms));\n }",
" function hasPerm($perm, $global=true) {\n if ($global)\n return $this->getPermission()->has($perm);\n if ($this->getRole()->hasPerm($perm))\n return true;\n foreach ($this->dept_access as $da)\n if ($da->role->hasPerm($perm))\n return true;\n return false;\n }",
" function canSearchEverything() {\n return $this->hasPerm(SearchBackend::PERM_EVERYTHING);\n }",
" function canManageTickets() {\n return $this->hasPerm(Ticket::PERM_DELETE, false)\n || $this->hasPerm(Ticket::PERM_TRANSFER, false)\n || $this->hasPerm(Ticket::PERM_ASSIGN, false)\n || $this->hasPerm(Ticket::PERM_CLOSE, false);\n }",
" function isManager($dept=null) {\n return (($dept=$dept?:$this->getDept()) && $dept->getManagerId()==$this->getId());\n }",
" function isStaff() {\n return TRUE;\n }",
" function isActive() {\n return $this->isactive;\n }",
" function getStatus() {\n return $this->isActive() ? __('Active') : __('Locked');\n }",
" function isVisible() {\n return $this->isvisible;\n }",
" function onVacation() {\n return $this->onvacation;\n }",
" function isAvailable() {\n return ($this->isActive() && !$this->onVacation());\n }",
" function showAssignedOnly() {\n return $this->assigned_only;\n }",
" function isAccessLimited() {\n return $this->showAssignedOnly();\n }",
" function isAdmin() {\n return $this->isadmin;\n }",
" function isTeamMember($teamId) {\n return ($teamId && in_array($teamId, $this->getTeams()));\n }",
" function canAccessDept($dept) {",
" if (!$dept instanceof Dept)\n return false;",
" return (!$this->isAccessLimited()\n && in_array($dept->getId(), $this->getDepts()));\n }",
" function getTeams() {",
" if (!isset($this->_teams)) {\n $this->_teams = array();\n foreach ($this->teams as $team)\n $this->_teams[] = (int) $team->team_id;\n }",
" return $this->_teams;\n }",
" function getTicketsVisibility($exclude_archived=false) {\n // -- Open and assigned to me\n $assigned = Q::any(array(\n 'staff_id' => $this->getId(),\n ));\n $assigned->add(array('thread__referrals__agent__staff_id' => $this->getId()));\n $childRefAgent = Q::all(new Q(array('child_thread__object_type' => 'C',\n 'child_thread__referrals__agent__staff_id' => $this->getId())));\n $assigned->add($childRefAgent);\n // -- Open and assigned to a team of mine\n if (($teams = array_filter($this->getTeams()))) {\n $assigned->add(array('team_id__in' => $teams));\n $assigned->add(array('thread__referrals__team__team_id__in' => $teams));\n $childRefTeam = Q::all(new Q(array('child_thread__object_type' => 'C',\n 'child_thread__referrals__team__team_id__in' => $teams)));\n $assigned->add($childRefTeam);\n }\n $visibility = Q::any(new Q(array('status__state'=>'open', $assigned)));\n // -- If access is limited to assigned only, return assigned\n if ($this->isAccessLimited())\n return $visibility;\n // -- Routed to a department of mine\n if (($depts=$this->getDepts()) && count($depts)) {\n $in_dept = Q::any(array(\n 'dept_id__in' => $depts,\n 'thread__referrals__dept__id__in' => $depts,\n ));\n if ($exclude_archived) {\n $in_dept = Q::all(array(\n 'status__state__in' => ['open', 'closed'],\n $in_dept,\n ));\n }\n $visibility->add($in_dept);\n $childRefDept = Q::all(new Q(array('child_thread__object_type' => 'C',\n 'child_thread__referrals__dept__id__in' => $depts)));\n $visibility->add($childRefDept);\n }\n return $visibility;\n }",
" function applyVisibility($query, $exclude_archived=false) {\n return $query->filter($this->getTicketsVisibility($exclude_archived));\n }",
" /* stats */\n function resetStats() {\n $this->stats = array();\n }",
" function getTasksStats() {",
" if (!$this->stats['tasks'])\n $this->stats['tasks'] = Task::getStaffStats($this);",
" return $this->stats['tasks'];\n }",
" function getNumAssignedTasks() {\n return ($stats=$this->getTasksStats()) ? $stats['assigned'] : 0;\n }",
" function getNumClosedTasks() {\n return ($stats=$this->getTasksStats()) ? $stats['closed'] : 0;\n }",
" function getExtraAttr($attr=false, $default=null) {\n if (!isset($this->_extra) && isset($this->extra))\n $this->_extra = JsonDataParser::decode($this->extra);",
" return $attr\n ? (isset($this->_extra[$attr]) ? $this->_extra[$attr] : $default)\n : $this->_extra;\n }",
" function setExtraAttr($attr, $value, $commit=true) {\n $this->getExtraAttr();\n $this->_extra[$attr] = $value;\n $this->extra = JsonDataEncoder::encode($this->_extra);",
" if ($commit) {\n $this->save();\n }\n }",
" function getPermission() {\n if (!isset($this->_perm)) {\n $this->_perm = new RolePermission($this->permissions);\n }\n return $this->_perm;\n }",
" function getPermissionInfo() {\n return $this->getPermission()->getInfo();\n }",
" function onLogin($bk) {\n // Update last apparent language preference\n $this->setExtraAttr('browser_lang',\n Internationalization::getCurrentLanguage(),\n false);",
" $this->lastlogin = SqlFunction::NOW();\n $this->save();\n }",
" //Staff profile update...unfortunately we have to separate it from admin update to avoid potential issues\n function updateProfile($vars, &$errors) {\n global $cfg;",
" $vars['firstname']=Format::striptags($vars['firstname']);\n $vars['lastname']=Format::striptags($vars['lastname']);",
" if (isset($this->staff_id) && $this->getId() != $vars['id'])\n $errors['err']=__('Internal error occurred');",
" if(!$vars['firstname'])\n $errors['firstname']=__('First name is required');",
" if(!$vars['lastname'])\n $errors['lastname']=__('Last name is required');",
" if(!$vars['email'] || !Validator::is_valid_email($vars['email']))\n $errors['email']=__('Valid email is required');\n elseif(Email::getIdByEmail($vars['email']))\n $errors['email']=__('Already in-use as system email');\n elseif (($uid=static::getIdByEmail($vars['email']))\n && (!isset($this->staff_id) || $uid!=$this->getId()))\n $errors['email']=__('Email already in use by another agent');",
" if($vars['phone'] && !Validator::is_phone($vars['phone']))\n $errors['phone']=__('Valid phone number is required');",
" if($vars['mobile'] && !Validator::is_phone($vars['mobile']))\n $errors['mobile']=__('Valid phone number is required');",
" if($vars['default_signature_type']=='mine' && !$vars['signature'])\n $errors['default_signature_type'] = __(\"You don't have a signature\");",
" // Update the user's password if requested\n if ($vars['passwd1']) {\n try {\n $this->setPassword($vars['passwd1'], $vars['cpasswd']);\n }\n catch (BadPassword $ex) {\n $errors['passwd1'] = $ex->getMessage();\n }\n catch (PasswordUpdateFailed $ex) {\n // TODO: Add a warning banner or crash the update\n }\n }",
" $vars['onvacation'] = isset($vars['onvacation']) ? 1 : 0;\n $this->firstname = $vars['firstname'];\n $this->lastname = $vars['lastname'];\n $this->email = $vars['email'];\n $this->phone = Format::phone($vars['phone']);\n $this->phone_ext = $vars['phone_ext'];\n $this->mobile = Format::phone($vars['mobile']);\n $this->signature = Format::sanitize($vars['signature']);\n $this->timezone = $vars['timezone'];\n $this->locale = $vars['locale'];\n $this->max_page_size = $vars['max_page_size'];\n $this->auto_refresh_rate = $vars['auto_refresh_rate'];\n $this->default_signature_type = $vars['default_signature_type'];\n $this->default_paper_size = $vars['default_paper_size'];\n $this->lang = $vars['lang'];\n $this->onvacation = $vars['onvacation'];",
" if (isset($vars['avatar_code']))\n $this->setExtraAttr('avatar', $vars['avatar_code']);",
" if ($errors)\n return false;",
" $_SESSION['::lang'] = null;\n TextDomain::configureForUser($this);",
" // Update the config information\n $_config = new Config('staff.'.$this->getId());\n $_config->updateAll(array(\n 'datetime_format' => $vars['datetime_format'],\n 'default_from_name' => $vars['default_from_name'],\n 'thread_view_order' => $vars['thread_view_order'],\n 'default_ticket_queue_id' => $vars['default_ticket_queue_id'],\n 'reply_redirect' => ($vars['reply_redirect'] == 'Queue') ? 'Queue' : 'Ticket',\n 'img_att_view' => ($vars['img_att_view'] == 'inline') ? 'inline' : 'download',\n 'editor_spacing' => ($vars['editor_spacing'] == 'double') ? 'double' : 'single'\n )\n );\n $this->_config = $_config->getInfo();",
" return $this->save();\n }",
" function updateTeams($membership, &$errors) {\n $dropped = array();\n foreach ($this->teams as $TM)\n $dropped[$TM->team_id] = 1;",
" reset($membership);\n while(list(, list($team_id, $alerts)) = each($membership)) {\n $member = $this->teams->findFirst(array('team_id' => $team_id));\n if (!$member) {\n $this->teams->add($member = new TeamMember(array(\n 'team_id' => $team_id,\n )));\n }\n $member->setAlerts($alerts);\n if (!$errors)\n $member->save();\n unset($dropped[$member->team_id]);\n }\n if (!$errors && $dropped) {\n $member = $this->teams\n ->filter(array('team_id__in' => array_keys($dropped)))\n ->delete();\n $this->teams->reset();\n }\n return true;\n }",
" function delete() {\n global $thisstaff;",
" if (!$thisstaff || $this->getId() == $thisstaff->getId())\n return false;",
" if (!parent::delete())\n return false;",
" $type = array('type' => 'deleted');\n Signal::send('object.deleted', $this, $type);",
" // DO SOME HOUSE CLEANING\n //Move remove any ticket assignments...TODO: send alert to Dept. manager?\n Ticket::objects()\n ->filter(array('staff_id' => $this->getId()))\n ->update(array('staff_id' => 0));",
" //Update the poster and clear staff_id on ticket thread table.\n ThreadEntry::objects()\n ->filter(array('staff_id' => $this->getId()))\n ->update(array(\n 'staff_id' => 0,\n 'poster' => $this->getName()->getOriginal(),\n ));",
" // Cleanup Team membership table.\n TeamMember::objects()\n ->filter(array('staff_id'=>$this->getId()))\n ->delete();",
" // Cleanup staff dept access\n StaffDeptAccess::objects()\n ->filter(array('staff_id'=>$this->getId()))\n ->delete();",
" return true;\n }",
" /**** Static functions ********/\n static function lookup($var) {\n if (is_array($var))\n return parent::lookup($var);\n elseif (is_numeric($var))",
" return parent::lookup(array('staff_id' => (int) $var));",
" elseif (Validator::is_email($var))",
" return parent::lookup(array('email' => $var));\n elseif (is_string($var) && Validator::is_username($var))\n return parent::lookup(array('username' => (string) $var));",
" else\n return null;\n }",
" static function getStaffMembers($criteria=array()) {\n global $cfg;",
" $members = static::objects();",
" if (isset($criteria['available'])) {\n $members = $members->filter(array(\n 'onvacation' => 0,\n 'isactive' => 1,\n ));\n }",
" $members = self::nsort($members);",
" $users=array();\n foreach ($members as $M) {\n $users[$M->getId()] = $M->getName();\n }",
" return $users;\n }",
" static function getAvailableStaffMembers() {\n return self::getStaffMembers(array('available'=>true));\n }",
" static function getsortby($path='', $format=null) {\n global $cfg;",
" $format = $format ?: $cfg->getAgentNameFormat();\n switch ($format) {\n case 'last':\n case 'lastfirst':\n case 'legal':\n $fields = array(\"{$path}lastname\", \"{$path}firstname\");\n break;\n default:\n $fields = array(\"${path}firstname\", \"${path}lastname\");\n }",
" return $fields;\n }",
" static function nsort(QuerySet $qs, $path='', $format=null) {\n $fields = self::getsortby($path, $format);\n $qs->order_by($fields);\n return $qs;\n }",
" static function getIdByUsername($username) {\n $row = static::objects()->filter(array('username' => $username))\n ->values_flat('staff_id')->first();\n return $row ? $row[0] : 0;\n }",
" static function getIdByEmail($email) {\n $row = static::objects()->filter(array('email' => $email))\n ->values_flat('staff_id')->first();\n return $row ? $row[0] : 0;\n }",
"\n static function create($vars=false) {\n $staff = new static($vars);\n $staff->created = SqlFunction::NOW();\n return $staff;\n }",
" function cancelResetTokens() {\n // TODO: Drop password-reset tokens from the config table for\n // this user id\n $sql = 'DELETE FROM '.CONFIG_TABLE.' WHERE `namespace`=\"pwreset\"\n AND `value`='.db_input($this->getId());\n db_query($sql, false);\n unset($_SESSION['_staff']['reset-token']);\n }",
" function sendResetEmail($template='pwreset-staff', $log=true) {\n global $ost, $cfg;",
" $content = Page::lookupByType($template);\n $token = Misc::randCode(48); // 290-bits",
" if (!$content)\n return new BaseError(/* @trans */ 'Unable to retrieve password reset email template');",
" $vars = array(\n 'url' => $ost->getConfig()->getBaseUrl(),\n 'token' => $token,\n 'staff' => $this,\n 'recipient' => $this,\n 'reset_link' => sprintf(\n \"%s/scp/pwreset.php?token=%s\",\n $ost->getConfig()->getBaseUrl(),\n $token),\n );\n $vars['link'] = &$vars['reset_link'];",
" if (!($email = $cfg->getAlertEmail()))\n $email = $cfg->getDefaultEmail();",
" $info = array('email' => $email, 'vars' => &$vars, 'log'=>$log);\n Signal::send('auth.pwreset.email', $this, $info);",
" if ($info['log'])\n $ost->logWarning(_S('Agent Password Reset'), sprintf(\n _S('Password reset was attempted for agent: %1$s<br><br>\n Requested-User-Id: %2$s<br>\n Source-Ip: %3$s<br>\n Email-Sent-To: %4$s<br>\n Email-Sent-Via: %5$s'),\n $this->getName(),\n $_POST['userid'],\n $_SERVER['REMOTE_ADDR'],\n $this->getEmail(),\n $email->getEmail()\n ), false);",
" $lang = $this->lang ?: $this->getExtraAttr('browser_lang');\n $msg = $ost->replaceTemplateVariables(array(\n 'subj' => $content->getLocalName($lang),\n 'body' => $content->getLocalBody($lang),\n ), $vars);",
" $_config = new Config('pwreset');\n $_config->set($vars['token'], $this->getId());",
" $email->send($this->getEmail(), Format::striptags($msg['subj']),\n $msg['body']);\n }",
" static function importCsv($stream, $defaults=array(), $callback=false) {\n require_once INCLUDE_DIR . 'class.import.php';",
" $importer = new CsvImporter($stream);\n $imported = 0;\n $fields = array(\n 'firstname' => new TextboxField(array(\n 'label' => __('First Name'),\n )),\n 'lastname' => new TextboxField(array(\n 'label' => __('Last Name'),\n )),\n 'email' => new TextboxField(array(\n 'label' => __('Email Address'),\n 'configuration' => array(\n 'validator' => 'email',\n ),\n )),\n 'username' => new TextboxField(array(\n 'label' => __('Username'),\n 'validators' => function($self, $value) {\n if (!Validator::is_username($value))\n $self->addError('Not a valid username');\n },\n )),\n );\n $form = new SimpleForm($fields);",
" try {\n db_autocommit(false);\n $errors = array();\n $records = $importer->importCsv($form->getFields(), $defaults);\n foreach ($records as $data) {\n if (!isset($data['email']) || !isset($data['username']))\n throw new ImportError('Both `username` and `email` fields are required');",
" if ($agent = self::lookup(array('username' => $data['username']))) {\n // TODO: Update the user\n }\n elseif ($agent = self::create($data, $errors)) {\n if ($callback)\n $callback($agent, $data);\n $agent->save();\n }\n else {\n throw new ImportError(sprintf(__('Unable to import (%s): %s'),\n Format::htmlchars($data['username']),\n print_r(Format::htmlchars($errors), true)\n ));\n }\n $imported++;\n }\n db_autocommit(true);\n }\n catch (Exception $ex) {\n db_rollback();\n return $ex->getMessage();\n }\n return $imported;\n }",
" function save($refetch=false) {\n if ($this->dirty)\n $this->updated = SqlFunction::NOW();\n return parent::save($refetch || $this->dirty);\n }",
" function update($vars, &$errors) {\n $vars['username']=Format::striptags($vars['username']);\n $vars['firstname']=Format::striptags($vars['firstname']);\n $vars['lastname']=Format::striptags($vars['lastname']);",
" if (isset($this->staff_id) && $this->getId() != $vars['id'])\n $errors['err']=__('Internal error occurred');",
" if(!$vars['firstname'])\n $errors['firstname']=__('First name required');\n if(!$vars['lastname'])\n $errors['lastname']=__('Last name required');",
" $error = '';\n if(!$vars['username'] || !Validator::is_username($vars['username'], $error))\n $errors['username']=($error) ? $error : __('Username is required');\n elseif (($uid=static::getIdByUsername($vars['username']))\n && (!isset($this->staff_id) || $uid!=$this->getId()))\n $errors['username']=__('Username already in use');",
" if(!$vars['email'] || !Validator::is_valid_email($vars['email']))\n $errors['email']=__('Valid email is required');\n elseif(Email::getIdByEmail($vars['email']))\n $errors['email']=__('Already in use system email');\n elseif (($uid=static::getIdByEmail($vars['email']))\n && (!isset($this->staff_id) || $uid!=$this->getId()))\n $errors['email']=__('Email already in use by another agent');",
" if($vars['phone'] && !Validator::is_phone($vars['phone']))\n $errors['phone']=__('Valid phone number is required');",
" if($vars['mobile'] && !Validator::is_phone($vars['mobile']))\n $errors['mobile']=__('Valid phone number is required');",
" if(!$vars['dept_id'])\n $errors['dept_id']=__('Department is required');\n if(!$vars['role_id'])\n $errors['role_id']=__('Role for primary department is required');",
" $dept = Dept::lookup($vars['dept_id']);\n if($dept && !$dept->isActive())\n $errors['dept_id'] = sprintf(__('%s selected must be active'), __('Department'));",
" // Ensure we will still have an administrator with access\n if ($vars['isadmin'] !== '1' || $vars['islocked'] === '1') {\n $sql = 'select count(*), max(staff_id) from '.STAFF_TABLE\n .' WHERE isadmin=1 and isactive=1';\n if (($res = db_query($sql))\n && (list($count, $sid) = db_fetch_row($res))) {\n if ($count == 1 && $sid == $uid) {\n $errors['isadmin'] = __(\n 'Cowardly refusing to remove or lock out the only active administrator'\n );\n }\n }\n }",
" // Update the local permissions\n $this->updatePerms($vars['perms'], $errors);",
" //checkboxes\n $vars['isadmin'] = isset($vars['isadmin']) ? 1 : 0;\n $vars['islocked'] = isset($vars['islocked']) ? 0 : 1;\n $vars['isvisible'] = isset($vars['isvisible']) ? 1 : 0;\n $vars['onvacation'] = isset($vars['onvacation']) ? 1 : 0;\n $vars['assigned_only'] = isset($vars['assigned_only']) ? 1 : 0;",
" $this->isadmin = $vars['isadmin'];\n $this->isactive = $vars['islocked'];\n $this->isvisible = $vars['isvisible'];\n $this->onvacation = $vars['onvacation'];\n $this->assigned_only = $vars['assigned_only'];\n $this->role_id = $vars['role_id'];\n $this->username = $vars['username'];\n $this->firstname = $vars['firstname'];\n $this->lastname = $vars['lastname'];\n $this->email = $vars['email'];\n $this->backend = $vars['backend'];\n $this->phone = Format::phone($vars['phone']);\n $this->phone_ext = $vars['phone_ext'];\n $this->mobile = Format::phone($vars['mobile']);\n $this->notes = Format::sanitize($vars['notes']);",
" // Set staff password if exists\n if (!$vars['welcome_email'] && $vars['passwd1']) {\n $this->setPassword($vars['passwd1'], null);\n $this->change_passwd = $vars['change_passwd'] ? 1 : 0;\n }",
" if ($errors)\n return false;",
" if ($this->save()) {\n // Update some things for ::updateAccess to inspect\n $this->setDepartmentId($vars['dept_id']);",
" // Format access update as [array(dept_id, role_id, alerts?)]\n $access = array();\n if (isset($vars['dept_access'])) {\n foreach (@$vars['dept_access'] as $dept_id) {\n $access[] = array($dept_id, $vars['dept_access_role'][$dept_id],\n @$vars['dept_access_alerts'][$dept_id]);\n }\n }\n $this->updateAccess($access, $errors);\n $this->setExtraAttr('def_assn_role',\n isset($vars['assign_use_pri_role']), true);",
" // Format team membership as [array(team_id, alerts?)]\n $teams = array();\n if (isset($vars['teams'])) {\n foreach (@$vars['teams'] as $team_id) {\n $teams[] = array($team_id, @$vars['team_alerts'][$team_id]);\n }\n }\n $this->updateTeams($teams, $errors);",
" if ($vars['welcome_email'])\n $this->sendResetEmail('registration-staff', false);\n return true;\n }",
" if (isset($this->staff_id)) {\n $errors['err']=sprintf(__('Unable to update %s.'), __('this agent'))\n .' '.__('Internal error occurred');\n } else {\n $errors['err']=sprintf(__('Unable to create %s.'), __('this agent'))\n .' '.__('Internal error occurred');\n }\n return false;\n }",
" /**\n * Parameters:\n * $access - (<array($dept_id, $role_id, $alerts)>) a list of the complete,\n * extended access for this agent. Any the agent currently has, which\n * is not listed will be removed.\n * $errors - (<array>) list of error messages from the process, which will\n * be indexed by the dept_id number.\n */\n function updateAccess($access, &$errors) {\n reset($access);\n $dropped = array();\n foreach ($this->dept_access as $DA)\n $dropped[$DA->dept_id] = 1;\n while (list(, list($dept_id, $role_id, $alerts)) = each($access)) {\n unset($dropped[$dept_id]);\n if (!$role_id || !Role::lookup($role_id))\n $errors['dept_access'][$dept_id] = __('Select a valid role');\n if (!$dept_id || !($dept=Dept::lookup($dept_id)))\n $errors['dept_access'][$dept_id] = __('Select a valid department');\n if ($dept_id == $this->getDeptId())\n $errors['dept_access'][$dept_id] = sprintf(__('Agent already has access to %s'), __('this department'));\n $da = $this->dept_access->findFirst(array('dept_id' => $dept_id));\n if (!isset($da)) {\n $da = new StaffDeptAccess(array(\n 'dept_id' => $dept_id, 'role_id' => $role_id\n ));\n $this->dept_access->add($da);\n $type = array('type' => 'edited',\n 'key' => sprintf('%s Department Access Added', $dept->getName()));\n Signal::send('object.edited', $this, $type);\n }\n else {\n $da->role_id = $role_id;\n }\n $da->setAlerts($alerts);\n if (!$errors)\n $da->save();\n }\n if (!$errors && $dropped) {\n $this->dept_access\n ->filter(array('dept_id__in' => array_keys($dropped)))\n ->delete();\n $this->dept_access->reset();\n foreach (array_keys($dropped) as $dept_id) {\n $deptName = Dept::getNameById($dept_id);\n $type = array('type' => 'edited',\n 'key' => sprintf('%s Department Access Removed', $deptName));\n Signal::send('object.edited', $this, $type);\n }\n }\n return !$errors;\n }",
" function updatePerms($vars, &$errors=array()) {\n if (!$vars) {\n $this->permissions = '';\n return;\n }\n $permissions = $this->getPermission();\n foreach ($vars as $k => $val) {\n if (!$permissions->exists($val)) {\n $type = array('type' => 'edited', 'key' => $val);\n Signal::send('object.edited', $this, $type);\n }\n }",
" foreach (RolePermission::allPermissions() as $g => $perms) {\n foreach ($perms as $k => $v) {\n if (!in_array($k, $vars) && $permissions->exists($k)) {\n $type = array('type' => 'edited', 'key' => $k);\n Signal::send('object.edited', $this, $type);\n }\n $permissions->set($k, in_array($k, $vars) ? 1 : 0);\n }\n }\n $this->permissions = $permissions->toJson();\n return true;\n }",
" static function export($criteria=null, $filename='') {\n include_once(INCLUDE_DIR.'class.error.php');",
" $agents = Staff::objects();\n // Sort based on name formating\n $agents = self::nsort($agents);\n Export::agents($agents, $filename);\n }",
"}",
"interface RestrictedAccess {\n function checkStaffPerm($staff);\n}",
"class StaffDeptAccess extends VerySimpleModel {\n static $meta = array(\n 'table' => STAFF_DEPT_TABLE,\n 'pk' => array('staff_id', 'dept_id'),\n 'select_related' => array('dept', 'role'),\n 'joins' => array(\n 'dept' => array(\n 'constraint' => array('dept_id' => 'Dept.id'),\n ),\n 'staff' => array(\n 'constraint' => array('staff_id' => 'Staff.staff_id'),\n ),\n 'role' => array(\n 'constraint' => array('role_id' => 'Role.id'),\n ),\n ),\n );",
" const FLAG_ALERTS = 0x0001;",
" function isAlertsEnabled() {\n return $this->flags & self::FLAG_ALERTS != 0;\n }",
" function setFlag($flag, $value) {\n if ($value)\n $this->flags |= $flag;\n else\n $this->flags &= ~$flag;\n }",
" function setAlerts($value) {\n $this->setFlag(self::FLAG_ALERTS, $value);\n }\n}",
"/**\n * This form is used to administratively change the password. The\n * ChangePasswordForm is used for an agent to change their own password.\n */\nclass PasswordResetForm\nextends AbstractForm {\n function buildFields() {\n return array(\n 'welcome_email' => new BooleanField(array(\n 'default' => true,\n 'configuration' => array(\n 'desc' => __('Send the agent a password reset email'),\n ),\n )),\n 'passwd1' => new PasswordField(array(\n 'placeholder' => __('New Password'),\n 'required' => true,\n 'configuration' => array(\n 'classes' => 'span12',\n ),\n 'visibility' => new VisibilityConstraint(\n new Q(array('welcome_email' => false)),\n VisibilityConstraint::HIDDEN\n ),\n )),\n 'passwd2' => new PasswordField(array(\n 'placeholder' => __('Confirm Password'),\n 'required' => true,\n 'configuration' => array(\n 'classes' => 'span12',\n ),\n 'visibility' => new VisibilityConstraint(\n new Q(array('welcome_email' => false)),\n VisibilityConstraint::HIDDEN\n ),\n )),\n 'change_passwd' => new BooleanField(array(\n 'default' => true,\n 'configuration' => array(\n 'desc' => __('Require password change at next login'),\n 'classes' => 'form footer',\n ),\n 'visibility' => new VisibilityConstraint(\n new Q(array('welcome_email' => false)),\n VisibilityConstraint::HIDDEN\n ),\n )),\n );\n }",
" function validate($clean) {\n if ($clean['passwd1'] != $clean['passwd2'])\n $this->getField('passwd1')->addError(__('Passwords do not match'));\n }\n}",
"class PasswordChangeForm\nextends AbstractForm {\n function buildFields() {\n $fields = array(\n 'current' => new PasswordField(array(\n 'placeholder' => __('Current Password'),\n 'required' => true,\n 'configuration' => array(\n 'autofocus' => true,\n ),\n )),\n 'passwd1' => new PasswordField(array(\n 'label' => __('Enter a new password'),\n 'placeholder' => __('New Password'),\n 'required' => true,\n )),\n 'passwd2' => new PasswordField(array(\n 'placeholder' => __('Confirm Password'),\n 'required' => true,\n )),\n );",
" // When using the password reset system, the current password is not\n // required for agents.\n if (isset($_SESSION['_staff']['reset-token'])) {\n unset($fields['current']);\n $fields['passwd1']->set('configuration', array('autofocus' => true));\n }\n else {\n $fields['passwd1']->set('layout',\n new GridFluidCell(12, array('style' => 'padding-top: 20px'))\n );\n }\n return $fields;\n }",
" function getInstructions() {\n return __('Confirm your current password and enter a new password to continue');\n }",
" function validate($clean) {\n if ($clean['passwd1'] != $clean['passwd2'])\n $this->getField('passwd1')->addError(__('Passwords do not match'));\n }\n}",
"class ResetAgentPermissionsForm\nextends AbstractForm {\n function buildFields() {\n $permissions = array();\n foreach (RolePermission::allPermissions() as $g => $perms) {\n foreach ($perms as $k => $v) {\n if (!$v['primary'])\n continue;\n $permissions[$g][$k] = \"{$v['title']} — {$v['desc']}\";\n }\n }\n return array(\n 'clone' => new ChoiceField(array(\n 'default' => 0,\n 'choices' =>\n array(0 => '— '.__('Clone an existing agent').' —')\n + Staff::getStaffMembers(),\n 'configuration' => array(\n 'classes' => 'span12',\n ),\n )),\n 'perms' => new ChoiceField(array(\n 'choices' => $permissions,\n 'widget' => 'TabbedBoxChoicesWidget',\n 'configuration' => array(\n 'multiple' => true,\n ),\n )),\n );\n }",
" function getClean($validate = true) {\n $clean = parent::getClean();\n // Index permissions as ['ticket.edit' => 1]\n $clean['perms'] = array_keys($clean['perms']);\n return $clean;\n }",
" function render($staff=true, $title=false, $options=array()) {\n return parent::render($staff, $title, $options + array('template' => 'dynamic-form-simple.tmpl.php'));\n }\n}",
"class ChangeDepartmentForm\nextends AbstractForm {\n function buildFields() {\n return array(\n 'dept_id' => new ChoiceField(array(\n 'default' => 0,\n 'required' => true,\n 'label' => __('Primary Department'),\n 'choices' =>\n array(0 => '— '.__('Primary Department').' —')\n + Dept::getDepartments(),\n 'configuration' => array(\n 'classes' => 'span12',\n ),\n )),\n 'role_id' => new ChoiceField(array(\n 'default' => 0,\n 'required' => true,\n 'label' => __('Primary Role'),\n 'choices' =>\n array(0 => '— '.__('Corresponding Role').' —')\n + Role::getRoles(),\n 'configuration' => array(\n 'classes' => 'span12',\n ),\n )),\n 'eavesdrop' => new BooleanField(array(\n 'configuration' => array(\n 'desc' => __('Maintain access to current primary department'),\n 'classes' => 'form footer',\n ),\n )),\n // alerts?\n );\n }",
" function getInstructions() {\n return __('Change the primary department and primary role of the selected agents');\n }",
" function getClean($validate = true) {\n $clean = parent::getClean();\n $clean['eavesdrop'] = $clean['eavesdrop'] ? 1 : 0;\n return $clean;\n }",
" function render($staff=true, $title=false, $options=array()) {\n return parent::render($staff, $title, $options + array('template' => 'dynamic-form-simple.tmpl.php'));\n }\n}",
"class StaffQuickAddForm\nextends AbstractForm {\n static $layout = 'GridFormLayout';",
" function buildFields() {\n global $cfg;",
" return array(\n 'firstname' => new TextboxField(array(\n 'required' => true,\n 'configuration' => array(\n 'placeholder' => __(\"First Name\"),\n 'autofocus' => true,\n ),\n 'layout' => new GridFluidCell(6),\n )),\n 'lastname' => new TextboxField(array(\n 'required' => true,\n 'configuration' => array(\n 'placeholder' => __(\"Last Name\"),\n ),\n 'layout' => new GridFluidCell(6),\n )),\n 'email' => new TextboxField(array(\n 'required' => true,\n 'configuration' => array(\n 'validator' => 'email',\n 'placeholder' => __('Email Address — e.g. me@mycompany.com'),\n 'length' => 128,\n 'autocomplete' => 'email',\n ),\n )),\n 'dept_id' => new ChoiceField(array(\n 'label' => __('Department'),\n 'required' => true,\n 'choices' => Dept::getDepartments(),\n 'default' => $cfg->getDefaultDeptId(),\n 'layout' => new GridFluidCell(6),\n )),\n 'role_id' => new ChoiceField(array(\n 'label' => __('Primary Role'),\n 'required' => true,\n 'choices' =>\n array(0 => __('Select Role'))\n + Role::getRoles(),\n 'layout' => new GridFluidCell(6),\n )),\n 'isadmin' => new BooleanField(array(\n 'label' => __('Account Type'),\n 'configuration' => array(\n 'desc' => __('Agent has access to the admin panel'),\n ),\n 'layout' => new GridFluidCell(6),\n )),\n 'welcome_email' => new BooleanField(array(\n 'configuration' => array(\n 'desc' => __('Send a welcome email with login information'),\n ),\n 'default' => true,\n 'layout' => new GridFluidCell(12, array('style' => 'padding-top: 50px')),\n )),\n 'passwd1' => new PasswordField(array(\n 'required' => true,\n 'configuration' => array(\n 'placeholder' => __(\"Temporary Password\"),\n 'autocomplete' => 'new-password',\n ),\n 'visibility' => new VisibilityConstraint(\n new Q(array('welcome_email' => false))\n ),\n 'layout' => new GridFluidCell(6),\n )),\n 'passwd2' => new PasswordField(array(\n 'required' => true,\n 'configuration' => array(\n 'placeholder' => __(\"Confirm Password\"),\n 'autocomplete' => 'new-password',\n ),\n 'visibility' => new VisibilityConstraint(\n new Q(array('welcome_email' => false))\n ),\n 'layout' => new GridFluidCell(6),\n )),\n // TODO: Add role_id drop-down\n );\n }",
" function getClean($validate = true) {\n $clean = parent::getClean();\n list($clean['username'],) = preg_split('/[^\\w.-]/u', $clean['email'], 2);\n if (mb_strlen($clean['username']) < 3 || Staff::lookup($clean['username']))\n $clean['username'] = mb_strtolower($clean['firstname']);",
"\n // Inherit default dept's role as primary role\n $clean['assign_use_pri_role'] = true;",
" // Default permissions\n $clean['perms'] = array(\n User::PERM_CREATE,\n User::PERM_EDIT,\n User::PERM_DELETE,\n User::PERM_MANAGE,\n User::PERM_DIRECTORY,\n Organization::PERM_CREATE,\n Organization::PERM_EDIT,\n Organization::PERM_DELETE,\n FAQ::PERM_MANAGE,\n );\n return $clean;\n }\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [870, 1348, 224, 19, 76], "buggy_code_start_loc": [865, 1344, 223, 18, 42], "filenames": ["include/class.staff.php", "include/class.user.php", "include/class.validator.php", "pwreset.php", "scp/pwreset.php"], "fixing_code_end_loc": [870, 1348, 232, 21, 79], "fixing_code_start_loc": [865, 1344, 223, 18, 42], "message": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "2ACCEE58-8958-4EBE-BF9E-37DD119DBD44", "versionEndExcluding": "1.14.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "22F26EC6-59B4-4CCA-9A7E-FD8DD0D0ECE9", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.15", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality."}, {"lang": "es", "value": "Una inyecci\u00f3n SQL en el proceso de inicio de sesi\u00f3n y restablecimiento de contrase\u00f1a de osTicket versiones anteriores a 1.14.8 y 1.15.4, permite a atacantes acceder a la funcionalidad osTicket administration profile"}], "evaluatorComment": null, "id": "CVE-2021-42235", "lastModified": "2022-05-13T17:13:06.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-04T17:15:08.087", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}, "type": "CWE-89"}
| 259
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*********************************************************************\n class.user.php",
" External end-user identification for osTicket",
" Peter Rotich <peter@osticket.com>\n Jared Hancock <jared@osticket.com>\n Copyright (c) 2006-2013 osTicket\n http://www.osticket.com",
" Released under the GNU General Public License WITHOUT ANY WARRANTY.\n See LICENSE.TXT for details.",
" vim: expandtab sw=4 ts=4 sts=4:\n**********************************************************************/\nrequire_once INCLUDE_DIR . 'class.orm.php';\nrequire_once INCLUDE_DIR . 'class.util.php';\nrequire_once INCLUDE_DIR . 'class.variable.php';\nrequire_once INCLUDE_DIR . 'class.search.php';\nrequire_once INCLUDE_DIR . 'class.organization.php';",
"class UserEmailModel extends VerySimpleModel {\n static $meta = array(\n 'table' => USER_EMAIL_TABLE,\n 'pk' => array('id'),\n 'joins' => array(\n 'user' => array(\n 'constraint' => array('user_id' => 'UserModel.id')\n )\n )\n );",
" function __toString() {\n return (string) $this->address;\n }",
" static function getIdByEmail($email) {\n $row = UserEmailModel::objects()\n ->filter(array('address'=>$email))\n ->values_flat('user_id')\n ->first();",
" return $row ? $row[0] : 0;\n }\n}",
"class UserModel extends VerySimpleModel {\n static $meta = array(\n 'table' => USER_TABLE,\n 'pk' => array('id'),\n 'select_related' => array('default_email', 'org', 'account'),\n 'joins' => array(\n 'emails' => array(\n 'reverse' => 'UserEmailModel.user',\n ),\n 'tickets' => array(\n 'null' => true,\n 'reverse' => 'Ticket.user',\n ),\n 'account' => array(\n 'list' => false,\n 'null' => true,\n 'reverse' => 'ClientAccount.user',\n ),\n 'org' => array(\n 'null' => true,\n 'constraint' => array('org_id' => 'Organization.id')\n ),\n 'default_email' => array(\n 'null' => true,\n 'constraint' => array('default_email_id' => 'UserEmailModel.id')\n ),\n 'cdata' => array(\n 'constraint' => array('id' => 'UserCdata.user_id'),\n 'null' => true,\n ),\n 'entries' => array(\n 'constraint' => array(\n 'id' => 'DynamicFormEntry.object_id',\n \"'U'\" => 'DynamicFormEntry.object_type',\n ),\n 'list' => true,\n ),\n )\n );",
" const PRIMARY_ORG_CONTACT = 0x0001;",
" const PERM_CREATE = 'user.create';\n const PERM_EDIT = 'user.edit';\n const PERM_DELETE = 'user.delete';\n const PERM_MANAGE = 'user.manage';\n const PERM_DIRECTORY = 'user.dir';",
" static protected $perms = array(\n self::PERM_CREATE => array(\n 'title' => /* @trans */ 'Create',\n 'desc' => /* @trans */ 'Ability to add new users',\n 'primary' => true,\n ),\n self::PERM_EDIT => array(\n 'title' => /* @trans */ 'Edit',\n 'desc' => /* @trans */ 'Ability to manage user information',\n 'primary' => true,\n ),\n self::PERM_DELETE => array(\n 'title' => /* @trans */ 'Delete',\n 'desc' => /* @trans */ 'Ability to delete users',\n 'primary' => true,\n ),\n self::PERM_MANAGE => array(\n 'title' => /* @trans */ 'Manage Account',\n 'desc' => /* @trans */ 'Ability to manage active user accounts',\n 'primary' => true,\n ),\n self::PERM_DIRECTORY => array(\n 'title' => /* @trans */ 'User Directory',\n 'desc' => /* @trans */ 'Ability to access the user directory',\n 'primary' => true,\n ),\n );",
" function getId() {\n return $this->id;\n }",
" function getDefaultEmailAddress() {\n return $this->getDefaultEmail()->address;\n }",
" function getDefaultEmail() {\n return $this->default_email;\n }",
" function hasAccount() {\n return !is_null($this->account);\n }\n function getAccount() {\n return $this->account;\n }",
" function getOrgId() {\n return $this->get('org_id');\n }",
" function getOrganization() {\n return $this->org;\n }",
" function setOrganization($org, $save=true) {",
" $this->set('org', $org);",
" if ($save)\n $this->save();",
" return true;\n }",
" public function setFlag($flag, $val) {\n if ($val)\n $this->status |= $flag;\n else\n $this->status &= ~$flag;\n }",
" protected function hasStatus($flag) {\n return $this->get('status') & $flag !== 0;\n }",
" protected function clearStatus($flag) {\n return $this->set('status', $this->get('status') & ~$flag);\n }",
" protected function setStatus($flag) {\n return $this->set('status', $this->get('status') | $flag);\n }",
" function isPrimaryContact() {\n return $this->hasStatus(User::PRIMARY_ORG_CONTACT);\n }",
" function setPrimaryContact($flag) {\n if ($flag)\n $this->setStatus(User::PRIMARY_ORG_CONTACT);\n else\n $this->clearStatus(User::PRIMARY_ORG_CONTACT);\n }",
" static function getPermissions() {\n return self::$perms;\n }\n}\ninclude_once INCLUDE_DIR.'class.role.php';\nRolePermission::register(/* @trans */ 'Users', UserModel::getPermissions());",
"class UserCdata extends VerySimpleModel {\n static $meta = array(\n 'table' => USER_CDATA_TABLE,\n 'pk' => array('user_id'),\n 'joins' => array(\n 'user' => array(\n 'constraint' => array('user_id' => 'UserModel.id'),\n ),\n ),\n );\n}",
"class User extends UserModel\nimplements TemplateVariable, Searchable {",
" var $_email;\n var $_entries;\n var $_forms;\n var $_queue;",
"",
" static function fromVars($vars, $create=true, $update=false) {\n // Try and lookup by email address\n $user = static::lookupByEmail($vars['email']);\n if (!$user && $create) {\n $name = $vars['name'];\n if (is_array($name))\n $name = implode(', ', $name);\n elseif (!$name)\n list($name) = explode('@', $vars['email'], 2);",
" $user = new User(array(\n 'name' => Format::htmldecode(Format::sanitize($name, false)),\n 'created' => new SqlFunction('NOW'),\n 'updated' => new SqlFunction('NOW'),\n //XXX: Do plain create once the cause\n // of the detached emails is fixed.\n 'default_email' => UserEmail::ensure($vars['email'])\n ));\n // Is there an organization registered for this domain\n list($mailbox, $domain) = explode('@', $vars['email'], 2);\n if (isset($vars['org_id']))\n $user->set('org_id', $vars['org_id']);\n elseif ($org = Organization::forDomain($domain))\n $user->setOrganization($org, false);",
" try {\n $user->save(true);\n $user->emails->add($user->default_email);\n // Attach initial custom fields\n $user->addDynamicData($vars);\n }\n catch (OrmException $e) {\n return null;\n }\n $type = array('type' => 'created');\n Signal::send('object.created', $user, $type);\n Signal::send('user.created', $user);\n }\n elseif ($update) {\n $errors = array();\n $user->updateInfo($vars, $errors, true);\n }",
" return $user;\n }",
" static function fromForm($form, $create=true) {\n global $thisstaff;",
" if(!$form) return null;",
" //Validate the form\n $valid = true;\n $filter = function($f) use ($thisstaff) {\n return !isset($thisstaff) || $f->isRequiredForStaff() || $f->isVisibleToStaff();\n };\n if (!$form->isValid($filter))\n $valid = false;",
" //Make sure the email is not in-use\n if (($field=$form->getField('email'))\n && $field->getClean()\n && User::lookup(array('emails__address'=>$field->getClean()))) {\n $field->addError(__('Email is assigned to another user'));\n $valid = false;\n }",
" return $valid ? self::fromVars($form->getClean(), $create) : null;\n }",
" function getEmail() {",
" if (!isset($this->_email))\n $this->_email = new EmailAddress(sprintf('\"%s\" <%s>',\n addcslashes($this->getName(), '\"'),\n $this->default_email->address));",
" return $this->_email;\n }",
" function getAvatar($size=null) {\n global $cfg;\n $source = $cfg->getClientAvatarSource();\n $avatar = $source->getAvatar($this);\n if (isset($size))\n $avatar->setSize($size);\n return $avatar;\n }",
" function getFullName() {\n return $this->name;\n }",
" function getPhoneNumber() {\n foreach ($this->getDynamicData() as $e)\n if ($a = $e->getAnswer('phone'))\n return $a;\n }",
" function getName() {\n if (!$this->name)\n list($name) = explode('@', $this->getDefaultEmailAddress(), 2);\n else\n $name = $this->name;\n return new UsersName($name);\n }",
" function getUpdateDate() {\n return $this->updated;\n }",
" function getCreateDate() {\n return $this->created;\n }",
" function getTimezone() {\n global $cfg;",
" if (($acct = $this->getAccount()) && ($tz = $acct->getTimezone())) {\n return $tz;\n }\n return $cfg->getDefaultTimezone();\n }",
" function addForm($form, $sort=1, $data=null) {\n $entry = $form->instanciate($sort, $data);\n $entry->set('object_type', 'U');\n $entry->set('object_id', $this->getId());\n $entry->save();\n return $entry;\n }",
" function getLanguage($flags=false) {\n if ($acct = $this->getAccount())\n return $acct->getLanguage($flags);\n }",
" function to_json() {",
" $info = array(\n 'id' => $this->getId(),\n 'name' => Format::htmlchars($this->getName()),\n 'email' => (string) $this->getEmail(),\n 'phone' => (string) $this->getPhoneNumber());",
" return Format::json_encode($info);\n }",
" function __toString() {\n return $this->asVar();\n }",
" function asVar() {\n return (string) $this->getName();\n }",
" function getVar($tag) {\n $tag = mb_strtolower($tag);\n foreach ($this->getDynamicData() as $e)\n if ($a = $e->getAnswer($tag))\n return $a;\n }",
" static function getVarScope() {\n $base = array(\n 'email' => array(\n 'class' => 'EmailAddress', 'desc' => __('Default email address')\n ),\n 'name' => array(\n 'class' => 'PersonsName', 'desc' => 'User name, default format'\n ),\n 'organization' => array('class' => 'Organization', 'desc' => __('Organization')),\n );\n $extra = VariableReplacer::compileFormScope(UserForm::getInstance());\n return $base + $extra;\n }",
" static function getSearchableFields() {\n $base = array();\n $uform = UserForm::getUserForm();\n $base = array();\n foreach ($uform->getFields() as $F) {\n $fname = $F->get('name') ?: ('field_'.$F->get('id'));\n # XXX: email in the model corresponds to `emails__address` ORM path\n if ($fname == 'email')\n $fname = 'emails__address';\n if (!$F->hasData() || $F->isPresentationOnly())\n continue;\n if (!$F->isStorable())\n $base[$fname] = $F;\n else\n $base[\"cdata__{$fname}\"] = $F;\n }\n return $base;\n }",
" static function supportsCustomData() {\n return true;\n }",
" function addDynamicData($data) {\n return $this->addForm(UserForm::objects()->one(), 1, $data);\n }",
" function getDynamicData($create=true) {\n if (!isset($this->_entries)) {\n $this->_entries = DynamicFormEntry::forObject($this->id, 'U')->all();\n if (!$this->_entries && $create) {\n $g = UserForm::getNewInstance();\n $g->setClientId($this->id);\n $g->save();\n $this->_entries[] = $g;\n }\n }",
" return $this->_entries ?: array();\n }",
" function getFilterData() {\n $vars = array();\n foreach ($this->getDynamicData() as $entry) {\n $vars += $entry->getFilterData();",
" // Add in special `name` and `email` fields\n if ($entry->getDynamicForm()->get('type') != 'U')\n continue;",
" foreach (array('name', 'email') as $name) {\n if ($f = $entry->getField($name))\n $vars['field.'.$f->get('id')] =\n $name == 'name' ? $this->getName() : $this->getEmail();\n }\n }",
" return $vars;\n }",
" function getForms($data=null, $cb=null) {",
" if (!isset($this->_forms)) {\n $this->_forms = array();\n $cb = $cb ?: function ($f) use($data) { return ($data); };\n foreach ($this->getDynamicData() as $entry) {\n $entry->addMissingFields();\n if(($form = $entry->getDynamicForm())\n && $form->get('type') == 'U' ) {",
" foreach ($entry->getFields() as $f) {\n if ($f->get('name') == 'name' && !$cb($f))\n $f->value = $this->getFullName();\n elseif ($f->get('name') == 'email' && !$cb($f))\n $f->value = $this->getEmail();\n }\n }",
" $this->_forms[] = $entry;\n }\n }",
" return $this->_forms;\n }",
" function getAccountStatus() {",
" if (!($account=$this->getAccount()))\n return __('Guest');",
" return (string) $account->getStatus();\n }",
" function canSeeOrgTickets() {\n return $this->org && (\n $this->org->shareWithEverybody()\n || ($this->isPrimaryContact() && $this->org->shareWithPrimaryContacts()));\n }",
" function register($vars, &$errors) {",
" // user already registered?\n if ($this->getAccount())\n return true;",
" return UserAccount::register($this, $vars, $errors);\n }",
" static function importCsv($stream, $defaults=array()) {\n require_once INCLUDE_DIR . 'class.import.php';",
" $importer = new CsvImporter($stream);\n $imported = 0;\n try {\n db_autocommit(false);\n $records = $importer->importCsv(UserForm::getUserForm()->getFields(), $defaults);\n foreach ($records as $data) {\n if (!Validator::is_email($data['email']) || empty($data['name']))\n throw new ImportError('Both `name` and `email` fields are required');\n if (!($user = static::fromVars($data, true, true)))\n throw new ImportError(sprintf(__('Unable to import user: %s'),\n print_r(Format::htmlchars($data), true)));\n $imported++;\n }\n db_autocommit(true);\n }\n catch (Exception $ex) {\n db_rollback();\n return $ex->getMessage();\n }\n return $imported;\n }",
" function importFromPost($stream, $extra=array()) {\n if (!is_array($stream))\n $stream = sprintf('name, email%s %s',PHP_EOL, $stream);",
" return User::importCsv($stream, $extra);\n }",
" function updateInfo($vars, &$errors, $staff=false) {\n $isEditable = function ($f) use($staff) {\n return ($staff ? $f->isEditableToStaff() :\n $f->isEditableToUsers());\n };\n $valid = true;\n $forms = $this->getForms($vars, $isEditable);\n foreach ($forms as $entry) {\n $entry->setSource($vars);\n if ($staff && !$entry->isValidForStaff(true))\n $valid = false;\n elseif (!$staff && !$entry->isValidForClient(true))\n $valid = false;\n elseif ($entry->getDynamicForm()->get('type') == 'U'\n && ($f=$entry->getField('email'))\n && $isEditable($f)\n && $f->getClean()\n && ($u=User::lookup(array('emails__address'=>$f->getClean())))\n && $u->id != $this->getId()) {\n $valid = false;\n $f->addError(__('Email is assigned to another user'));\n }",
" if (!$valid)\n $errors = array_merge($errors, $entry->errors());\n }",
"\n if (!$valid)\n return false;",
" // Save the entries\n foreach ($forms as $entry) {\n $fields = $entry->getFields();\n foreach ($fields as $field) {\n $changes = $field->getChanges();\n if ((is_array($changes) && $changes[0]) || $changes && !is_array($changes)) {\n $type = array('type' => 'edited', 'key' => $field->getLabel());\n Signal::send('object.edited', $this, $type);\n }\n }",
" if ($entry->getDynamicForm()->get('type') == 'U') {\n // Name field\n if (($name = $entry->getField('name')) && $isEditable($name) ) {\n $name = $name->getClean();\n if (is_array($name))\n $name = implode(', ', $name);\n if ($this->name != $name) {\n $type = array('type' => 'edited', 'key' => 'Name');\n Signal::send('object.edited', $this, $type);\n }\n $this->name = $name;\n }",
" // Email address field\n if (($email = $entry->getField('email'))\n && $isEditable($email)) {\n if ($this->default_email->address != $email->getClean()) {\n $type = array('type' => 'edited', 'key' => 'Email');\n Signal::send('object.edited', $this, $type);\n }\n $this->default_email->address = $email->getClean();\n $this->default_email->save();\n }\n }",
" // DynamicFormEntry::saveAnswers returns the number of answers updated\n if ($entry->saveAnswers($isEditable)) {\n $this->updated = SqlFunction::NOW();\n }\n }",
" return $this->save();\n }",
"\n function save($refetch=false) {\n // Drop commas and reorganize the name without them\n $parts = array_map('trim', explode(',', $this->name));\n switch (count($parts)) {\n case 2:\n // Assume last, first --or-- last suff., first\n $this->name = $parts[1].' '.$parts[0];\n // XXX: Consider last, first suff.\n break;\n case 3:\n // Assume last, first, suffix, write 'first last suffix'\n $this->name = $parts[1].' '.$parts[0].' '.$parts[2];\n break;\n }",
" // Handle email addresses -- use the box name\n if (Validator::is_email($this->name)) {\n list($box, $domain) = explode('@', $this->name, 2);\n if (strpos($box, '.') !== false)\n $this->name = str_replace('.', ' ', $box);\n else\n $this->name = $box;\n $this->name = mb_convert_case($this->name, MB_CASE_TITLE);\n }",
" if (count($this->dirty)) //XXX: doesn't work??\n $this->set('updated', new SqlFunction('NOW'));\n return parent::save($refetch);\n }",
" function delete() {\n // Refuse to delete a user with tickets\n if ($this->tickets->count())\n return false;",
" // Delete account record (if any)\n if ($this->getAccount())\n $this->getAccount()->delete();",
" // Delete emails.\n $this->emails->expunge();",
" // Drop dynamic data\n foreach ($this->getDynamicData() as $entry) {\n $entry->delete();\n }",
" $type = array('type' => 'deleted');\n Signal::send('object.deleted', $this, $type);",
" // Delete user\n return parent::delete();\n }",
" function deleteAllTickets() {\n $status_id = TicketStatus::lookup(array('state' => 'deleted'));\n foreach($this->tickets as $ticket) {\n if (!$T = Ticket::lookup($ticket->getId()))\n continue;\n if (!$T->setStatus($status_id))\n return false;\n }\n $this->tickets->reset();\n return true;\n }",
" static function lookupByEmail($email) {\n return static::lookup(array('emails__address'=>$email));\n }",
" static function getNameById($id) {\n if ($user = static::lookup($id))\n return $user->getName();\n }",
" static function getLink($id) {\n global $thisstaff;",
" if (!$id || !$thisstaff)\n return false;",
" return ROOT_PATH . sprintf('scp/users.php?id=%s', $id);\n }",
" function getTicketsQueue($collabs=true) {\n global $thisstaff;",
" if (!$this->_queue) {\n $email = $this->getDefaultEmailAddress();\n $filter = [\n ['user__id', 'equal', $this->getId()],\n ];\n if ($collabs)\n $filter = [\n ['user__emails__address', 'equal', $email],\n ['thread__collaborators__user__emails__address', 'equal', $email],\n ];\n $this->_queue = new AdhocSearch(array(\n 'id' => 'adhoc,uid'.$this->getId(),\n 'root' => 'T',\n 'staff_id' => $thisstaff->getId(),\n 'title' => $this->getName()\n ));\n $this->_queue->config = $filter;\n }",
" return $this->_queue;\n }\n}",
"class EmailAddress\nimplements TemplateVariable {\n var $email;\n var $address;\n protected $_info;",
" function __construct($address) {\n $this->_info = self::parse($address);\n $this->email = sprintf('%s@%s',\n $this->getMailbox(),\n $this->getDomain());",
" if ($this->getName())\n $this->address = sprintf('\"%s\" <%s>',\n $this->getName(),\n $this->email);\n }",
" function __toString() {\n return (string) $this->email;\n }",
" function getVar($what) {",
" if (!$this->_info)\n return '';",
" switch ($what) {\n case 'host':\n case 'domain':\n return $this->_info->host;\n case 'personal':\n return trim($this->_info->personal, '\"');\n case 'mailbox':\n return $this->_info->mailbox;\n }\n }",
" function getAddress() {\n return $this->address ?: $this->email;\n }",
" function getHost() {\n return $this->getVar('host');\n }",
" function getDomain() {\n return $this->getHost();\n }",
" function getName() {\n return $this->getVar('personal');\n }",
" function getMailbox() {\n return $this->getVar('mailbox');\n }",
" // Parse and email adddress (RFC822) into it's parts.\n // @address - one address is expected\n static function parse($address) {\n require_once PEAR_DIR . 'Mail/RFC822.php';\n require_once PEAR_DIR . 'PEAR.php';\n if (($parts = Mail_RFC822::parseAddressList($address))\n && !PEAR::isError($parts))\n return current($parts);\n }",
" static function getVarScope() {\n return array(\n 'domain' => __('Domain'),\n 'mailbox' => __('Mailbox'),\n 'personal' => __('Personal name'),\n );\n }\n}",
"class PersonsName\nimplements TemplateVariable {\n var $format;\n var $parts;\n var $name;",
" static $formats = array(\n 'first' => array( /*@trans*/ \"First\", 'getFirst'),\n 'last' => array( /*@trans*/ \"Last\", 'getLast'),\n 'full' => array( /*@trans*/ \"First Last\", 'getFull'),\n 'legal' => array( /*@trans*/ \"First M. Last\", 'getLegal'),\n 'lastfirst' => array( /*@trans*/ \"Last, First\", 'getLastFirst'),\n 'formal' => array( /*@trans*/ \"Mr. Last\", 'getFormal'),\n 'short' => array( /*@trans*/ \"First L.\", 'getShort'),\n 'shortformal' => array(/*@trans*/ \"F. Last\", 'getShortFormal'),\n 'complete' => array( /*@trans*/ \"Mr. First M. Last Sr.\", 'getComplete'),\n 'original' => array( /*@trans*/ '-- As Entered --', 'getOriginal'),\n );",
" function __construct($name, $format=null) {\n global $cfg;",
" if ($format && isset(static::$formats[$format]))\n $this->format = $format;\n else\n $this->format = 'original';",
" if (!is_array($name)) {\n $this->parts = static::splitName($name);\n $this->name = $name;\n }\n else {\n $this->parts = $name;\n $this->name = implode(' ', $name);\n }\n }",
" function getFirst() {\n return $this->parts['first'];\n }",
" function getLast() {\n return $this->parts['last'];\n }",
" function getMiddle() {\n return $this->parts['middle'];\n }",
" function getMiddleInitial() {\n return mb_substr($this->parts['middle'],0,1).'.';\n }",
" function getFormal() {\n return trim($this->parts['salutation'].' '.$this->parts['last']);\n }",
" function getFull() {\n return trim($this->parts['first'].' '.$this->parts['last']);\n }",
" function getLegal() {\n $parts = array(\n $this->parts['first'],\n mb_substr($this->parts['middle'],0,1),\n $this->parts['last'],\n );\n if ($parts[1]) $parts[1] .= '.';\n return implode(' ', array_filter($parts));\n }",
" function getComplete() {\n $parts = array(\n $this->parts['salutation'],\n $this->parts['first'],\n mb_substr($this->parts['middle'],0,1),\n $this->parts['last'],\n $this->parts['suffix']\n );\n if ($parts[2]) $parts[2] .= '.';\n return implode(' ', array_filter($parts));\n }",
" function getLastFirst() {\n $name = $this->parts['last'].', '.$this->parts['first'];\n if ($this->parts['suffix'])\n $name .= ', '.$this->parts['suffix'];\n return $name;\n }",
" function getShort() {\n return $this->parts['first'].' '.mb_substr($this->parts['last'],0,1).'.';\n }",
" function getShortFormal() {\n return mb_substr($this->parts['first'],0,1).'. '.$this->parts['last'];\n }",
" function getOriginal() {\n return $this->name;\n }",
" function getInitials() {\n $names = array($this->parts['first']);\n $names = array_merge($names, explode(' ', $this->parts['middle']));\n $names[] = $this->parts['last'];\n $initials = '';\n foreach (array_filter($names) as $n)\n $initials .= mb_substr($n,0,1);\n return mb_convert_case($initials, MB_CASE_UPPER);\n }",
" function getName() {\n return $this;\n }",
" function getNameFormats($user, $type) {\n $nameFormats = array();",
" foreach (PersonsName::allFormats() as $format => $func) {\n $nameFormats[$type . '.name.' . $format] = $user->getName()->$func[1]();\n }",
" return $nameFormats;\n }",
" function asVar() {\n return $this->__toString();\n }",
" static function getVarScope() {\n $formats = array();\n foreach (static::$formats as $name=>$info) {\n if (in_array($name, array('original', 'complete')))\n continue;\n $formats[$name] = $info[0];\n }\n return $formats;\n }",
" function __toString() {",
" @list(, $func) = static::$formats[$this->format];\n if (!$func) $func = 'getFull';",
" return (string) call_user_func(array($this, $func));\n }",
" static function allFormats() {\n return static::$formats;\n }",
" /**\n * Thanks, http://stackoverflow.com/a/14420217\n */\n static function splitName($name) {\n $results = array();",
" $r = explode(' ', $name);\n $size = count($r);",
" //check if name is bad format (ex: J.Everybody), and fix them\n if($size==1 && mb_strpos($r[0], '.') !== false)\n {\n $r = explode('.', $name);\n $size = count($r);\n }",
" //check first for period, assume salutation if so\n if (mb_strpos($r[0], '.') === false)\n {\n $results['salutation'] = '';\n $results['first'] = $r[0];\n }\n else\n {\n $results['salutation'] = $r[0];\n $results['first'] = $r[1];\n }",
" //check last for period, assume suffix if so\n if (mb_strpos($r[$size - 1], '.') === false)\n {\n $results['suffix'] = '';\n }\n else\n {\n $results['suffix'] = $r[$size - 1];\n }",
" //combine remains into last\n $start = ($results['salutation']) ? 2 : 1;\n $end = ($results['suffix']) ? $size - 2 : $size - 1;",
" $middle = array();\n for ($i = $start; $i <= $end; $i++)\n {\n $middle[] = $r[$i];\n }\n if (count($middle) > 1) {\n $results['last'] = array_pop($middle);\n $results['middle'] = implode(' ', $middle);\n }\n else {\n $results['last'] = $middle[0];\n $results['middle'] = '';\n }",
" return $results;\n }",
"}",
"class AgentsName extends PersonsName {\n function __construct($name, $format=null) {\n global $cfg;",
" if (!$format && $cfg)\n $format = $cfg->getAgentNameFormat();",
" parent::__construct($name, $format);\n }\n}",
"class UsersName extends PersonsName {\n function __construct($name, $format=null) {\n global $cfg;\n if (!$format && $cfg)\n $format = $cfg->getClientNameFormat();",
" parent::__construct($name, $format);\n }\n}",
"\nclass UserEmail extends UserEmailModel {\n static function ensure($address) {\n $email = static::lookup(array('address'=>$address));\n if (!$email) {\n $email = new static(array('address'=>$address));\n $email->save();\n }\n return $email;\n }\n}",
"\nclass UserAccount extends VerySimpleModel {\n static $meta = array(\n 'table' => USER_ACCOUNT_TABLE,\n 'pk' => array('id'),\n 'joins' => array(\n 'user' => array(\n 'null' => false,\n 'constraint' => array('user_id' => 'User.id')\n ),\n ),\n );",
" const LANG_MAILOUTS = 1; // Language preference for mailouts",
" var $_status;\n var $_extra;",
" function getStatus() {\n if (!isset($this->_status))\n $this->_status = new UserAccountStatus($this->get('status'));\n return $this->_status;\n }",
" function statusChanged($flag, $var) {\n if (($this->hasStatus($flag) && !$var) ||\n (!$this->hasStatus($flag) && $var))\n return true;\n }",
" protected function hasStatus($flag) {\n return $this->getStatus()->check($flag);\n }",
" protected function clearStatus($flag) {\n return $this->set('status', $this->get('status') & ~$flag);\n }",
" protected function setStatus($flag) {\n return $this->set('status', $this->get('status') | $flag);\n }",
" function confirm() {\n $this->setStatus(UserAccountStatus::CONFIRMED);\n return $this->save();\n }",
" function isConfirmed() {\n return $this->getStatus()->isConfirmed();\n }",
" function lock() {\n $this->setStatus(UserAccountStatus::LOCKED);\n return $this->save();\n }",
" function unlock() {\n $this->clearStatus(UserAccountStatus::LOCKED);\n return $this->save();\n }",
" function isLocked() {\n return $this->getStatus()->isLocked();\n }",
" function forcePasswdReset() {\n $this->setStatus(UserAccountStatus::REQUIRE_PASSWD_RESET);\n return $this->save();\n }",
" function isPasswdResetForced() {\n return $this->hasStatus(UserAccountStatus::REQUIRE_PASSWD_RESET);\n }",
" function isPasswdResetEnabled() {\n return !$this->hasStatus(UserAccountStatus::FORBID_PASSWD_RESET);\n }",
" function getInfo() {\n return $this->ht;\n }",
" function getId() {\n return $this->get('id');\n }",
" function getUserId() {\n return $this->get('user_id');\n }",
" function getUser() {\n return $this->user;\n }",
" function getUserName() {\n return $this->getUser()->getName();\n }",
" function getExtraAttr($attr=false, $default=null) {\n if (!isset($this->_extra))\n $this->_extra = JsonDataParser::decode($this->get('extra', ''));",
" return $attr ? (@$this->_extra[$attr] ?: $default) : $this->_extra;\n }",
" function setExtraAttr($attr, $value) {\n $this->getExtraAttr();\n $this->_extra[$attr] = $value;\n }",
" /**\n * Function: getLanguage\n *\n * Returns the language preference for the user or false if no\n * preference is defined. False indicates the browser indicated\n * preference should be used. For requests apart from browser requests,\n * the last language preference of the browser is set in the\n * 'browser_lang' extra attribute upon logins. Send the LANG_MAILOUTS\n * flag to also consider this saved value. Such is useful when sending\n * the user a message (such as an email), and the user's browser\n * preference is not available in the HTTP request.\n *\n * Parameters:\n * $flags - (int) Send UserAccount::LANG_MAILOUTS if the user's\n * last-known browser preference should be considered. Normally\n * only the user's saved language preference is considered.\n *\n * Returns:\n * Current or last-known language preference or false if no language\n * preference is currently set or known.\n */\n function getLanguage($flags=false) {\n $lang = $this->get('lang', false);\n if (!$lang && ($flags & UserAccount::LANG_MAILOUTS))\n $lang = $this->getExtraAttr('browser_lang', false);",
" return $lang;\n }",
" function getTimezone() {\n return $this->timezone;\n }",
" function save($refetch=false) {\n // Serialize the extra column on demand\n if (isset($this->_extra)) {\n $this->extra = JsonDataEncoder::encode($this->_extra);\n }\n return parent::save($refetch);\n }",
" function hasPassword() {\n return (bool) $this->get('passwd');\n }",
" function sendResetEmail() {\n return static::sendUnlockEmail('pwreset-client') === true;\n }",
" function sendConfirmEmail() {\n return static::sendUnlockEmail('registration-client') === true;\n }",
" function setPassword($new) {\n $this->set('passwd', Passwd::hash($new));\n // Clean sessions\n Signal::send('auth.clean', $this->getUser());\n }",
" protected function sendUnlockEmail($template) {\n global $ost, $cfg;",
" $token = Misc::randCode(48); // 290-bits",
" $email = $cfg->getDefaultEmail();\n $content = Page::lookupByType($template);",
" if (!$email || !$content)\n return new BaseError(sprintf(_S('%s: Unable to retrieve template'),\n $template));",
" $vars = array(\n 'url' => $ost->getConfig()->getBaseUrl(),\n 'token' => $token,\n 'user' => $this->getUser(),\n 'recipient' => $this->getUser(),\n 'link' => sprintf(\n \"%s/pwreset.php?token=%s\",\n $ost->getConfig()->getBaseUrl(),\n $token),\n );\n $vars['reset_link'] = &$vars['link'];",
" $info = array('email' => $email, 'vars' => &$vars, 'log'=>true);\n Signal::send('auth.pwreset.email', $this->getUser(), $info);",
" $lang = $this->getLanguage(UserAccount::LANG_MAILOUTS);\n $msg = $ost->replaceTemplateVariables(array(\n 'subj' => $content->getLocalName($lang),\n 'body' => $content->getLocalBody($lang),\n ), $vars);",
" $_config = new Config('pwreset');\n $_config->set($vars['token'], 'c'.$this->getUser()->getId());",
" $email->send($this->getUser()->getEmail(),\n Format::striptags($msg['subj']), $msg['body']);",
" return true;\n }",
" function __toString() {\n return (string) $this->getStatus();\n }",
" /*\n * Updates may be done by Staff or by the User if registration\n * options are set to Public\n */\n function update($vars, &$errors) {\n // TODO: Make sure the username is unique",
" // Timezone selection is not required. System default is a valid\n // fallback",
" // Changing password?\n if ($vars['passwd1'] || $vars['passwd2']) {\n if (!$vars['passwd1'])\n $errors['passwd1'] = __('New password is required');\n elseif ($vars['passwd1'] && strlen($vars['passwd1'])<6)\n $errors['passwd1'] = __('Must be at least 6 characters');\n elseif ($vars['passwd1'] && strcmp($vars['passwd1'], $vars['passwd2']))\n $errors['passwd2'] = __('Passwords do not match');\n }",
" // Make sure the username is not an email.\n if ($vars['username'] && Validator::is_email($vars['username']))\n $errors['username'] =\n __('Users can always sign in with their email address');",
" if ($errors) return false;",
" //flags\n $pwreset = $this->statusChanged(UserAccountStatus::REQUIRE_PASSWD_RESET, $vars['pwreset-flag']);\n $locked = $this->statusChanged(UserAccountStatus::LOCKED, $vars['locked-flag']);\n $forbidPwChange = $this->statusChanged(UserAccountStatus::FORBID_PASSWD_RESET, $vars['forbid-pwchange-flag']);",
" $info = $this->getInfo();\n foreach ($vars as $key => $value) {\n if (($key != 'id' && $info[$key] && $info[$key] != $value) || ($pwreset && $key == 'pwreset-flag' ||\n $locked && $key == 'locked-flag' || $forbidPwChange && $key == 'forbid-pwchange-flag')) {\n $type = array('type' => 'edited', 'key' => $key);\n Signal::send('object.edited', $this, $type);\n }\n }",
" $this->set('timezone', $vars['timezone']);\n $this->set('username', $vars['username']);",
" if ($vars['passwd1']) {\n $this->setPassword($vars['passwd1']);\n $this->setStatus(UserAccountStatus::CONFIRMED);\n $type = array('type' => 'edited', 'key' => 'password');\n Signal::send('object.edited', $this, $type);\n }",
" // Set flags\n foreach (array(\n 'pwreset-flag' => UserAccountStatus::REQUIRE_PASSWD_RESET,\n 'locked-flag' => UserAccountStatus::LOCKED,\n 'forbid-pwchange-flag' => UserAccountStatus::FORBID_PASSWD_RESET\n ) as $ck=>$flag) {\n if ($vars[$ck])\n $this->setStatus($flag);\n else {\n if (($pwreset && $ck == 'pwreset-flag') || ($locked && $ck == 'locked-flag') ||\n ($forbidPwChange && $ck == 'forbid-pwchange-flag')) {\n $type = array('type' => 'edited', 'key' => $ck);\n Signal::send('object.edited', $this, $type);\n }\n $this->clearStatus($flag);\n }\n }",
" return $this->save(true);\n }",
" static function createForUser($user, $defaults=false) {\n $acct = new static(array('user_id'=>$user->getId()));\n if ($defaults && is_array($defaults)) {\n foreach ($defaults as $k => $v)\n $acct->set($k, $v);\n }\n return $acct;\n }",
" static function lookupByUsername($username) {",
" if (strpos($username, '@') !== false)\n $user = static::lookup(array('user__emails__address'=>$username));\n else\n $user = static::lookup(array('username'=>$username));",
"\n return $user;\n }",
" static function register($user, $vars, &$errors) {",
" if (!$user || !$vars)\n return false;",
" //Require temp password.\n if ((!$vars['backend'] || $vars['backend'] != 'client')\n && !isset($vars['sendemail'])) {\n if (!$vars['passwd1'])\n $errors['passwd1'] = 'Temporary password required';\n elseif ($vars['passwd1'] && strlen($vars['passwd1'])<6)\n $errors['passwd1'] = 'Must be at least 6 characters';\n elseif ($vars['passwd1'] && strcmp($vars['passwd1'], $vars['passwd2']))\n $errors['passwd2'] = 'Passwords do not match';\n }",
" if ($errors) return false;",
" $account = new UserAccount(array(\n 'user_id' => $user->getId(),\n 'timezone' => $vars['timezone'],\n 'backend' => $vars['backend'],\n ));",
" if ($vars['username'] && strcasecmp($vars['username'], $user->getEmail()))\n $account->set('username', $vars['username']);",
" if ($vars['passwd1'] && !$vars['sendemail']) {\n $account->set('passwd', Passwd::hash($vars['passwd1']));\n $account->setStatus(UserAccountStatus::CONFIRMED);\n if ($vars['pwreset-flag'])\n $account->setStatus(UserAccountStatus::REQUIRE_PASSWD_RESET);\n if ($vars['forbid-pwreset-flag'])\n $account->setStatus(UserAccountStatus::FORBID_PASSWD_RESET);\n }\n elseif ($vars['backend'] && $vars['backend'] != 'client') {\n // Auto confirm remote accounts\n $account->setStatus(UserAccountStatus::CONFIRMED);\n }",
" $account->save(true);",
" if (!$account->isConfirmed() && $vars['sendemail'])\n $account->sendConfirmEmail();",
" return $account;\n }",
"}",
"class UserAccountStatus {",
" var $flag;",
" const CONFIRMED = 0x0001;\n const LOCKED = 0x0002;\n const REQUIRE_PASSWD_RESET = 0x0004;\n const FORBID_PASSWD_RESET = 0x0008;",
" function __construct($flag) {\n $this->flag = $flag;\n }",
" function check($flag) {\n return 0 !== ($this->flag & $flag);\n }",
" function isLocked() {\n return $this->check(self::LOCKED);\n }",
" function isConfirmed() {\n return $this->check(self::CONFIRMED);\n }",
" function __toString() {",
" if ($this->isLocked())\n return __('Locked (Administrative)');",
" if (!$this->isConfirmed())\n return __('Locked (Pending Activation)');",
" // ... Other flags here (password reset, etc).",
" return __('Active (Registered)');\n }\n}",
"/*\n * Generic user list.\n */\nclass UserList extends MailingList {",
" function add($user) {\n if (!$user instanceof ITicketUser)\n throw new InvalidArgumentException('User expected');",
" return parent::add($user);\n }\n}",
"?>"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [870, 1348, 224, 19, 76], "buggy_code_start_loc": [865, 1344, 223, 18, 42], "filenames": ["include/class.staff.php", "include/class.user.php", "include/class.validator.php", "pwreset.php", "scp/pwreset.php"], "fixing_code_end_loc": [870, 1348, 232, 21, 79], "fixing_code_start_loc": [865, 1344, 223, 18, 42], "message": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "2ACCEE58-8958-4EBE-BF9E-37DD119DBD44", "versionEndExcluding": "1.14.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "22F26EC6-59B4-4CCA-9A7E-FD8DD0D0ECE9", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.15", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality."}, {"lang": "es", "value": "Una inyecci\u00f3n SQL en el proceso de inicio de sesi\u00f3n y restablecimiento de contrase\u00f1a de osTicket versiones anteriores a 1.14.8 y 1.15.4, permite a atacantes acceder a la funcionalidad osTicket administration profile"}], "evaluatorComment": null, "id": "CVE-2021-42235", "lastModified": "2022-05-13T17:13:06.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-04T17:15:08.087", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}, "type": "CWE-89"}
| 259
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*********************************************************************\n class.user.php",
" External end-user identification for osTicket",
" Peter Rotich <peter@osticket.com>\n Jared Hancock <jared@osticket.com>\n Copyright (c) 2006-2013 osTicket\n http://www.osticket.com",
" Released under the GNU General Public License WITHOUT ANY WARRANTY.\n See LICENSE.TXT for details.",
" vim: expandtab sw=4 ts=4 sts=4:\n**********************************************************************/\nrequire_once INCLUDE_DIR . 'class.orm.php';\nrequire_once INCLUDE_DIR . 'class.util.php';\nrequire_once INCLUDE_DIR . 'class.variable.php';\nrequire_once INCLUDE_DIR . 'class.search.php';\nrequire_once INCLUDE_DIR . 'class.organization.php';",
"class UserEmailModel extends VerySimpleModel {\n static $meta = array(\n 'table' => USER_EMAIL_TABLE,\n 'pk' => array('id'),\n 'joins' => array(\n 'user' => array(\n 'constraint' => array('user_id' => 'UserModel.id')\n )\n )\n );",
" function __toString() {\n return (string) $this->address;\n }",
" static function getIdByEmail($email) {\n $row = UserEmailModel::objects()\n ->filter(array('address'=>$email))\n ->values_flat('user_id')\n ->first();",
" return $row ? $row[0] : 0;\n }\n}",
"class UserModel extends VerySimpleModel {\n static $meta = array(\n 'table' => USER_TABLE,\n 'pk' => array('id'),\n 'select_related' => array('default_email', 'org', 'account'),\n 'joins' => array(\n 'emails' => array(\n 'reverse' => 'UserEmailModel.user',\n ),\n 'tickets' => array(\n 'null' => true,\n 'reverse' => 'Ticket.user',\n ),\n 'account' => array(\n 'list' => false,\n 'null' => true,\n 'reverse' => 'ClientAccount.user',\n ),\n 'org' => array(\n 'null' => true,\n 'constraint' => array('org_id' => 'Organization.id')\n ),\n 'default_email' => array(\n 'null' => true,\n 'constraint' => array('default_email_id' => 'UserEmailModel.id')\n ),\n 'cdata' => array(\n 'constraint' => array('id' => 'UserCdata.user_id'),\n 'null' => true,\n ),\n 'entries' => array(\n 'constraint' => array(\n 'id' => 'DynamicFormEntry.object_id',\n \"'U'\" => 'DynamicFormEntry.object_type',\n ),\n 'list' => true,\n ),\n )\n );",
" const PRIMARY_ORG_CONTACT = 0x0001;",
" const PERM_CREATE = 'user.create';\n const PERM_EDIT = 'user.edit';\n const PERM_DELETE = 'user.delete';\n const PERM_MANAGE = 'user.manage';\n const PERM_DIRECTORY = 'user.dir';",
" static protected $perms = array(\n self::PERM_CREATE => array(\n 'title' => /* @trans */ 'Create',\n 'desc' => /* @trans */ 'Ability to add new users',\n 'primary' => true,\n ),\n self::PERM_EDIT => array(\n 'title' => /* @trans */ 'Edit',\n 'desc' => /* @trans */ 'Ability to manage user information',\n 'primary' => true,\n ),\n self::PERM_DELETE => array(\n 'title' => /* @trans */ 'Delete',\n 'desc' => /* @trans */ 'Ability to delete users',\n 'primary' => true,\n ),\n self::PERM_MANAGE => array(\n 'title' => /* @trans */ 'Manage Account',\n 'desc' => /* @trans */ 'Ability to manage active user accounts',\n 'primary' => true,\n ),\n self::PERM_DIRECTORY => array(\n 'title' => /* @trans */ 'User Directory',\n 'desc' => /* @trans */ 'Ability to access the user directory',\n 'primary' => true,\n ),\n );",
" function getId() {\n return $this->id;\n }",
" function getDefaultEmailAddress() {\n return $this->getDefaultEmail()->address;\n }",
" function getDefaultEmail() {\n return $this->default_email;\n }",
" function hasAccount() {\n return !is_null($this->account);\n }\n function getAccount() {\n return $this->account;\n }",
" function getOrgId() {\n return $this->get('org_id');\n }",
" function getOrganization() {\n return $this->org;\n }",
" function setOrganization($org, $save=true) {",
" $this->set('org', $org);",
" if ($save)\n $this->save();",
" return true;\n }",
" public function setFlag($flag, $val) {\n if ($val)\n $this->status |= $flag;\n else\n $this->status &= ~$flag;\n }",
" protected function hasStatus($flag) {\n return $this->get('status') & $flag !== 0;\n }",
" protected function clearStatus($flag) {\n return $this->set('status', $this->get('status') & ~$flag);\n }",
" protected function setStatus($flag) {\n return $this->set('status', $this->get('status') | $flag);\n }",
" function isPrimaryContact() {\n return $this->hasStatus(User::PRIMARY_ORG_CONTACT);\n }",
" function setPrimaryContact($flag) {\n if ($flag)\n $this->setStatus(User::PRIMARY_ORG_CONTACT);\n else\n $this->clearStatus(User::PRIMARY_ORG_CONTACT);\n }",
" static function getPermissions() {\n return self::$perms;\n }\n}\ninclude_once INCLUDE_DIR.'class.role.php';\nRolePermission::register(/* @trans */ 'Users', UserModel::getPermissions());",
"class UserCdata extends VerySimpleModel {\n static $meta = array(\n 'table' => USER_CDATA_TABLE,\n 'pk' => array('user_id'),\n 'joins' => array(\n 'user' => array(\n 'constraint' => array('user_id' => 'UserModel.id'),\n ),\n ),\n );\n}",
"class User extends UserModel\nimplements TemplateVariable, Searchable {",
" var $_email;\n var $_entries;\n var $_forms;\n var $_queue;",
"",
" static function fromVars($vars, $create=true, $update=false) {\n // Try and lookup by email address\n $user = static::lookupByEmail($vars['email']);\n if (!$user && $create) {\n $name = $vars['name'];\n if (is_array($name))\n $name = implode(', ', $name);\n elseif (!$name)\n list($name) = explode('@', $vars['email'], 2);",
" $user = new User(array(\n 'name' => Format::htmldecode(Format::sanitize($name, false)),\n 'created' => new SqlFunction('NOW'),\n 'updated' => new SqlFunction('NOW'),\n //XXX: Do plain create once the cause\n // of the detached emails is fixed.\n 'default_email' => UserEmail::ensure($vars['email'])\n ));\n // Is there an organization registered for this domain\n list($mailbox, $domain) = explode('@', $vars['email'], 2);\n if (isset($vars['org_id']))\n $user->set('org_id', $vars['org_id']);\n elseif ($org = Organization::forDomain($domain))\n $user->setOrganization($org, false);",
" try {\n $user->save(true);\n $user->emails->add($user->default_email);\n // Attach initial custom fields\n $user->addDynamicData($vars);\n }\n catch (OrmException $e) {\n return null;\n }\n $type = array('type' => 'created');\n Signal::send('object.created', $user, $type);\n Signal::send('user.created', $user);\n }\n elseif ($update) {\n $errors = array();\n $user->updateInfo($vars, $errors, true);\n }",
" return $user;\n }",
" static function fromForm($form, $create=true) {\n global $thisstaff;",
" if(!$form) return null;",
" //Validate the form\n $valid = true;\n $filter = function($f) use ($thisstaff) {\n return !isset($thisstaff) || $f->isRequiredForStaff() || $f->isVisibleToStaff();\n };\n if (!$form->isValid($filter))\n $valid = false;",
" //Make sure the email is not in-use\n if (($field=$form->getField('email'))\n && $field->getClean()\n && User::lookup(array('emails__address'=>$field->getClean()))) {\n $field->addError(__('Email is assigned to another user'));\n $valid = false;\n }",
" return $valid ? self::fromVars($form->getClean(), $create) : null;\n }",
" function getEmail() {",
" if (!isset($this->_email))\n $this->_email = new EmailAddress(sprintf('\"%s\" <%s>',\n addcslashes($this->getName(), '\"'),\n $this->default_email->address));",
" return $this->_email;\n }",
" function getAvatar($size=null) {\n global $cfg;\n $source = $cfg->getClientAvatarSource();\n $avatar = $source->getAvatar($this);\n if (isset($size))\n $avatar->setSize($size);\n return $avatar;\n }",
" function getFullName() {\n return $this->name;\n }",
" function getPhoneNumber() {\n foreach ($this->getDynamicData() as $e)\n if ($a = $e->getAnswer('phone'))\n return $a;\n }",
" function getName() {\n if (!$this->name)\n list($name) = explode('@', $this->getDefaultEmailAddress(), 2);\n else\n $name = $this->name;\n return new UsersName($name);\n }",
" function getUpdateDate() {\n return $this->updated;\n }",
" function getCreateDate() {\n return $this->created;\n }",
" function getTimezone() {\n global $cfg;",
" if (($acct = $this->getAccount()) && ($tz = $acct->getTimezone())) {\n return $tz;\n }\n return $cfg->getDefaultTimezone();\n }",
" function addForm($form, $sort=1, $data=null) {\n $entry = $form->instanciate($sort, $data);\n $entry->set('object_type', 'U');\n $entry->set('object_id', $this->getId());\n $entry->save();\n return $entry;\n }",
" function getLanguage($flags=false) {\n if ($acct = $this->getAccount())\n return $acct->getLanguage($flags);\n }",
" function to_json() {",
" $info = array(\n 'id' => $this->getId(),\n 'name' => Format::htmlchars($this->getName()),\n 'email' => (string) $this->getEmail(),\n 'phone' => (string) $this->getPhoneNumber());",
" return Format::json_encode($info);\n }",
" function __toString() {\n return $this->asVar();\n }",
" function asVar() {\n return (string) $this->getName();\n }",
" function getVar($tag) {\n $tag = mb_strtolower($tag);\n foreach ($this->getDynamicData() as $e)\n if ($a = $e->getAnswer($tag))\n return $a;\n }",
" static function getVarScope() {\n $base = array(\n 'email' => array(\n 'class' => 'EmailAddress', 'desc' => __('Default email address')\n ),\n 'name' => array(\n 'class' => 'PersonsName', 'desc' => 'User name, default format'\n ),\n 'organization' => array('class' => 'Organization', 'desc' => __('Organization')),\n );\n $extra = VariableReplacer::compileFormScope(UserForm::getInstance());\n return $base + $extra;\n }",
" static function getSearchableFields() {\n $base = array();\n $uform = UserForm::getUserForm();\n $base = array();\n foreach ($uform->getFields() as $F) {\n $fname = $F->get('name') ?: ('field_'.$F->get('id'));\n # XXX: email in the model corresponds to `emails__address` ORM path\n if ($fname == 'email')\n $fname = 'emails__address';\n if (!$F->hasData() || $F->isPresentationOnly())\n continue;\n if (!$F->isStorable())\n $base[$fname] = $F;\n else\n $base[\"cdata__{$fname}\"] = $F;\n }\n return $base;\n }",
" static function supportsCustomData() {\n return true;\n }",
" function addDynamicData($data) {\n return $this->addForm(UserForm::objects()->one(), 1, $data);\n }",
" function getDynamicData($create=true) {\n if (!isset($this->_entries)) {\n $this->_entries = DynamicFormEntry::forObject($this->id, 'U')->all();\n if (!$this->_entries && $create) {\n $g = UserForm::getNewInstance();\n $g->setClientId($this->id);\n $g->save();\n $this->_entries[] = $g;\n }\n }",
" return $this->_entries ?: array();\n }",
" function getFilterData() {\n $vars = array();\n foreach ($this->getDynamicData() as $entry) {\n $vars += $entry->getFilterData();",
" // Add in special `name` and `email` fields\n if ($entry->getDynamicForm()->get('type') != 'U')\n continue;",
" foreach (array('name', 'email') as $name) {\n if ($f = $entry->getField($name))\n $vars['field.'.$f->get('id')] =\n $name == 'name' ? $this->getName() : $this->getEmail();\n }\n }",
" return $vars;\n }",
" function getForms($data=null, $cb=null) {",
" if (!isset($this->_forms)) {\n $this->_forms = array();\n $cb = $cb ?: function ($f) use($data) { return ($data); };\n foreach ($this->getDynamicData() as $entry) {\n $entry->addMissingFields();\n if(($form = $entry->getDynamicForm())\n && $form->get('type') == 'U' ) {",
" foreach ($entry->getFields() as $f) {\n if ($f->get('name') == 'name' && !$cb($f))\n $f->value = $this->getFullName();\n elseif ($f->get('name') == 'email' && !$cb($f))\n $f->value = $this->getEmail();\n }\n }",
" $this->_forms[] = $entry;\n }\n }",
" return $this->_forms;\n }",
" function getAccountStatus() {",
" if (!($account=$this->getAccount()))\n return __('Guest');",
" return (string) $account->getStatus();\n }",
" function canSeeOrgTickets() {\n return $this->org && (\n $this->org->shareWithEverybody()\n || ($this->isPrimaryContact() && $this->org->shareWithPrimaryContacts()));\n }",
" function register($vars, &$errors) {",
" // user already registered?\n if ($this->getAccount())\n return true;",
" return UserAccount::register($this, $vars, $errors);\n }",
" static function importCsv($stream, $defaults=array()) {\n require_once INCLUDE_DIR . 'class.import.php';",
" $importer = new CsvImporter($stream);\n $imported = 0;\n try {\n db_autocommit(false);\n $records = $importer->importCsv(UserForm::getUserForm()->getFields(), $defaults);\n foreach ($records as $data) {\n if (!Validator::is_email($data['email']) || empty($data['name']))\n throw new ImportError('Both `name` and `email` fields are required');\n if (!($user = static::fromVars($data, true, true)))\n throw new ImportError(sprintf(__('Unable to import user: %s'),\n print_r(Format::htmlchars($data), true)));\n $imported++;\n }\n db_autocommit(true);\n }\n catch (Exception $ex) {\n db_rollback();\n return $ex->getMessage();\n }\n return $imported;\n }",
" function importFromPost($stream, $extra=array()) {\n if (!is_array($stream))\n $stream = sprintf('name, email%s %s',PHP_EOL, $stream);",
" return User::importCsv($stream, $extra);\n }",
" function updateInfo($vars, &$errors, $staff=false) {\n $isEditable = function ($f) use($staff) {\n return ($staff ? $f->isEditableToStaff() :\n $f->isEditableToUsers());\n };\n $valid = true;\n $forms = $this->getForms($vars, $isEditable);\n foreach ($forms as $entry) {\n $entry->setSource($vars);\n if ($staff && !$entry->isValidForStaff(true))\n $valid = false;\n elseif (!$staff && !$entry->isValidForClient(true))\n $valid = false;\n elseif ($entry->getDynamicForm()->get('type') == 'U'\n && ($f=$entry->getField('email'))\n && $isEditable($f)\n && $f->getClean()\n && ($u=User::lookup(array('emails__address'=>$f->getClean())))\n && $u->id != $this->getId()) {\n $valid = false;\n $f->addError(__('Email is assigned to another user'));\n }",
" if (!$valid)\n $errors = array_merge($errors, $entry->errors());\n }",
"\n if (!$valid)\n return false;",
" // Save the entries\n foreach ($forms as $entry) {\n $fields = $entry->getFields();\n foreach ($fields as $field) {\n $changes = $field->getChanges();\n if ((is_array($changes) && $changes[0]) || $changes && !is_array($changes)) {\n $type = array('type' => 'edited', 'key' => $field->getLabel());\n Signal::send('object.edited', $this, $type);\n }\n }",
" if ($entry->getDynamicForm()->get('type') == 'U') {\n // Name field\n if (($name = $entry->getField('name')) && $isEditable($name) ) {\n $name = $name->getClean();\n if (is_array($name))\n $name = implode(', ', $name);\n if ($this->name != $name) {\n $type = array('type' => 'edited', 'key' => 'Name');\n Signal::send('object.edited', $this, $type);\n }\n $this->name = $name;\n }",
" // Email address field\n if (($email = $entry->getField('email'))\n && $isEditable($email)) {\n if ($this->default_email->address != $email->getClean()) {\n $type = array('type' => 'edited', 'key' => 'Email');\n Signal::send('object.edited', $this, $type);\n }\n $this->default_email->address = $email->getClean();\n $this->default_email->save();\n }\n }",
" // DynamicFormEntry::saveAnswers returns the number of answers updated\n if ($entry->saveAnswers($isEditable)) {\n $this->updated = SqlFunction::NOW();\n }\n }",
" return $this->save();\n }",
"\n function save($refetch=false) {\n // Drop commas and reorganize the name without them\n $parts = array_map('trim', explode(',', $this->name));\n switch (count($parts)) {\n case 2:\n // Assume last, first --or-- last suff., first\n $this->name = $parts[1].' '.$parts[0];\n // XXX: Consider last, first suff.\n break;\n case 3:\n // Assume last, first, suffix, write 'first last suffix'\n $this->name = $parts[1].' '.$parts[0].' '.$parts[2];\n break;\n }",
" // Handle email addresses -- use the box name\n if (Validator::is_email($this->name)) {\n list($box, $domain) = explode('@', $this->name, 2);\n if (strpos($box, '.') !== false)\n $this->name = str_replace('.', ' ', $box);\n else\n $this->name = $box;\n $this->name = mb_convert_case($this->name, MB_CASE_TITLE);\n }",
" if (count($this->dirty)) //XXX: doesn't work??\n $this->set('updated', new SqlFunction('NOW'));\n return parent::save($refetch);\n }",
" function delete() {\n // Refuse to delete a user with tickets\n if ($this->tickets->count())\n return false;",
" // Delete account record (if any)\n if ($this->getAccount())\n $this->getAccount()->delete();",
" // Delete emails.\n $this->emails->expunge();",
" // Drop dynamic data\n foreach ($this->getDynamicData() as $entry) {\n $entry->delete();\n }",
" $type = array('type' => 'deleted');\n Signal::send('object.deleted', $this, $type);",
" // Delete user\n return parent::delete();\n }",
" function deleteAllTickets() {\n $status_id = TicketStatus::lookup(array('state' => 'deleted'));\n foreach($this->tickets as $ticket) {\n if (!$T = Ticket::lookup($ticket->getId()))\n continue;\n if (!$T->setStatus($status_id))\n return false;\n }\n $this->tickets->reset();\n return true;\n }",
" static function lookupByEmail($email) {\n return static::lookup(array('emails__address'=>$email));\n }",
" static function getNameById($id) {\n if ($user = static::lookup($id))\n return $user->getName();\n }",
" static function getLink($id) {\n global $thisstaff;",
" if (!$id || !$thisstaff)\n return false;",
" return ROOT_PATH . sprintf('scp/users.php?id=%s', $id);\n }",
" function getTicketsQueue($collabs=true) {\n global $thisstaff;",
" if (!$this->_queue) {\n $email = $this->getDefaultEmailAddress();\n $filter = [\n ['user__id', 'equal', $this->getId()],\n ];\n if ($collabs)\n $filter = [\n ['user__emails__address', 'equal', $email],\n ['thread__collaborators__user__emails__address', 'equal', $email],\n ];\n $this->_queue = new AdhocSearch(array(\n 'id' => 'adhoc,uid'.$this->getId(),\n 'root' => 'T',\n 'staff_id' => $thisstaff->getId(),\n 'title' => $this->getName()\n ));\n $this->_queue->config = $filter;\n }",
" return $this->_queue;\n }\n}",
"class EmailAddress\nimplements TemplateVariable {\n var $email;\n var $address;\n protected $_info;",
" function __construct($address) {\n $this->_info = self::parse($address);\n $this->email = sprintf('%s@%s',\n $this->getMailbox(),\n $this->getDomain());",
" if ($this->getName())\n $this->address = sprintf('\"%s\" <%s>',\n $this->getName(),\n $this->email);\n }",
" function __toString() {\n return (string) $this->email;\n }",
" function getVar($what) {",
" if (!$this->_info)\n return '';",
" switch ($what) {\n case 'host':\n case 'domain':\n return $this->_info->host;\n case 'personal':\n return trim($this->_info->personal, '\"');\n case 'mailbox':\n return $this->_info->mailbox;\n }\n }",
" function getAddress() {\n return $this->address ?: $this->email;\n }",
" function getHost() {\n return $this->getVar('host');\n }",
" function getDomain() {\n return $this->getHost();\n }",
" function getName() {\n return $this->getVar('personal');\n }",
" function getMailbox() {\n return $this->getVar('mailbox');\n }",
" // Parse and email adddress (RFC822) into it's parts.\n // @address - one address is expected\n static function parse($address) {\n require_once PEAR_DIR . 'Mail/RFC822.php';\n require_once PEAR_DIR . 'PEAR.php';\n if (($parts = Mail_RFC822::parseAddressList($address))\n && !PEAR::isError($parts))\n return current($parts);\n }",
" static function getVarScope() {\n return array(\n 'domain' => __('Domain'),\n 'mailbox' => __('Mailbox'),\n 'personal' => __('Personal name'),\n );\n }\n}",
"class PersonsName\nimplements TemplateVariable {\n var $format;\n var $parts;\n var $name;",
" static $formats = array(\n 'first' => array( /*@trans*/ \"First\", 'getFirst'),\n 'last' => array( /*@trans*/ \"Last\", 'getLast'),\n 'full' => array( /*@trans*/ \"First Last\", 'getFull'),\n 'legal' => array( /*@trans*/ \"First M. Last\", 'getLegal'),\n 'lastfirst' => array( /*@trans*/ \"Last, First\", 'getLastFirst'),\n 'formal' => array( /*@trans*/ \"Mr. Last\", 'getFormal'),\n 'short' => array( /*@trans*/ \"First L.\", 'getShort'),\n 'shortformal' => array(/*@trans*/ \"F. Last\", 'getShortFormal'),\n 'complete' => array( /*@trans*/ \"Mr. First M. Last Sr.\", 'getComplete'),\n 'original' => array( /*@trans*/ '-- As Entered --', 'getOriginal'),\n );",
" function __construct($name, $format=null) {\n global $cfg;",
" if ($format && isset(static::$formats[$format]))\n $this->format = $format;\n else\n $this->format = 'original';",
" if (!is_array($name)) {\n $this->parts = static::splitName($name);\n $this->name = $name;\n }\n else {\n $this->parts = $name;\n $this->name = implode(' ', $name);\n }\n }",
" function getFirst() {\n return $this->parts['first'];\n }",
" function getLast() {\n return $this->parts['last'];\n }",
" function getMiddle() {\n return $this->parts['middle'];\n }",
" function getMiddleInitial() {\n return mb_substr($this->parts['middle'],0,1).'.';\n }",
" function getFormal() {\n return trim($this->parts['salutation'].' '.$this->parts['last']);\n }",
" function getFull() {\n return trim($this->parts['first'].' '.$this->parts['last']);\n }",
" function getLegal() {\n $parts = array(\n $this->parts['first'],\n mb_substr($this->parts['middle'],0,1),\n $this->parts['last'],\n );\n if ($parts[1]) $parts[1] .= '.';\n return implode(' ', array_filter($parts));\n }",
" function getComplete() {\n $parts = array(\n $this->parts['salutation'],\n $this->parts['first'],\n mb_substr($this->parts['middle'],0,1),\n $this->parts['last'],\n $this->parts['suffix']\n );\n if ($parts[2]) $parts[2] .= '.';\n return implode(' ', array_filter($parts));\n }",
" function getLastFirst() {\n $name = $this->parts['last'].', '.$this->parts['first'];\n if ($this->parts['suffix'])\n $name .= ', '.$this->parts['suffix'];\n return $name;\n }",
" function getShort() {\n return $this->parts['first'].' '.mb_substr($this->parts['last'],0,1).'.';\n }",
" function getShortFormal() {\n return mb_substr($this->parts['first'],0,1).'. '.$this->parts['last'];\n }",
" function getOriginal() {\n return $this->name;\n }",
" function getInitials() {\n $names = array($this->parts['first']);\n $names = array_merge($names, explode(' ', $this->parts['middle']));\n $names[] = $this->parts['last'];\n $initials = '';\n foreach (array_filter($names) as $n)\n $initials .= mb_substr($n,0,1);\n return mb_convert_case($initials, MB_CASE_UPPER);\n }",
" function getName() {\n return $this;\n }",
" function getNameFormats($user, $type) {\n $nameFormats = array();",
" foreach (PersonsName::allFormats() as $format => $func) {\n $nameFormats[$type . '.name.' . $format] = $user->getName()->$func[1]();\n }",
" return $nameFormats;\n }",
" function asVar() {\n return $this->__toString();\n }",
" static function getVarScope() {\n $formats = array();\n foreach (static::$formats as $name=>$info) {\n if (in_array($name, array('original', 'complete')))\n continue;\n $formats[$name] = $info[0];\n }\n return $formats;\n }",
" function __toString() {",
" @list(, $func) = static::$formats[$this->format];\n if (!$func) $func = 'getFull';",
" return (string) call_user_func(array($this, $func));\n }",
" static function allFormats() {\n return static::$formats;\n }",
" /**\n * Thanks, http://stackoverflow.com/a/14420217\n */\n static function splitName($name) {\n $results = array();",
" $r = explode(' ', $name);\n $size = count($r);",
" //check if name is bad format (ex: J.Everybody), and fix them\n if($size==1 && mb_strpos($r[0], '.') !== false)\n {\n $r = explode('.', $name);\n $size = count($r);\n }",
" //check first for period, assume salutation if so\n if (mb_strpos($r[0], '.') === false)\n {\n $results['salutation'] = '';\n $results['first'] = $r[0];\n }\n else\n {\n $results['salutation'] = $r[0];\n $results['first'] = $r[1];\n }",
" //check last for period, assume suffix if so\n if (mb_strpos($r[$size - 1], '.') === false)\n {\n $results['suffix'] = '';\n }\n else\n {\n $results['suffix'] = $r[$size - 1];\n }",
" //combine remains into last\n $start = ($results['salutation']) ? 2 : 1;\n $end = ($results['suffix']) ? $size - 2 : $size - 1;",
" $middle = array();\n for ($i = $start; $i <= $end; $i++)\n {\n $middle[] = $r[$i];\n }\n if (count($middle) > 1) {\n $results['last'] = array_pop($middle);\n $results['middle'] = implode(' ', $middle);\n }\n else {\n $results['last'] = $middle[0];\n $results['middle'] = '';\n }",
" return $results;\n }",
"}",
"class AgentsName extends PersonsName {\n function __construct($name, $format=null) {\n global $cfg;",
" if (!$format && $cfg)\n $format = $cfg->getAgentNameFormat();",
" parent::__construct($name, $format);\n }\n}",
"class UsersName extends PersonsName {\n function __construct($name, $format=null) {\n global $cfg;\n if (!$format && $cfg)\n $format = $cfg->getClientNameFormat();",
" parent::__construct($name, $format);\n }\n}",
"\nclass UserEmail extends UserEmailModel {\n static function ensure($address) {\n $email = static::lookup(array('address'=>$address));\n if (!$email) {\n $email = new static(array('address'=>$address));\n $email->save();\n }\n return $email;\n }\n}",
"\nclass UserAccount extends VerySimpleModel {\n static $meta = array(\n 'table' => USER_ACCOUNT_TABLE,\n 'pk' => array('id'),\n 'joins' => array(\n 'user' => array(\n 'null' => false,\n 'constraint' => array('user_id' => 'User.id')\n ),\n ),\n );",
" const LANG_MAILOUTS = 1; // Language preference for mailouts",
" var $_status;\n var $_extra;",
" function getStatus() {\n if (!isset($this->_status))\n $this->_status = new UserAccountStatus($this->get('status'));\n return $this->_status;\n }",
" function statusChanged($flag, $var) {\n if (($this->hasStatus($flag) && !$var) ||\n (!$this->hasStatus($flag) && $var))\n return true;\n }",
" protected function hasStatus($flag) {\n return $this->getStatus()->check($flag);\n }",
" protected function clearStatus($flag) {\n return $this->set('status', $this->get('status') & ~$flag);\n }",
" protected function setStatus($flag) {\n return $this->set('status', $this->get('status') | $flag);\n }",
" function confirm() {\n $this->setStatus(UserAccountStatus::CONFIRMED);\n return $this->save();\n }",
" function isConfirmed() {\n return $this->getStatus()->isConfirmed();\n }",
" function lock() {\n $this->setStatus(UserAccountStatus::LOCKED);\n return $this->save();\n }",
" function unlock() {\n $this->clearStatus(UserAccountStatus::LOCKED);\n return $this->save();\n }",
" function isLocked() {\n return $this->getStatus()->isLocked();\n }",
" function forcePasswdReset() {\n $this->setStatus(UserAccountStatus::REQUIRE_PASSWD_RESET);\n return $this->save();\n }",
" function isPasswdResetForced() {\n return $this->hasStatus(UserAccountStatus::REQUIRE_PASSWD_RESET);\n }",
" function isPasswdResetEnabled() {\n return !$this->hasStatus(UserAccountStatus::FORBID_PASSWD_RESET);\n }",
" function getInfo() {\n return $this->ht;\n }",
" function getId() {\n return $this->get('id');\n }",
" function getUserId() {\n return $this->get('user_id');\n }",
" function getUser() {\n return $this->user;\n }",
" function getUserName() {\n return $this->getUser()->getName();\n }",
" function getExtraAttr($attr=false, $default=null) {\n if (!isset($this->_extra))\n $this->_extra = JsonDataParser::decode($this->get('extra', ''));",
" return $attr ? (@$this->_extra[$attr] ?: $default) : $this->_extra;\n }",
" function setExtraAttr($attr, $value) {\n $this->getExtraAttr();\n $this->_extra[$attr] = $value;\n }",
" /**\n * Function: getLanguage\n *\n * Returns the language preference for the user or false if no\n * preference is defined. False indicates the browser indicated\n * preference should be used. For requests apart from browser requests,\n * the last language preference of the browser is set in the\n * 'browser_lang' extra attribute upon logins. Send the LANG_MAILOUTS\n * flag to also consider this saved value. Such is useful when sending\n * the user a message (such as an email), and the user's browser\n * preference is not available in the HTTP request.\n *\n * Parameters:\n * $flags - (int) Send UserAccount::LANG_MAILOUTS if the user's\n * last-known browser preference should be considered. Normally\n * only the user's saved language preference is considered.\n *\n * Returns:\n * Current or last-known language preference or false if no language\n * preference is currently set or known.\n */\n function getLanguage($flags=false) {\n $lang = $this->get('lang', false);\n if (!$lang && ($flags & UserAccount::LANG_MAILOUTS))\n $lang = $this->getExtraAttr('browser_lang', false);",
" return $lang;\n }",
" function getTimezone() {\n return $this->timezone;\n }",
" function save($refetch=false) {\n // Serialize the extra column on demand\n if (isset($this->_extra)) {\n $this->extra = JsonDataEncoder::encode($this->_extra);\n }\n return parent::save($refetch);\n }",
" function hasPassword() {\n return (bool) $this->get('passwd');\n }",
" function sendResetEmail() {\n return static::sendUnlockEmail('pwreset-client') === true;\n }",
" function sendConfirmEmail() {\n return static::sendUnlockEmail('registration-client') === true;\n }",
" function setPassword($new) {\n $this->set('passwd', Passwd::hash($new));\n // Clean sessions\n Signal::send('auth.clean', $this->getUser());\n }",
" protected function sendUnlockEmail($template) {\n global $ost, $cfg;",
" $token = Misc::randCode(48); // 290-bits",
" $email = $cfg->getDefaultEmail();\n $content = Page::lookupByType($template);",
" if (!$email || !$content)\n return new BaseError(sprintf(_S('%s: Unable to retrieve template'),\n $template));",
" $vars = array(\n 'url' => $ost->getConfig()->getBaseUrl(),\n 'token' => $token,\n 'user' => $this->getUser(),\n 'recipient' => $this->getUser(),\n 'link' => sprintf(\n \"%s/pwreset.php?token=%s\",\n $ost->getConfig()->getBaseUrl(),\n $token),\n );\n $vars['reset_link'] = &$vars['link'];",
" $info = array('email' => $email, 'vars' => &$vars, 'log'=>true);\n Signal::send('auth.pwreset.email', $this->getUser(), $info);",
" $lang = $this->getLanguage(UserAccount::LANG_MAILOUTS);\n $msg = $ost->replaceTemplateVariables(array(\n 'subj' => $content->getLocalName($lang),\n 'body' => $content->getLocalBody($lang),\n ), $vars);",
" $_config = new Config('pwreset');\n $_config->set($vars['token'], 'c'.$this->getUser()->getId());",
" $email->send($this->getUser()->getEmail(),\n Format::striptags($msg['subj']), $msg['body']);",
" return true;\n }",
" function __toString() {\n return (string) $this->getStatus();\n }",
" /*\n * Updates may be done by Staff or by the User if registration\n * options are set to Public\n */\n function update($vars, &$errors) {\n // TODO: Make sure the username is unique",
" // Timezone selection is not required. System default is a valid\n // fallback",
" // Changing password?\n if ($vars['passwd1'] || $vars['passwd2']) {\n if (!$vars['passwd1'])\n $errors['passwd1'] = __('New password is required');\n elseif ($vars['passwd1'] && strlen($vars['passwd1'])<6)\n $errors['passwd1'] = __('Must be at least 6 characters');\n elseif ($vars['passwd1'] && strcmp($vars['passwd1'], $vars['passwd2']))\n $errors['passwd2'] = __('Passwords do not match');\n }",
" // Make sure the username is not an email.\n if ($vars['username'] && Validator::is_email($vars['username']))\n $errors['username'] =\n __('Users can always sign in with their email address');",
" if ($errors) return false;",
" //flags\n $pwreset = $this->statusChanged(UserAccountStatus::REQUIRE_PASSWD_RESET, $vars['pwreset-flag']);\n $locked = $this->statusChanged(UserAccountStatus::LOCKED, $vars['locked-flag']);\n $forbidPwChange = $this->statusChanged(UserAccountStatus::FORBID_PASSWD_RESET, $vars['forbid-pwchange-flag']);",
" $info = $this->getInfo();\n foreach ($vars as $key => $value) {\n if (($key != 'id' && $info[$key] && $info[$key] != $value) || ($pwreset && $key == 'pwreset-flag' ||\n $locked && $key == 'locked-flag' || $forbidPwChange && $key == 'forbid-pwchange-flag')) {\n $type = array('type' => 'edited', 'key' => $key);\n Signal::send('object.edited', $this, $type);\n }\n }",
" $this->set('timezone', $vars['timezone']);\n $this->set('username', $vars['username']);",
" if ($vars['passwd1']) {\n $this->setPassword($vars['passwd1']);\n $this->setStatus(UserAccountStatus::CONFIRMED);\n $type = array('type' => 'edited', 'key' => 'password');\n Signal::send('object.edited', $this, $type);\n }",
" // Set flags\n foreach (array(\n 'pwreset-flag' => UserAccountStatus::REQUIRE_PASSWD_RESET,\n 'locked-flag' => UserAccountStatus::LOCKED,\n 'forbid-pwchange-flag' => UserAccountStatus::FORBID_PASSWD_RESET\n ) as $ck=>$flag) {\n if ($vars[$ck])\n $this->setStatus($flag);\n else {\n if (($pwreset && $ck == 'pwreset-flag') || ($locked && $ck == 'locked-flag') ||\n ($forbidPwChange && $ck == 'forbid-pwchange-flag')) {\n $type = array('type' => 'edited', 'key' => $ck);\n Signal::send('object.edited', $this, $type);\n }\n $this->clearStatus($flag);\n }\n }",
" return $this->save(true);\n }",
" static function createForUser($user, $defaults=false) {\n $acct = new static(array('user_id'=>$user->getId()));\n if ($defaults && is_array($defaults)) {\n foreach ($defaults as $k => $v)\n $acct->set($k, $v);\n }\n return $acct;\n }",
" static function lookupByUsername($username) {",
" if (Validator::is_email($username))\n $user = static::lookup(array('user__emails__address' => $username));\n elseif (Validator::is_userid($username))\n $user = static::lookup(array('username' => $username));",
"\n return $user;\n }",
" static function register($user, $vars, &$errors) {",
" if (!$user || !$vars)\n return false;",
" //Require temp password.\n if ((!$vars['backend'] || $vars['backend'] != 'client')\n && !isset($vars['sendemail'])) {\n if (!$vars['passwd1'])\n $errors['passwd1'] = 'Temporary password required';\n elseif ($vars['passwd1'] && strlen($vars['passwd1'])<6)\n $errors['passwd1'] = 'Must be at least 6 characters';\n elseif ($vars['passwd1'] && strcmp($vars['passwd1'], $vars['passwd2']))\n $errors['passwd2'] = 'Passwords do not match';\n }",
" if ($errors) return false;",
" $account = new UserAccount(array(\n 'user_id' => $user->getId(),\n 'timezone' => $vars['timezone'],\n 'backend' => $vars['backend'],\n ));",
" if ($vars['username'] && strcasecmp($vars['username'], $user->getEmail()))\n $account->set('username', $vars['username']);",
" if ($vars['passwd1'] && !$vars['sendemail']) {\n $account->set('passwd', Passwd::hash($vars['passwd1']));\n $account->setStatus(UserAccountStatus::CONFIRMED);\n if ($vars['pwreset-flag'])\n $account->setStatus(UserAccountStatus::REQUIRE_PASSWD_RESET);\n if ($vars['forbid-pwreset-flag'])\n $account->setStatus(UserAccountStatus::FORBID_PASSWD_RESET);\n }\n elseif ($vars['backend'] && $vars['backend'] != 'client') {\n // Auto confirm remote accounts\n $account->setStatus(UserAccountStatus::CONFIRMED);\n }",
" $account->save(true);",
" if (!$account->isConfirmed() && $vars['sendemail'])\n $account->sendConfirmEmail();",
" return $account;\n }",
"}",
"class UserAccountStatus {",
" var $flag;",
" const CONFIRMED = 0x0001;\n const LOCKED = 0x0002;\n const REQUIRE_PASSWD_RESET = 0x0004;\n const FORBID_PASSWD_RESET = 0x0008;",
" function __construct($flag) {\n $this->flag = $flag;\n }",
" function check($flag) {\n return 0 !== ($this->flag & $flag);\n }",
" function isLocked() {\n return $this->check(self::LOCKED);\n }",
" function isConfirmed() {\n return $this->check(self::CONFIRMED);\n }",
" function __toString() {",
" if ($this->isLocked())\n return __('Locked (Administrative)');",
" if (!$this->isConfirmed())\n return __('Locked (Pending Activation)');",
" // ... Other flags here (password reset, etc).",
" return __('Active (Registered)');\n }\n}",
"/*\n * Generic user list.\n */\nclass UserList extends MailingList {",
" function add($user) {\n if (!$user instanceof ITicketUser)\n throw new InvalidArgumentException('User expected');",
" return parent::add($user);\n }\n}",
"?>"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [870, 1348, 224, 19, 76], "buggy_code_start_loc": [865, 1344, 223, 18, 42], "filenames": ["include/class.staff.php", "include/class.user.php", "include/class.validator.php", "pwreset.php", "scp/pwreset.php"], "fixing_code_end_loc": [870, 1348, 232, 21, 79], "fixing_code_start_loc": [865, 1344, 223, 18, 42], "message": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "2ACCEE58-8958-4EBE-BF9E-37DD119DBD44", "versionEndExcluding": "1.14.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "22F26EC6-59B4-4CCA-9A7E-FD8DD0D0ECE9", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.15", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality."}, {"lang": "es", "value": "Una inyecci\u00f3n SQL en el proceso de inicio de sesi\u00f3n y restablecimiento de contrase\u00f1a de osTicket versiones anteriores a 1.14.8 y 1.15.4, permite a atacantes acceder a la funcionalidad osTicket administration profile"}], "evaluatorComment": null, "id": "CVE-2021-42235", "lastModified": "2022-05-13T17:13:06.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-04T17:15:08.087", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}, "type": "CWE-89"}
| 259
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*********************************************************************\n class.validator.php",
" Input validation helper. This class contains collection of functions used for data validation.",
" Peter Rotich <peter@osticket.com>\n Copyright (c) 2006-2013 osTicket\n http://www.osticket.com",
" Released under the GNU General Public License WITHOUT ANY WARRANTY.\n See LICENSE.TXT for details.",
" vim: expandtab sw=4 ts=4 sts=4:\n**********************************************************************/",
"class Validator {",
" var $input=array();\n var $fields=array();\n var $errors=array();",
" function __construct($fields=null) {\n $this->setFields($fields);\n }\n function setFields(&$fields){",
" if($fields && is_array($fields)):\n $this->fields=$fields;\n return (true);\n endif;",
" return (false);\n }",
"\n function validate($source,$userinput=true){\n $this->errors=array();\n //Check the input and make sure the fields are specified.\n if(!$source || !is_array($source))\n $this->errors['err']=__('Invalid input');\n elseif(!$this->fields || !is_array($this->fields))\n $this->errors['err']=__('No fields set up');\n //Abort on error\n if($this->errors)\n return false;",
" //if magic quotes are enabled - then try cleaning up inputs before validation...\n if($userinput && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())\n $source=Format::strip_slashes($source);",
"\n $this->input=$source;",
" //Do the do.\n foreach($this->fields as $k=>$field){\n if(!$field['required'] && !$this->input[$k]) //NOT required...and no data provided...\n continue;",
" if($field['required'] && !isset($this->input[$k]) || (!$this->input[$k] && $field['type']!='int')){ //Required...and no data provided...\n $this->errors[$k]=$field['error'];\n continue;\n }",
" //We don't care about the type.\n if ($field['type'] == '*') continue;",
" //Do the actual validation based on the type.\n switch(strtolower($field['type'])):\n case 'integer':\n case 'int':\n if(!is_numeric($this->input[$k]))\n $this->errors[$k]=$field['error'];\n elseif ($field['min'] && $this->input[$k] < $field['min'])\n $this->errors[$k]=$field['error'];\n break;\n case 'double':\n if(!is_numeric($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'text':\n case 'string':\n if(!is_string($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'array':\n if(!$this->input[$k] || !is_array($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'radio':\n if(!isset($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'date': //TODO...make sure it is really in GNU date format..\n if(strtotime($this->input[$k])===false)\n $this->errors[$k]=$field['error'];\n break;\n case 'time': //TODO...make sure it is really in GNU time format..\n break;\n case 'phone':\n case 'fax':\n if(!self::is_phone($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'email':\n if(!self::is_email($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'url':\n if(!self::is_url($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'password':\n if(strlen($this->input[$k])<6)\n $this->errors[$k]=$field['error'].' '.__('(Six characters min)');\n break;\n case 'username':\n $error = '';\n if (!self::is_username($this->input[$k], $error))\n $this->errors[$k]=$field['error'].\": $error\";\n break;\n case 'zipcode':\n if(!is_numeric($this->input[$k]) || (strlen($this->input[$k])!=5))\n $this->errors[$k]=$field['error'];\n break;\n case 'cs-domain': // Comma separated list of domains\n if($values=explode(',', $this->input[$k]))\n foreach($values as $v)\n if(!preg_match_all(\n '/^([a-z0-9|-]+\\.)*[a-z0-9|-]+\\.[a-z]+$/',\n ltrim($v)))\n $this->errors[$k]=$field['error'];\n break;\n case 'cs-url': // Comma separated list of urls\n if($values=explode(',', $this->input[$k]))\n foreach($values as $v)\n if(!preg_match_all(\n '/^(https?:\\/\\/)?((\\*\\.|\\w+\\.)?[\\w-]+(\\.[a-zA-Z]+)?(:([0-9]+|\\*))?)+$/',\n ltrim($v)))\n $this->errors[$k]=$field['error'];\n break;\n case 'ipaddr':\n if($values=explode(',', $this->input[$k])){\n foreach($values as $v)\n if(!preg_match_all('/^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$/', ltrim($v)))\n $this->errors[$k]=$field['error'];\n }\n break;\n default://If param type is not set...or handle..error out...\n $this->errors[$k]=$field['error'].' '.__('(type not set)');\n endswitch;\n }\n return ($this->errors)?(FALSE):(TRUE);\n }",
" function iserror(){\n return $this->errors?true:false;\n }",
" function errors(){\n return $this->errors;\n }",
" /*** Functions below can be called directly without class instance.\n Validator::func(var..); (nolint) ***/\n static function is_email($email, $list=false, $verify=false) {\n require_once PEAR_DIR . 'Mail/RFC822.php';\n require_once PEAR_DIR . 'PEAR.php';\n $rfc822 = new Mail_RFC822();\n if (!($mails = @$rfc822->parseAddressList($email)) || PEAR::isError($mails))\n return false;",
" if (!$list && count($mails) > 1)\n return false;",
" foreach ($mails as $m) {\n if (!$m->mailbox)\n return false;\n if ($m->host == 'localhost')\n return false;\n }",
" // According to RFC2821, the domain (A record) can be treated as an\n // MX if no MX records exist for the domain. Also, include a\n // full-stop trailing char so that the default domain of the server\n // is not added automatically\n if ($verify and !dns_get_record($m->host.'.', DNS_MX))\n return 0 < @count(dns_get_record($m->host.'.', DNS_A|DNS_AAAA));",
" return true;\n }",
" static function is_numeric($number, &$error='') {\n if (!is_numeric($number))\n $error = __('Enter a Number');\n return $error == '';\n }",
" static function is_valid_email($email, &$error='') {\n global $cfg;\n // Default to FALSE for installation\n return self::is_email($email, false, $cfg && $cfg->verifyEmailAddrs());\n }",
" static function is_phone($phone, &$error='') {\n /* We're not really validating the phone number but just making sure it doesn't contain illegal chars and of acceptable len */\n $stripped=preg_replace(\"(\\(|\\)|\\-|\\.|\\+|[ ]+)\",\"\",$phone);\n return (!is_numeric($stripped) || ((strlen($stripped)<7) || (strlen($stripped)>16)))?false:true;\n }",
" static function is_url($url) {\n //XXX: parse_url is not ideal for validating urls but it's ideal for basic checks.\n return ($url && ($info=parse_url($url)) && $info['host']);\n }",
" static function is_ip($ip, &$error='') {\n return filter_var(trim($ip), FILTER_VALIDATE_IP) !== false;\n }",
" static function is_username($username, &$error='') {\n if (strlen($username)<2)\n $error = __('Username must have at least two (2) characters');",
" elseif (!preg_match('/^[\\p{L}\\d._-]+$/u', $username))",
" $error = __('Username contains invalid characters');",
"",
" return $error == '';\n }",
" static function is_formula($text, &$error='') {\n if (!preg_match('/^[^=\\+@-].*$/s', $text))\n $error = __('Content cannot start with the following characters: = - + @');\n return $error == '';\n }",
" static function check_passwd($passwd, &$error='') {\n try {\n PasswordPolicy::checkPassword($passwd, null);\n } catch (BadPassword $ex) {\n $error = $ex->getMessage();\n }\n return $error == '';\n }",
" /*\n * check_ip\n * Checks if an IP (IPv4 or IPv6) address is contained in the list of given IPs or subnets.\n *\n * @credit - borrowed from Symfony project\n *\n */\n public static function check_ip($ip, $ips) {",
" if (!Validator::is_ip($ip))\n return false;",
" $method = substr_count($ip, ':') > 1 ? 'check_ipv6' : 'check_ipv4';\n $ips = is_array($ips) ? $ips : array($ips);\n foreach ($ips as $_ip) {\n if (self::$method($ip, $_ip)) {\n return true;\n }\n }",
" return false;\n }",
" /**\n * check_ipv4\n * Compares two IPv4 addresses.\n * In case a subnet is given, it checks if it contains the request IP.\n *\n * @credit - borrowed from Symfony project\n */\n public static function check_ipv4($ip, $cidr) {",
" if (false !== strpos($cidr, '/')) {\n list($address, $netmask) = explode('/', $cidr, 2);",
" if ($netmask === '0')\n return filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);",
" if ($netmask < 0 || $netmask > 32)\n return false;",
" } else {\n $address = $cidr;\n $netmask = 32;\n }",
" return 0 === substr_compare(\n sprintf('%032b', ip2long($ip)),\n sprintf('%032b', ip2long($address)),\n 0, $netmask);\n }",
" /**\n * Compares two IPv6 addresses.\n * In case a subnet is given, it checks if it contains the request IP.\n *\n * @credit - borrowed from Symfony project\n * @author David Soria Parra <dsp at php dot net>\n *\n * @see https://github.com/dsp/v6tools\n *\n */\n public static function check_ipv6($ip, $cidr) {",
" if (!((extension_loaded('sockets') && defined('AF_INET6')) || @inet_pton('::1')))\n return false;",
" if (false !== strpos($cidr, '/')) {\n list($address, $netmask) = explode('/', $cidr, 2);\n if ($netmask < 1 || $netmask > 128)\n return false;\n } else {\n $address = $cidr;\n $netmask = 128;\n }",
" $bytesAddr = unpack('n*', @inet_pton($address));\n $bytesTest = unpack('n*', @inet_pton($ip));\n if (!$bytesAddr || !$bytesTest)\n return false;",
" for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) {\n $left = $netmask - 16 * ($i - 1);\n $left = ($left <= 16) ? $left : 16;\n $mask = ~(0xffff >> $left) & 0xffff;\n if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {\n return false;\n }\n }",
" return true;\n }",
" function process($fields,$vars,&$errors){",
" $val = new Validator();\n $val->setFields($fields);\n if(!$val->validate($vars))\n $errors=array_merge($errors,$val->errors());",
" return (!$errors);\n }",
" function check_acl($backend) {\n global $cfg;",
" $acl = $cfg->getACL();\n if (empty($acl))\n return true;\n $ip = osTicket::get_client_ip();\n if (empty($ip))\n return false;",
" $aclbk = $cfg->getACLBackend();\n switch($backend) {\n case 'client':\n if (in_array($aclbk, array(0,3)))\n return true;\n break;\n case 'staff':\n if (in_array($aclbk, array(0,2)))\n return true;\n break;\n default:\n return false;\n break;\n }",
" if (!in_array($ip, $acl))\n return false;",
" return true;\n }\n}\n?>"
] |
[
1,
1,
1,
1,
1,
1,
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,
1,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [870, 1348, 224, 19, 76], "buggy_code_start_loc": [865, 1344, 223, 18, 42], "filenames": ["include/class.staff.php", "include/class.user.php", "include/class.validator.php", "pwreset.php", "scp/pwreset.php"], "fixing_code_end_loc": [870, 1348, 232, 21, 79], "fixing_code_start_loc": [865, 1344, 223, 18, 42], "message": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "2ACCEE58-8958-4EBE-BF9E-37DD119DBD44", "versionEndExcluding": "1.14.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "22F26EC6-59B4-4CCA-9A7E-FD8DD0D0ECE9", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.15", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality."}, {"lang": "es", "value": "Una inyecci\u00f3n SQL en el proceso de inicio de sesi\u00f3n y restablecimiento de contrase\u00f1a de osTicket versiones anteriores a 1.14.8 y 1.15.4, permite a atacantes acceder a la funcionalidad osTicket administration profile"}], "evaluatorComment": null, "id": "CVE-2021-42235", "lastModified": "2022-05-13T17:13:06.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-04T17:15:08.087", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}, "type": "CWE-89"}
| 259
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*********************************************************************\n class.validator.php",
" Input validation helper. This class contains collection of functions used for data validation.",
" Peter Rotich <peter@osticket.com>\n Copyright (c) 2006-2013 osTicket\n http://www.osticket.com",
" Released under the GNU General Public License WITHOUT ANY WARRANTY.\n See LICENSE.TXT for details.",
" vim: expandtab sw=4 ts=4 sts=4:\n**********************************************************************/",
"class Validator {",
" var $input=array();\n var $fields=array();\n var $errors=array();",
" function __construct($fields=null) {\n $this->setFields($fields);\n }\n function setFields(&$fields){",
" if($fields && is_array($fields)):\n $this->fields=$fields;\n return (true);\n endif;",
" return (false);\n }",
"\n function validate($source,$userinput=true){\n $this->errors=array();\n //Check the input and make sure the fields are specified.\n if(!$source || !is_array($source))\n $this->errors['err']=__('Invalid input');\n elseif(!$this->fields || !is_array($this->fields))\n $this->errors['err']=__('No fields set up');\n //Abort on error\n if($this->errors)\n return false;",
" //if magic quotes are enabled - then try cleaning up inputs before validation...\n if($userinput && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())\n $source=Format::strip_slashes($source);",
"\n $this->input=$source;",
" //Do the do.\n foreach($this->fields as $k=>$field){\n if(!$field['required'] && !$this->input[$k]) //NOT required...and no data provided...\n continue;",
" if($field['required'] && !isset($this->input[$k]) || (!$this->input[$k] && $field['type']!='int')){ //Required...and no data provided...\n $this->errors[$k]=$field['error'];\n continue;\n }",
" //We don't care about the type.\n if ($field['type'] == '*') continue;",
" //Do the actual validation based on the type.\n switch(strtolower($field['type'])):\n case 'integer':\n case 'int':\n if(!is_numeric($this->input[$k]))\n $this->errors[$k]=$field['error'];\n elseif ($field['min'] && $this->input[$k] < $field['min'])\n $this->errors[$k]=$field['error'];\n break;\n case 'double':\n if(!is_numeric($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'text':\n case 'string':\n if(!is_string($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'array':\n if(!$this->input[$k] || !is_array($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'radio':\n if(!isset($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'date': //TODO...make sure it is really in GNU date format..\n if(strtotime($this->input[$k])===false)\n $this->errors[$k]=$field['error'];\n break;\n case 'time': //TODO...make sure it is really in GNU time format..\n break;\n case 'phone':\n case 'fax':\n if(!self::is_phone($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'email':\n if(!self::is_email($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'url':\n if(!self::is_url($this->input[$k]))\n $this->errors[$k]=$field['error'];\n break;\n case 'password':\n if(strlen($this->input[$k])<6)\n $this->errors[$k]=$field['error'].' '.__('(Six characters min)');\n break;\n case 'username':\n $error = '';\n if (!self::is_username($this->input[$k], $error))\n $this->errors[$k]=$field['error'].\": $error\";\n break;\n case 'zipcode':\n if(!is_numeric($this->input[$k]) || (strlen($this->input[$k])!=5))\n $this->errors[$k]=$field['error'];\n break;\n case 'cs-domain': // Comma separated list of domains\n if($values=explode(',', $this->input[$k]))\n foreach($values as $v)\n if(!preg_match_all(\n '/^([a-z0-9|-]+\\.)*[a-z0-9|-]+\\.[a-z]+$/',\n ltrim($v)))\n $this->errors[$k]=$field['error'];\n break;\n case 'cs-url': // Comma separated list of urls\n if($values=explode(',', $this->input[$k]))\n foreach($values as $v)\n if(!preg_match_all(\n '/^(https?:\\/\\/)?((\\*\\.|\\w+\\.)?[\\w-]+(\\.[a-zA-Z]+)?(:([0-9]+|\\*))?)+$/',\n ltrim($v)))\n $this->errors[$k]=$field['error'];\n break;\n case 'ipaddr':\n if($values=explode(',', $this->input[$k])){\n foreach($values as $v)\n if(!preg_match_all('/^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$/', ltrim($v)))\n $this->errors[$k]=$field['error'];\n }\n break;\n default://If param type is not set...or handle..error out...\n $this->errors[$k]=$field['error'].' '.__('(type not set)');\n endswitch;\n }\n return ($this->errors)?(FALSE):(TRUE);\n }",
" function iserror(){\n return $this->errors?true:false;\n }",
" function errors(){\n return $this->errors;\n }",
" /*** Functions below can be called directly without class instance.\n Validator::func(var..); (nolint) ***/\n static function is_email($email, $list=false, $verify=false) {\n require_once PEAR_DIR . 'Mail/RFC822.php';\n require_once PEAR_DIR . 'PEAR.php';\n $rfc822 = new Mail_RFC822();\n if (!($mails = @$rfc822->parseAddressList($email)) || PEAR::isError($mails))\n return false;",
" if (!$list && count($mails) > 1)\n return false;",
" foreach ($mails as $m) {\n if (!$m->mailbox)\n return false;\n if ($m->host == 'localhost')\n return false;\n }",
" // According to RFC2821, the domain (A record) can be treated as an\n // MX if no MX records exist for the domain. Also, include a\n // full-stop trailing char so that the default domain of the server\n // is not added automatically\n if ($verify and !dns_get_record($m->host.'.', DNS_MX))\n return 0 < @count(dns_get_record($m->host.'.', DNS_A|DNS_AAAA));",
" return true;\n }",
" static function is_numeric($number, &$error='') {\n if (!is_numeric($number))\n $error = __('Enter a Number');\n return $error == '';\n }",
" static function is_valid_email($email, &$error='') {\n global $cfg;\n // Default to FALSE for installation\n return self::is_email($email, false, $cfg && $cfg->verifyEmailAddrs());\n }",
" static function is_phone($phone, &$error='') {\n /* We're not really validating the phone number but just making sure it doesn't contain illegal chars and of acceptable len */\n $stripped=preg_replace(\"(\\(|\\)|\\-|\\.|\\+|[ ]+)\",\"\",$phone);\n return (!is_numeric($stripped) || ((strlen($stripped)<7) || (strlen($stripped)>16)))?false:true;\n }",
" static function is_url($url) {\n //XXX: parse_url is not ideal for validating urls but it's ideal for basic checks.\n return ($url && ($info=parse_url($url)) && $info['host']);\n }",
" static function is_ip($ip, &$error='') {\n return filter_var(trim($ip), FILTER_VALIDATE_IP) !== false;\n }",
" static function is_username($username, &$error='') {\n if (strlen($username)<2)\n $error = __('Username must have at least two (2) characters');",
" elseif (is_numeric($username) || !preg_match('/^[\\p{L}\\d._-]+$/u', $username))",
" $error = __('Username contains invalid characters');",
" return $error == '';\n }",
" static function is_userid($userid, &$error='') {\n if (!self::is_username($userid)\n && !self::is_email($userid))\n $error = __('Invalid User Id ');",
" return $error == '';\n }",
" static function is_formula($text, &$error='') {\n if (!preg_match('/^[^=\\+@-].*$/s', $text))\n $error = __('Content cannot start with the following characters: = - + @');\n return $error == '';\n }",
" static function check_passwd($passwd, &$error='') {\n try {\n PasswordPolicy::checkPassword($passwd, null);\n } catch (BadPassword $ex) {\n $error = $ex->getMessage();\n }\n return $error == '';\n }",
" /*\n * check_ip\n * Checks if an IP (IPv4 or IPv6) address is contained in the list of given IPs or subnets.\n *\n * @credit - borrowed from Symfony project\n *\n */\n public static function check_ip($ip, $ips) {",
" if (!Validator::is_ip($ip))\n return false;",
" $method = substr_count($ip, ':') > 1 ? 'check_ipv6' : 'check_ipv4';\n $ips = is_array($ips) ? $ips : array($ips);\n foreach ($ips as $_ip) {\n if (self::$method($ip, $_ip)) {\n return true;\n }\n }",
" return false;\n }",
" /**\n * check_ipv4\n * Compares two IPv4 addresses.\n * In case a subnet is given, it checks if it contains the request IP.\n *\n * @credit - borrowed from Symfony project\n */\n public static function check_ipv4($ip, $cidr) {",
" if (false !== strpos($cidr, '/')) {\n list($address, $netmask) = explode('/', $cidr, 2);",
" if ($netmask === '0')\n return filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);",
" if ($netmask < 0 || $netmask > 32)\n return false;",
" } else {\n $address = $cidr;\n $netmask = 32;\n }",
" return 0 === substr_compare(\n sprintf('%032b', ip2long($ip)),\n sprintf('%032b', ip2long($address)),\n 0, $netmask);\n }",
" /**\n * Compares two IPv6 addresses.\n * In case a subnet is given, it checks if it contains the request IP.\n *\n * @credit - borrowed from Symfony project\n * @author David Soria Parra <dsp at php dot net>\n *\n * @see https://github.com/dsp/v6tools\n *\n */\n public static function check_ipv6($ip, $cidr) {",
" if (!((extension_loaded('sockets') && defined('AF_INET6')) || @inet_pton('::1')))\n return false;",
" if (false !== strpos($cidr, '/')) {\n list($address, $netmask) = explode('/', $cidr, 2);\n if ($netmask < 1 || $netmask > 128)\n return false;\n } else {\n $address = $cidr;\n $netmask = 128;\n }",
" $bytesAddr = unpack('n*', @inet_pton($address));\n $bytesTest = unpack('n*', @inet_pton($ip));\n if (!$bytesAddr || !$bytesTest)\n return false;",
" for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) {\n $left = $netmask - 16 * ($i - 1);\n $left = ($left <= 16) ? $left : 16;\n $mask = ~(0xffff >> $left) & 0xffff;\n if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {\n return false;\n }\n }",
" return true;\n }",
" function process($fields,$vars,&$errors){",
" $val = new Validator();\n $val->setFields($fields);\n if(!$val->validate($vars))\n $errors=array_merge($errors,$val->errors());",
" return (!$errors);\n }",
" function check_acl($backend) {\n global $cfg;",
" $acl = $cfg->getACL();\n if (empty($acl))\n return true;\n $ip = osTicket::get_client_ip();\n if (empty($ip))\n return false;",
" $aclbk = $cfg->getACLBackend();\n switch($backend) {\n case 'client':\n if (in_array($aclbk, array(0,3)))\n return true;\n break;\n case 'staff':\n if (in_array($aclbk, array(0,2)))\n return true;\n break;\n default:\n return false;\n break;\n }",
" if (!in_array($ip, $acl))\n return false;",
" return true;\n }\n}\n?>"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [870, 1348, 224, 19, 76], "buggy_code_start_loc": [865, 1344, 223, 18, 42], "filenames": ["include/class.staff.php", "include/class.user.php", "include/class.validator.php", "pwreset.php", "scp/pwreset.php"], "fixing_code_end_loc": [870, 1348, 232, 21, 79], "fixing_code_start_loc": [865, 1344, 223, 18, 42], "message": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "2ACCEE58-8958-4EBE-BF9E-37DD119DBD44", "versionEndExcluding": "1.14.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "22F26EC6-59B4-4CCA-9A7E-FD8DD0D0ECE9", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.15", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality."}, {"lang": "es", "value": "Una inyecci\u00f3n SQL en el proceso de inicio de sesi\u00f3n y restablecimiento de contrase\u00f1a de osTicket versiones anteriores a 1.14.8 y 1.15.4, permite a atacantes acceder a la funcionalidad osTicket administration profile"}], "evaluatorComment": null, "id": "CVE-2021-42235", "lastModified": "2022-05-13T17:13:06.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-04T17:15:08.087", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}, "type": "CWE-89"}
| 259
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"require_once('client.inc.php');\nif(!defined('INCLUDE_DIR')) die('Fatal Error');\ndefine('CLIENTINC_DIR',INCLUDE_DIR.'client/');\ndefine('OSTCLIENTINC',TRUE); //make includes happy",
"require_once(INCLUDE_DIR.'class.client.php');",
"$inc = 'pwreset.request.php';\nif($_POST) {\n if (!$ost->checkCSRFToken()) {\n Http::response(400, __('Valid CSRF Token Required'));\n exit;\n }\n switch ($_POST['do']) {\n case 'sendmail':",
" if (($acct=ClientAccount::lookupByUsername($_POST['userid']))) {",
" if (!$acct->isPasswdResetEnabled()) {\n $banner = __('Password reset is not enabled for your account. Contact your administrator');\n }\n elseif ($acct->sendResetEmail()) {\n $inc = 'pwreset.sent.php';\n }\n else\n $banner = __('Unable to send reset email.')\n .' '.__('Internal error occurred');\n }\n else\n $banner = sprintf(__('Unable to verify username %s'),\n Format::htmlchars($_POST['userid']));\n break;\n case 'reset':\n $inc = 'pwreset.login.php';\n $errors = array();\n if ($client = UserAuthenticationBackend::processSignOn($errors)) {\n Http::redirect('index.php');\n }\n elseif (isset($errors['msg'])) {\n $banner = $errors['msg'];\n }\n break;\n }\n}\nelseif ($_GET['token']) {\n $banner = __('Re-enter your username or email');\n $inc = 'pwreset.login.php';\n $_config = new Config('pwreset');\n if (($id = $_config->get($_GET['token']))\n && ($acct = ClientAccount::lookup(array('user_id'=>substr($id,1))))) {\n if (!$acct->isConfirmed()) {\n $inc = 'register.confirmed.inc.php';\n $acct->confirm();\n // FIXME: The account has to be uncached in order for the lookup\n // in the ::processSignOn to detect the confirmation\n ModelInstanceManager::uncache($acct);\n // Log the user in\n if ($client = UserAuthenticationBackend::processSignOn($errors)) {\n if ($acct->hasPassword() && !$acct->get('backend')) {\n $acct->cancelResetTokens();\n }\n // No password setup yet -- force one to be created\n else {\n $_SESSION['_client']['reset-token'] = $_GET['token'];\n $acct->forcePasswdReset();\n }\n Http::redirect('account.php?confirmed');\n }\n }\n }\n elseif ($id && ($user = User::lookup($id)))\n $inc = 'pwreset.create.php';\n else\n Http::redirect('index.php');\n}\nelse {\n $banner = __('Enter your username or email address below');\n}",
"$nav = new UserNav();\n$nav->setActiveNav('status');\nrequire CLIENTINC_DIR.'header.inc.php';\nrequire CLIENTINC_DIR.$inc;\nrequire CLIENTINC_DIR.'footer.inc.php';\n?>"
] |
[
1,
1,
1,
1,
0,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [870, 1348, 224, 19, 76], "buggy_code_start_loc": [865, 1344, 223, 18, 42], "filenames": ["include/class.staff.php", "include/class.user.php", "include/class.validator.php", "pwreset.php", "scp/pwreset.php"], "fixing_code_end_loc": [870, 1348, 232, 21, 79], "fixing_code_start_loc": [865, 1344, 223, 18, 42], "message": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "2ACCEE58-8958-4EBE-BF9E-37DD119DBD44", "versionEndExcluding": "1.14.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "22F26EC6-59B4-4CCA-9A7E-FD8DD0D0ECE9", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.15", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality."}, {"lang": "es", "value": "Una inyecci\u00f3n SQL en el proceso de inicio de sesi\u00f3n y restablecimiento de contrase\u00f1a de osTicket versiones anteriores a 1.14.8 y 1.15.4, permite a atacantes acceder a la funcionalidad osTicket administration profile"}], "evaluatorComment": null, "id": "CVE-2021-42235", "lastModified": "2022-05-13T17:13:06.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-04T17:15:08.087", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}, "type": "CWE-89"}
| 259
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"require_once('client.inc.php');\nif(!defined('INCLUDE_DIR')) die('Fatal Error');\ndefine('CLIENTINC_DIR',INCLUDE_DIR.'client/');\ndefine('OSTCLIENTINC',TRUE); //make includes happy",
"require_once(INCLUDE_DIR.'class.client.php');",
"$inc = 'pwreset.request.php';\nif($_POST) {\n if (!$ost->checkCSRFToken()) {\n Http::response(400, __('Valid CSRF Token Required'));\n exit;\n }\n switch ($_POST['do']) {\n case 'sendmail':",
" $userid = (string) $_POST['userid'];\n if (Validator::is_userid($userid)\n && ($acct=ClientAccount::lookupByUsername($userid))) {",
" if (!$acct->isPasswdResetEnabled()) {\n $banner = __('Password reset is not enabled for your account. Contact your administrator');\n }\n elseif ($acct->sendResetEmail()) {\n $inc = 'pwreset.sent.php';\n }\n else\n $banner = __('Unable to send reset email.')\n .' '.__('Internal error occurred');\n }\n else\n $banner = sprintf(__('Unable to verify username %s'),\n Format::htmlchars($_POST['userid']));\n break;\n case 'reset':\n $inc = 'pwreset.login.php';\n $errors = array();\n if ($client = UserAuthenticationBackend::processSignOn($errors)) {\n Http::redirect('index.php');\n }\n elseif (isset($errors['msg'])) {\n $banner = $errors['msg'];\n }\n break;\n }\n}\nelseif ($_GET['token']) {\n $banner = __('Re-enter your username or email');\n $inc = 'pwreset.login.php';\n $_config = new Config('pwreset');\n if (($id = $_config->get($_GET['token']))\n && ($acct = ClientAccount::lookup(array('user_id'=>substr($id,1))))) {\n if (!$acct->isConfirmed()) {\n $inc = 'register.confirmed.inc.php';\n $acct->confirm();\n // FIXME: The account has to be uncached in order for the lookup\n // in the ::processSignOn to detect the confirmation\n ModelInstanceManager::uncache($acct);\n // Log the user in\n if ($client = UserAuthenticationBackend::processSignOn($errors)) {\n if ($acct->hasPassword() && !$acct->get('backend')) {\n $acct->cancelResetTokens();\n }\n // No password setup yet -- force one to be created\n else {\n $_SESSION['_client']['reset-token'] = $_GET['token'];\n $acct->forcePasswdReset();\n }\n Http::redirect('account.php?confirmed');\n }\n }\n }\n elseif ($id && ($user = User::lookup($id)))\n $inc = 'pwreset.create.php';\n else\n Http::redirect('index.php');\n}\nelse {\n $banner = __('Enter your username or email address below');\n}",
"$nav = new UserNav();\n$nav->setActiveNav('status');\nrequire CLIENTINC_DIR.'header.inc.php';\nrequire CLIENTINC_DIR.$inc;\nrequire CLIENTINC_DIR.'footer.inc.php';\n?>"
] |
[
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [870, 1348, 224, 19, 76], "buggy_code_start_loc": [865, 1344, 223, 18, 42], "filenames": ["include/class.staff.php", "include/class.user.php", "include/class.validator.php", "pwreset.php", "scp/pwreset.php"], "fixing_code_end_loc": [870, 1348, 232, 21, 79], "fixing_code_start_loc": [865, 1344, 223, 18, 42], "message": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "2ACCEE58-8958-4EBE-BF9E-37DD119DBD44", "versionEndExcluding": "1.14.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "22F26EC6-59B4-4CCA-9A7E-FD8DD0D0ECE9", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.15", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality."}, {"lang": "es", "value": "Una inyecci\u00f3n SQL en el proceso de inicio de sesi\u00f3n y restablecimiento de contrase\u00f1a de osTicket versiones anteriores a 1.14.8 y 1.15.4, permite a atacantes acceder a la funcionalidad osTicket administration profile"}], "evaluatorComment": null, "id": "CVE-2021-42235", "lastModified": "2022-05-13T17:13:06.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-04T17:15:08.087", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}, "type": "CWE-89"}
| 259
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*********************************************************************\n pwreset.php",
" Handles step 2, 3 and 5 of password resetting\n 1. Fail to login (2+ fail login attempts)\n 2. Visit password reset form and enter username or email\n 3. Receive an email with a link and follow it\n 4. Visit password reset form again, with the link\n 5. Enter the username or email address again and login\n 6. Password change is now required, user changes password and\n continues on with the session",
" Peter Rotich <peter@osticket.com>\n Jared Hancock <jared@osticket.com>\n Copyright (c) 2006-2013 osTicket\n http://www.osticket.com",
" Released under the GNU General Public License WITHOUT ANY WARRANTY.\n See LICENSE.TXT for details.",
" vim: expandtab sw=4 ts=4 sts=4:\n**********************************************************************/\nrequire_once('../main.inc.php');\nif(!defined('INCLUDE_DIR')) die('Fatal Error. Kwaheri!');",
"// Bootstrap gettext translations. Since no one is yet logged in, use the\n// system or browser default\nTextDomain::configureForUser();",
"require_once(INCLUDE_DIR.'class.staff.php');\nrequire_once(INCLUDE_DIR.'class.csrf.php');",
"$tpl = 'pwreset.php';\nif($_POST) {\n if (!$ost->checkCSRFToken()) {\n Http::response(400, __('Valid CSRF Token Required'));\n exit;\n }\n switch ($_POST['do']) {\n case 'sendmail':",
" if (($staff=Staff::lookup($_POST['userid']))) {",
" if (!$staff->hasPassword()) {\n if ($staff->sendResetEmail('registration-staff', false) !== false)\n $msg = __('Registration email sent successfully.');\n else\n $msg = __('Unable to reset password. Contact your administrator');\n }\n elseif (!$staff->sendResetEmail()) {\n $tpl = 'pwreset.sent.php';\n }\n }\n else\n $msg = sprintf(__('Unable to verify username %s'),\n Format::htmlchars($_POST['userid']));\n break;\n case 'newpasswd':\n // TODO: Compare passwords\n $tpl = 'pwreset.login.php';\n $errors = array();\n if ($staff = StaffAuthenticationBackend::processSignOn($errors)) {\n $info = array('page' => 'index.php');\n Http::redirect($info['page']);\n }\n elseif (isset($errors['msg'])) {\n $msg = $errors['msg'];\n }\n break;\n }\n}\nelseif ($_GET['token']) {\n $msg = __('Please enter your username or email');\n $_config = new Config('pwreset');\n if (($id = $_config->get($_GET['token']))",
" && ($staff = Staff::lookup($id)))",
" // TODO: Detect staff confirmation (for welcome email)\n $tpl = 'pwreset.login.php';\n else\n header('Location: index.php');\n}\nelseif ($cfg->allowPasswordReset()) {\n $msg = __('Enter your username or email address below');\n}\nelse {\n $_SESSION['_staff']['auth']['msg']=__('Password resets are disabled');\n return header('Location: index.php');\n}\ndefine(\"OSTSCPINC\",TRUE); //Make includes happy!\ninclude_once(INCLUDE_DIR.'staff/'. $tpl);"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [870, 1348, 224, 19, 76], "buggy_code_start_loc": [865, 1344, 223, 18, 42], "filenames": ["include/class.staff.php", "include/class.user.php", "include/class.validator.php", "pwreset.php", "scp/pwreset.php"], "fixing_code_end_loc": [870, 1348, 232, 21, 79], "fixing_code_start_loc": [865, 1344, 223, 18, 42], "message": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "2ACCEE58-8958-4EBE-BF9E-37DD119DBD44", "versionEndExcluding": "1.14.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "22F26EC6-59B4-4CCA-9A7E-FD8DD0D0ECE9", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.15", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality."}, {"lang": "es", "value": "Una inyecci\u00f3n SQL en el proceso de inicio de sesi\u00f3n y restablecimiento de contrase\u00f1a de osTicket versiones anteriores a 1.14.8 y 1.15.4, permite a atacantes acceder a la funcionalidad osTicket administration profile"}], "evaluatorComment": null, "id": "CVE-2021-42235", "lastModified": "2022-05-13T17:13:06.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-04T17:15:08.087", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}, "type": "CWE-89"}
| 259
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*********************************************************************\n pwreset.php",
" Handles step 2, 3 and 5 of password resetting\n 1. Fail to login (2+ fail login attempts)\n 2. Visit password reset form and enter username or email\n 3. Receive an email with a link and follow it\n 4. Visit password reset form again, with the link\n 5. Enter the username or email address again and login\n 6. Password change is now required, user changes password and\n continues on with the session",
" Peter Rotich <peter@osticket.com>\n Jared Hancock <jared@osticket.com>\n Copyright (c) 2006-2013 osTicket\n http://www.osticket.com",
" Released under the GNU General Public License WITHOUT ANY WARRANTY.\n See LICENSE.TXT for details.",
" vim: expandtab sw=4 ts=4 sts=4:\n**********************************************************************/\nrequire_once('../main.inc.php');\nif(!defined('INCLUDE_DIR')) die('Fatal Error. Kwaheri!');",
"// Bootstrap gettext translations. Since no one is yet logged in, use the\n// system or browser default\nTextDomain::configureForUser();",
"require_once(INCLUDE_DIR.'class.staff.php');\nrequire_once(INCLUDE_DIR.'class.csrf.php');",
"$tpl = 'pwreset.php';\nif($_POST) {\n if (!$ost->checkCSRFToken()) {\n Http::response(400, __('Valid CSRF Token Required'));\n exit;\n }\n switch ($_POST['do']) {\n case 'sendmail':",
" $userid = (string) $_POST['userid'];\n if (Validator::is_userid($userid)\n && ($staff=Staff::lookup($userid))) {",
" if (!$staff->hasPassword()) {\n if ($staff->sendResetEmail('registration-staff', false) !== false)\n $msg = __('Registration email sent successfully.');\n else\n $msg = __('Unable to reset password. Contact your administrator');\n }\n elseif (!$staff->sendResetEmail()) {\n $tpl = 'pwreset.sent.php';\n }\n }\n else\n $msg = sprintf(__('Unable to verify username %s'),\n Format::htmlchars($_POST['userid']));\n break;\n case 'newpasswd':\n // TODO: Compare passwords\n $tpl = 'pwreset.login.php';\n $errors = array();\n if ($staff = StaffAuthenticationBackend::processSignOn($errors)) {\n $info = array('page' => 'index.php');\n Http::redirect($info['page']);\n }\n elseif (isset($errors['msg'])) {\n $msg = $errors['msg'];\n }\n break;\n }\n}\nelseif ($_GET['token']) {\n $msg = __('Please enter your username or email');\n $_config = new Config('pwreset');\n if (($id = $_config->get($_GET['token']))",
" && is_numeric($id)\n && ($staff = Staff::lookup( (int) $id)))",
" // TODO: Detect staff confirmation (for welcome email)\n $tpl = 'pwreset.login.php';\n else\n header('Location: index.php');\n}\nelseif ($cfg->allowPasswordReset()) {\n $msg = __('Enter your username or email address below');\n}\nelse {\n $_SESSION['_staff']['auth']['msg']=__('Password resets are disabled');\n return header('Location: index.php');\n}\ndefine(\"OSTSCPINC\",TRUE); //Make includes happy!\ninclude_once(INCLUDE_DIR.'staff/'. $tpl);"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [870, 1348, 224, 19, 76], "buggy_code_start_loc": [865, 1344, 223, 18, 42], "filenames": ["include/class.staff.php", "include/class.user.php", "include/class.validator.php", "pwreset.php", "scp/pwreset.php"], "fixing_code_end_loc": [870, 1348, 232, 21, 79], "fixing_code_start_loc": [865, 1344, 223, 18, 42], "message": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "2ACCEE58-8958-4EBE-BF9E-37DD119DBD44", "versionEndExcluding": "1.14.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "22F26EC6-59B4-4CCA-9A7E-FD8DD0D0ECE9", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.15", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection in osTicket before 1.14.8 and 1.15.4 login and password reset process allows attackers to access the osTicket administration profile functionality."}, {"lang": "es", "value": "Una inyecci\u00f3n SQL en el proceso de inicio de sesi\u00f3n y restablecimiento de contrase\u00f1a de osTicket versiones anteriores a 1.14.8 y 1.15.4, permite a atacantes acceder a la funcionalidad osTicket administration profile"}], "evaluatorComment": null, "id": "CVE-2021-42235", "lastModified": "2022-05-13T17:13:06.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-04T17:15:08.087", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osTicket/osTicket/commit/e28291022e662ffa754e170c09cade7bdadf3fd9"}, "type": "CWE-89"}
| 259
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\nBased on https://github.com/trevex/golem\nLicensed under the Apache License, Version 2.0\nhttp://www.apache.org/licenses/LICENSE-2.0.html\n*/\npackage main",
"import (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t_ \"expvar\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"",
"\t\"github.com/gorilla/websocket\"\n\t//_ \"github.com/mkevac/debugcharts\"\n\tconf \"github.com/msbranco/goconfig\"\n)",
"type State struct {\n\tmutes map[Userid]time.Time\n\tsubmode bool\n\tsync.RWMutex\n}",
"var (\n\tstate = &State{\n\t\tmutes: make(map[Userid]time.Time),\n\t}\n)",
"var upgrader = websocket.Upgrader{\n\tReadBufferSize: 1024,\n\tWriteBufferSize: 1024,",
"\tCheckOrigin: func(r *http.Request) bool { return true },",
"}",
"const (\n\tWRITETIMEOUT = 10 * time.Second\n\tREADTIMEOUT = time.Minute\n\tPINGINTERVAL = 10 * time.Second\n\tPINGTIMEOUT = 30 * time.Second\n\tMAXMESSAGESIZE = 6144 // 512 max chars in a message, 8bytes per chars possible, plus factor in some protocol overhead\n\tSENDCHANNELSIZE = 16\n\tBROADCASTCHANNELSIZE = 256\n\tDEFAULTBANDURATION = time.Hour\n\tDEFAULTMUTEDURATION = 10 * time.Minute\n)",
"var (\n\tdebuggingenabled = false\n\tDELAY = 300 * time.Millisecond\n\tMAXTHROTTLETIME = 5 * time.Minute\n)",
"func main() {",
"\tc, err := conf.ReadConfigFile(\"settings.cfg\")\n\tif err != nil {\n\t\tnc := conf.NewConfigFile()\n\t\tnc.AddOption(\"default\", \"debug\", \"false\")\n\t\tnc.AddOption(\"default\", \"listenaddress\", \":9998\")\n\t\tnc.AddOption(\"default\", \"maxprocesses\", \"0\")\n\t\tnc.AddOption(\"default\", \"chatdelay\", fmt.Sprintf(\"%d\", 300*time.Millisecond))\n\t\tnc.AddOption(\"default\", \"maxthrottletime\", fmt.Sprintf(\"%d\", 5*time.Minute))",
"\t\tnc.AddSection(\"redis\")\n\t\tnc.AddOption(\"redis\", \"address\", \"localhost:6379\")\n\t\tnc.AddOption(\"redis\", \"database\", \"0\")\n\t\tnc.AddOption(\"redis\", \"password\", \"\")",
"\t\tnc.AddSection(\"database\")\n\t\tnc.AddOption(\"database\", \"type\", \"mysql\")\n\t\tnc.AddOption(\"database\", \"dsn\", \"username:password@tcp(localhost:3306)/destinygg?loc=UTC&parseTime=true&strict=true&timeout=1s&time_zone=\\\"+00:00\\\"\")",
"\t\tnc.AddSection(\"api\")\n\t\tnc.AddOption(\"api\", \"url\", \"http://www.destiny.gg/api\")\n\t\tnc.AddOption(\"api\", \"key\", \"changeme\")",
"\t\tif err := nc.WriteConfigFile(\"settings.cfg\", 0644, \"DestinyChatBackend\"); err != nil {\n\t\t\tlog.Fatal(\"Unable to create settings.cfg: \", err)\n\t\t}\n\t\tif c, err = conf.ReadConfigFile(\"settings.cfg\"); err != nil {\n\t\t\tlog.Fatal(\"Unable to read settings.cfg: \", err)\n\t\t}\n\t}",
"\tdebuggingenabled, _ = c.GetBool(\"default\", \"debug\")\n\taddr, _ := c.GetString(\"default\", \"listenaddress\")\n\tprocesses, _ := c.GetInt64(\"default\", \"maxprocesses\")\n\tdelay, _ := c.GetInt64(\"default\", \"chatdelay\")\n\tmaxthrottletime, _ := c.GetInt64(\"default\", \"maxthrottletime\")\n\tapiurl, _ := c.GetString(\"api\", \"url\")\n\tapikey, _ := c.GetString(\"api\", \"key\")\n\tDELAY = time.Duration(delay)\n\tMAXTHROTTLETIME = time.Duration(maxthrottletime)",
"\tredisaddr, _ := c.GetString(\"redis\", \"address\")\n\tredisdb, _ := c.GetInt64(\"redis\", \"database\")\n\tredispw, _ := c.GetString(\"redis\", \"password\")",
"\tdbtype, _ := c.GetString(\"database\", \"type\")\n\tdbdsn, _ := c.GetString(\"database\", \"dsn\")",
"\tif processes <= 0 {\n\t\tprocesses = int64(runtime.NumCPU())\n\t}\n\truntime.GOMAXPROCS(int(processes))",
"\tstate.load()",
"\tinitApi(apiurl, apikey)\n\tinitRedis(redisaddr, redisdb, redispw)",
"\tinitNamesCache()\n\tinitHub()\n\tinitDatabase(dbtype, dbdsn)",
"\tinitBroadcast(redisdb)\n\tinitBans(redisdb)\n\tinitUsers(redisdb)",
"\thttp.HandleFunc(\"/ws\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"GET\" {\n\t\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\t\treturn\n\t\t}",
"\t\tws, err := upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}",
"\t\tuser, banned, ip := getUserFromWebRequest(r)",
"\t\tif banned {\n\t\t\tws.SetWriteDeadline(time.Now().Add(WRITETIMEOUT))\n\t\t\tws.WriteMessage(websocket.TextMessage, []byte(`ERR \"banned\"`))\n\t\t\treturn\n\t\t}",
"\t\tnewConnection(ws, user, ip)\n\t})",
"\tfmt.Printf(\"Using %v threads, and listening on: %v\\n\", processes, addr)\n\tif err := http.ListenAndServe(addr, nil); err != nil {\n\t\tlog.Fatal(\"ListenAndServe: \", err)\n\t}\n}",
"func unixMilliTime() int64 {\n\treturn time.Now().UTC().Truncate(time.Millisecond).UnixNano() / int64(time.Millisecond)\n}",
"// expecting the argument to be in UTC\nfunc isExpiredUTC(t time.Time) bool {\n\treturn t.Before(time.Now().UTC())\n}",
"func addDurationUTC(d time.Duration) time.Time {\n\treturn time.Now().UTC().Add(d)\n}",
"func getFuturetimeUTC() time.Time {\n\treturn time.Date(2030, time.January, 1, 0, 0, 0, 0, time.UTC)\n}",
"func (s *State) load() {\n\ts.Lock()\n\tdefer s.Unlock()",
"\tb, err := ioutil.ReadFile(\".state.dc\")\n\tif err != nil {\n\t\tD(\"Error while reading from states file\", err)\n\t\treturn\n\t}\n\tmb := bytes.NewBuffer(b)\n\tdec := gob.NewDecoder(mb)\n\terr = dec.Decode(&s.mutes)\n\tif err != nil {\n\t\tD(\"Error decoding mutes from states file\", err)\n\t}\n\terr = dec.Decode(&s.submode)\n\tif err != nil {\n\t\tD(\"Error decoding submode from states file\", err)\n\t}\n}",
"// expects to be called with locks held\nfunc (s *State) save() {\n\tmb := new(bytes.Buffer)\n\tenc := gob.NewEncoder(mb)\n\terr := enc.Encode(&s.mutes)\n\tif err != nil {\n\t\tD(\"Error encoding mutes:\", err)\n\t}\n\terr = enc.Encode(&s.submode)\n\tif err != nil {\n\t\tD(\"Error encoding submode:\", err)\n\t}",
"\terr = ioutil.WriteFile(\".state.dc\", mb.Bytes(), 0600)\n\tif err != nil {\n\t\tD(\"Error with writing out state file:\", err)\n\t}\n}"
] |
[
1,
1,
1,
1,
1,
1,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [41], "buggy_code_start_loc": [40], "filenames": ["main.go"], "fixing_code_end_loc": [39], "fixing_code_start_loc": [39], "message": "** UNSUPPORTED WHEN ASSIGNED ** A vulnerability was found in destiny.gg chat. It has been rated as problematic. This issue affects the function websocket.Upgrader of the file main.go. The manipulation leads to cross-site request forgery. The attack may be initiated remotely. The name of the patch is bebd256fc3063111fb4503ca25e005ebf6e73780. It is recommended to apply a patch to fix this issue. The identifier VDB-216521 was assigned to this vulnerability. NOTE: This vulnerability only affects products that are no longer supported by the maintainer.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:destiny:chat:-:*:*:*:*:*:*:*", "matchCriteriaId": "64343946-C5A2-4697-AFBE-EBA3AC1129AD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "** UNSUPPORTED WHEN ASSIGNED ** A vulnerability was found in destiny.gg chat. It has been rated as problematic. This issue affects the function websocket.Upgrader of the file main.go. The manipulation leads to cross-site request forgery. The attack may be initiated remotely. The name of the patch is bebd256fc3063111fb4503ca25e005ebf6e73780. It is recommended to apply a patch to fix this issue. The identifier VDB-216521 was assigned to this vulnerability. NOTE: This vulnerability only affects products that are no longer supported by the maintainer."}], "evaluatorComment": null, "id": "CVE-2020-36625", "lastModified": "2022-12-28T22:09:13.673", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}]}, "published": "2022-12-22T10:15:09.730", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/destinygg/chat/commit/bebd256fc3063111fb4503ca25e005ebf6e73780"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/destinygg/chat/pull/35"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.216521"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-352"}, {"lang": "en", "value": "CWE-862"}, {"lang": "en", "value": "CWE-863"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/destinygg/chat/commit/bebd256fc3063111fb4503ca25e005ebf6e73780"}, "type": "CWE-352"}
| 260
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\nBased on https://github.com/trevex/golem\nLicensed under the Apache License, Version 2.0\nhttp://www.apache.org/licenses/LICENSE-2.0.html\n*/\npackage main",
"import (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t_ \"expvar\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"",
"\t\"github.com/gorilla/websocket\"\n\t//_ \"github.com/mkevac/debugcharts\"\n\tconf \"github.com/msbranco/goconfig\"\n)",
"type State struct {\n\tmutes map[Userid]time.Time\n\tsubmode bool\n\tsync.RWMutex\n}",
"var (\n\tstate = &State{\n\t\tmutes: make(map[Userid]time.Time),\n\t}\n)",
"var upgrader = websocket.Upgrader{\n\tReadBufferSize: 1024,\n\tWriteBufferSize: 1024,",
"",
"}",
"const (\n\tWRITETIMEOUT = 10 * time.Second\n\tREADTIMEOUT = time.Minute\n\tPINGINTERVAL = 10 * time.Second\n\tPINGTIMEOUT = 30 * time.Second\n\tMAXMESSAGESIZE = 6144 // 512 max chars in a message, 8bytes per chars possible, plus factor in some protocol overhead\n\tSENDCHANNELSIZE = 16\n\tBROADCASTCHANNELSIZE = 256\n\tDEFAULTBANDURATION = time.Hour\n\tDEFAULTMUTEDURATION = 10 * time.Minute\n)",
"var (\n\tdebuggingenabled = false\n\tDELAY = 300 * time.Millisecond\n\tMAXTHROTTLETIME = 5 * time.Minute\n)",
"func main() {",
"\tc, err := conf.ReadConfigFile(\"settings.cfg\")\n\tif err != nil {\n\t\tnc := conf.NewConfigFile()\n\t\tnc.AddOption(\"default\", \"debug\", \"false\")\n\t\tnc.AddOption(\"default\", \"listenaddress\", \":9998\")\n\t\tnc.AddOption(\"default\", \"maxprocesses\", \"0\")\n\t\tnc.AddOption(\"default\", \"chatdelay\", fmt.Sprintf(\"%d\", 300*time.Millisecond))\n\t\tnc.AddOption(\"default\", \"maxthrottletime\", fmt.Sprintf(\"%d\", 5*time.Minute))",
"\t\tnc.AddSection(\"redis\")\n\t\tnc.AddOption(\"redis\", \"address\", \"localhost:6379\")\n\t\tnc.AddOption(\"redis\", \"database\", \"0\")\n\t\tnc.AddOption(\"redis\", \"password\", \"\")",
"\t\tnc.AddSection(\"database\")\n\t\tnc.AddOption(\"database\", \"type\", \"mysql\")\n\t\tnc.AddOption(\"database\", \"dsn\", \"username:password@tcp(localhost:3306)/destinygg?loc=UTC&parseTime=true&strict=true&timeout=1s&time_zone=\\\"+00:00\\\"\")",
"\t\tnc.AddSection(\"api\")\n\t\tnc.AddOption(\"api\", \"url\", \"http://www.destiny.gg/api\")\n\t\tnc.AddOption(\"api\", \"key\", \"changeme\")",
"\t\tif err := nc.WriteConfigFile(\"settings.cfg\", 0644, \"DestinyChatBackend\"); err != nil {\n\t\t\tlog.Fatal(\"Unable to create settings.cfg: \", err)\n\t\t}\n\t\tif c, err = conf.ReadConfigFile(\"settings.cfg\"); err != nil {\n\t\t\tlog.Fatal(\"Unable to read settings.cfg: \", err)\n\t\t}\n\t}",
"\tdebuggingenabled, _ = c.GetBool(\"default\", \"debug\")\n\taddr, _ := c.GetString(\"default\", \"listenaddress\")\n\tprocesses, _ := c.GetInt64(\"default\", \"maxprocesses\")\n\tdelay, _ := c.GetInt64(\"default\", \"chatdelay\")\n\tmaxthrottletime, _ := c.GetInt64(\"default\", \"maxthrottletime\")\n\tapiurl, _ := c.GetString(\"api\", \"url\")\n\tapikey, _ := c.GetString(\"api\", \"key\")\n\tDELAY = time.Duration(delay)\n\tMAXTHROTTLETIME = time.Duration(maxthrottletime)",
"\tredisaddr, _ := c.GetString(\"redis\", \"address\")\n\tredisdb, _ := c.GetInt64(\"redis\", \"database\")\n\tredispw, _ := c.GetString(\"redis\", \"password\")",
"\tdbtype, _ := c.GetString(\"database\", \"type\")\n\tdbdsn, _ := c.GetString(\"database\", \"dsn\")",
"\tif processes <= 0 {\n\t\tprocesses = int64(runtime.NumCPU())\n\t}\n\truntime.GOMAXPROCS(int(processes))",
"\tstate.load()",
"\tinitApi(apiurl, apikey)\n\tinitRedis(redisaddr, redisdb, redispw)",
"\tinitNamesCache()\n\tinitHub()\n\tinitDatabase(dbtype, dbdsn)",
"\tinitBroadcast(redisdb)\n\tinitBans(redisdb)\n\tinitUsers(redisdb)",
"\thttp.HandleFunc(\"/ws\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"GET\" {\n\t\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\t\treturn\n\t\t}",
"\t\tws, err := upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}",
"\t\tuser, banned, ip := getUserFromWebRequest(r)",
"\t\tif banned {\n\t\t\tws.SetWriteDeadline(time.Now().Add(WRITETIMEOUT))\n\t\t\tws.WriteMessage(websocket.TextMessage, []byte(`ERR \"banned\"`))\n\t\t\treturn\n\t\t}",
"\t\tnewConnection(ws, user, ip)\n\t})",
"\tfmt.Printf(\"Using %v threads, and listening on: %v\\n\", processes, addr)\n\tif err := http.ListenAndServe(addr, nil); err != nil {\n\t\tlog.Fatal(\"ListenAndServe: \", err)\n\t}\n}",
"func unixMilliTime() int64 {\n\treturn time.Now().UTC().Truncate(time.Millisecond).UnixNano() / int64(time.Millisecond)\n}",
"// expecting the argument to be in UTC\nfunc isExpiredUTC(t time.Time) bool {\n\treturn t.Before(time.Now().UTC())\n}",
"func addDurationUTC(d time.Duration) time.Time {\n\treturn time.Now().UTC().Add(d)\n}",
"func getFuturetimeUTC() time.Time {\n\treturn time.Date(2030, time.January, 1, 0, 0, 0, 0, time.UTC)\n}",
"func (s *State) load() {\n\ts.Lock()\n\tdefer s.Unlock()",
"\tb, err := ioutil.ReadFile(\".state.dc\")\n\tif err != nil {\n\t\tD(\"Error while reading from states file\", err)\n\t\treturn\n\t}\n\tmb := bytes.NewBuffer(b)\n\tdec := gob.NewDecoder(mb)\n\terr = dec.Decode(&s.mutes)\n\tif err != nil {\n\t\tD(\"Error decoding mutes from states file\", err)\n\t}\n\terr = dec.Decode(&s.submode)\n\tif err != nil {\n\t\tD(\"Error decoding submode from states file\", err)\n\t}\n}",
"// expects to be called with locks held\nfunc (s *State) save() {\n\tmb := new(bytes.Buffer)\n\tenc := gob.NewEncoder(mb)\n\terr := enc.Encode(&s.mutes)\n\tif err != nil {\n\t\tD(\"Error encoding mutes:\", err)\n\t}\n\terr = enc.Encode(&s.submode)\n\tif err != nil {\n\t\tD(\"Error encoding submode:\", err)\n\t}",
"\terr = ioutil.WriteFile(\".state.dc\", mb.Bytes(), 0600)\n\tif err != nil {\n\t\tD(\"Error with writing out state file:\", err)\n\t}\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [41], "buggy_code_start_loc": [40], "filenames": ["main.go"], "fixing_code_end_loc": [39], "fixing_code_start_loc": [39], "message": "** UNSUPPORTED WHEN ASSIGNED ** A vulnerability was found in destiny.gg chat. It has been rated as problematic. This issue affects the function websocket.Upgrader of the file main.go. The manipulation leads to cross-site request forgery. The attack may be initiated remotely. The name of the patch is bebd256fc3063111fb4503ca25e005ebf6e73780. It is recommended to apply a patch to fix this issue. The identifier VDB-216521 was assigned to this vulnerability. NOTE: This vulnerability only affects products that are no longer supported by the maintainer.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:destiny:chat:-:*:*:*:*:*:*:*", "matchCriteriaId": "64343946-C5A2-4697-AFBE-EBA3AC1129AD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "** UNSUPPORTED WHEN ASSIGNED ** A vulnerability was found in destiny.gg chat. It has been rated as problematic. This issue affects the function websocket.Upgrader of the file main.go. The manipulation leads to cross-site request forgery. The attack may be initiated remotely. The name of the patch is bebd256fc3063111fb4503ca25e005ebf6e73780. It is recommended to apply a patch to fix this issue. The identifier VDB-216521 was assigned to this vulnerability. NOTE: This vulnerability only affects products that are no longer supported by the maintainer."}], "evaluatorComment": null, "id": "CVE-2020-36625", "lastModified": "2022-12-28T22:09:13.673", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}]}, "published": "2022-12-22T10:15:09.730", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/destinygg/chat/commit/bebd256fc3063111fb4503ca25e005ebf6e73780"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/destinygg/chat/pull/35"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.216521"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-352"}, {"lang": "en", "value": "CWE-862"}, {"lang": "en", "value": "CWE-863"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/destinygg/chat/commit/bebd256fc3063111fb4503ca25e005ebf6e73780"}, "type": "CWE-352"}
| 260
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Digital Signature Service Protocol Project.\n * Copyright (C) 2013-2016 e-Contract.be BVBA.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License version\n * 3.0 as published by the Free Software Foundation.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, see \n * http://www.gnu.org/licenses/.\n */",
"package be.e_contract.dssp.client;",
"import java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.List;",
"import javax.xml.bind.JAXBContext;\nimport javax.xml.bind.JAXBElement;\nimport javax.xml.bind.JAXBException;\nimport javax.xml.bind.UnmarshalException;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.crypto.MarshalException;\nimport javax.xml.crypto.dsig.XMLSignature;\nimport javax.xml.crypto.dsig.XMLSignatureException;\nimport javax.xml.crypto.dsig.XMLSignatureFactory;\nimport javax.xml.crypto.dsig.dom.DOMValidateContext;\nimport javax.xml.namespace.QName;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;",
"import org.apache.xml.security.exceptions.Base64DecodingException;\nimport org.apache.xml.security.utils.Base64;\nimport org.joda.time.DateTime;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.NodeList;\nimport org.xml.sax.SAXException;",
"",
"\nimport be.e_contract.dssp.client.exception.ClientRuntimeException;\nimport be.e_contract.dssp.client.exception.SubjectNotAuthorizedException;\nimport be.e_contract.dssp.client.exception.UserCancelException;\nimport be.e_contract.dssp.client.impl.SecurityTokenKeySelector;\nimport be.e_contract.dssp.ws.DigitalSignatureServiceConstants;\nimport be.e_contract.dssp.ws.jaxb.dss.AnyType;\nimport be.e_contract.dssp.ws.jaxb.dss.ObjectFactory;\nimport be.e_contract.dssp.ws.jaxb.dss.Result;\nimport be.e_contract.dssp.ws.jaxb.dss.SignResponse;\nimport be.e_contract.dssp.ws.jaxb.saml.protocol.NameIdentifierType;\nimport be.e_contract.dssp.ws.jaxb.wsa.AttributedURIType;\nimport be.e_contract.dssp.ws.jaxb.wsa.RelatesToType;\nimport be.e_contract.dssp.ws.jaxb.wsu.AttributedDateTime;\nimport be.e_contract.dssp.ws.jaxb.wsu.TimestampType;",
"/**\n * Verifier for browser post dss:SignResponse messages.\n * \n * @author Frank Cornelis\n * \n */\npublic class SignResponseVerifier {",
"\tprivate static final Logger LOGGER = LoggerFactory.getLogger(SignResponseVerifier.class);",
"\tprivate static final QName RESPONSE_ID_QNAME = new QName(\n\t\t\t\"urn:oasis:names:tc:dss:1.0:profiles:asynchronousprocessing:1.0\", \"ResponseID\");",
"\tprivate final static QName TO_QNAME = new QName(\"http://www.w3.org/2005/08/addressing\", \"To\");",
"\tprivate SignResponseVerifier() {\n\t\tsuper();\n\t}",
"\t/**\n\t * Checks the signature on the SignResponse browser POST message.\n\t * \n\t * @param signResponseMessage\n\t * the SignResponse message.\n\t * @param session\n\t * the session object.\n\t * @return the verification result object.\n\t * @throws JAXBException\n\t * @throws ParserConfigurationException\n\t * @throws SAXException\n\t * @throws IOException\n\t * @throws MarshalException\n\t * @throws XMLSignatureException\n\t * @throws Base64DecodingException\n\t * @throws UserCancelException\n\t * @throws ClientRuntimeException\n\t * @throws SubjectNotAuthorizedException\n\t */\n\tpublic static SignResponseVerificationResult checkSignResponse(String signResponseMessage,\n\t\t\tDigitalSignatureServiceSession session) throws JAXBException, ParserConfigurationException, SAXException,\n\t\t\tIOException, MarshalException, XMLSignatureException, Base64DecodingException, UserCancelException,\n\t\t\tClientRuntimeException, SubjectNotAuthorizedException {\n\t\tif (null == session) {\n\t\t\tthrow new IllegalArgumentException(\"missing session\");\n\t\t}",
"\t\tbyte[] decodedSignResponseMessage;\n\t\ttry {\n\t\t\tdecodedSignResponseMessage = Base64.decode(signResponseMessage);\n\t\t} catch (Base64DecodingException e) {\n\t\t\tthrow new SecurityException(\"no Base64\");\n\t\t}",
"",
"\t\t// JAXB parsing\n\t\tJAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,\n\t\t\t\tbe.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory.class,\n\t\t\t\tbe.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class, be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class);\n\t\tUnmarshaller unmarshaller = jaxbContext.createUnmarshaller();\n\t\tSignResponse signResponse;\n\t\ttry {",
"\t\t\tsignResponse = (SignResponse) unmarshaller.unmarshal(new ByteArrayInputStream(decodedSignResponseMessage));",
"\t\t} catch (UnmarshalException e) {\n\t\t\tthrow new SecurityException(\"no valid SignResponse XML\");\n\t\t}",
"\n\t\t// DOM parsing\n\t\tDocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();\n\t\tdocumentBuilderFactory.setNamespaceAware(true);\n\t\tDocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();\n\t\tInputStream signResponseInputStream = new ByteArrayInputStream(decodedSignResponseMessage);\n\t\tDocument signResponseDocument = documentBuilder.parse(signResponseInputStream);",
"\n\t\t// signature verification\n\t\tNodeList signatureNodeList = signResponseDocument.getElementsByTagNameNS(\"http://www.w3.org/2000/09/xmldsig#\",\n\t\t\t\t\"Signature\");\n\t\tif (signatureNodeList.getLength() != 1) {\n\t\t\tthrow new SecurityException(\"requires 1 ds:Signature element\");\n\t\t}\n\t\tElement signatureElement = (Element) signatureNodeList.item(0);\n\t\tSecurityTokenKeySelector keySelector = new SecurityTokenKeySelector(session.getKey());\n\t\tDOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);\n\t\tXMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(\"DOM\");\n\t\tXMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);\n\t\tboolean validSignature = xmlSignature.validate(domValidateContext);\n\t\tif (false == validSignature) {\n\t\t\tthrow new SecurityException(\"invalid ds:Signature\");\n\t\t}",
"\t\t// verify content\n\t\tString responseId = null;\n\t\tRelatesToType relatesTo = null;\n\t\tAttributedURIType to = null;\n\t\tTimestampType timestamp = null;\n\t\tString signerIdentity = null;\n\t\tAnyType optionalOutputs = signResponse.getOptionalOutputs();\n\t\tList<Object> optionalOutputsList = optionalOutputs.getAny();\n\t\tfor (Object optionalOutputObject : optionalOutputsList) {\n\t\t\tLOGGER.debug(\"optional output object type: {}\", optionalOutputObject.getClass().getName());\n\t\t\tif (optionalOutputObject instanceof JAXBElement) {\n\t\t\t\tJAXBElement optionalOutputElement = (JAXBElement) optionalOutputObject;\n\t\t\t\tLOGGER.debug(\"optional output name: {}\", optionalOutputElement.getName());\n\t\t\t\tLOGGER.debug(\"optional output value type: {}\", optionalOutputElement.getValue().getClass().getName());\n\t\t\t\tif (RESPONSE_ID_QNAME.equals(optionalOutputElement.getName())) {\n\t\t\t\t\tresponseId = (String) optionalOutputElement.getValue();\n\t\t\t\t} else if (optionalOutputElement.getValue() instanceof RelatesToType) {\n\t\t\t\t\trelatesTo = (RelatesToType) optionalOutputElement.getValue();\n\t\t\t\t} else if (TO_QNAME.equals(optionalOutputElement.getName())) {\n\t\t\t\t\tto = (AttributedURIType) optionalOutputElement.getValue();\n\t\t\t\t} else if (optionalOutputElement.getValue() instanceof TimestampType) {\n\t\t\t\t\ttimestamp = (TimestampType) optionalOutputElement.getValue();\n\t\t\t\t} else if (optionalOutputElement.getValue() instanceof NameIdentifierType) {\n\t\t\t\t\tNameIdentifierType nameIdentifier = (NameIdentifierType) optionalOutputElement.getValue();\n\t\t\t\t\tsignerIdentity = nameIdentifier.getValue();\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\tResult result = signResponse.getResult();\n\t\tLOGGER.debug(\"result major: {}\", result.getResultMajor());\n\t\tLOGGER.debug(\"result minor: {}\", result.getResultMinor());\n\t\tif (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(result.getResultMajor())) {\n\t\t\tif (DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR.equals(result.getResultMinor())) {\n\t\t\t\tthrow new UserCancelException();\n\t\t\t}\n\t\t\tif (DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR.equals(result.getResultMinor())) {\n\t\t\t\tthrow new ClientRuntimeException();\n\t\t\t}\n\t\t\tif (DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR.equals(result.getResultMinor())) {\n\t\t\t\tthrow new SubjectNotAuthorizedException(signerIdentity);\n\t\t\t}\n\t\t}\n\t\tif (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(result.getResultMajor())) {\n\t\t\tthrow new SecurityException(\"invalid dss:ResultMajor\");\n\t\t}",
"\t\tif (null == responseId) {\n\t\t\tthrow new SecurityException(\"missing async:ResponseID\");\n\t\t}\n\t\tif (false == responseId.equals(session.getResponseId())) {\n\t\t\tthrow new SecurityException(\"invalid async:ResponseID\");\n\t\t}",
"\t\tif (null == relatesTo) {\n\t\t\tthrow new SecurityException(\"missing wsa:RelatesTo\");\n\t\t}\n\t\tif (false == session.getInResponseTo().equals(relatesTo.getValue())) {\n\t\t\tthrow new SecurityException(\"invalid wsa:RelatesTo\");\n\t\t}",
"\t\tif (null == to) {\n\t\t\tthrow new SecurityException(\"missing wsa:To\");\n\t\t}\n\t\tif (false == session.getDestination().equals(to.getValue())) {\n\t\t\tthrow new SecurityException(\"invalid wsa:To\");\n\t\t}",
"\t\tif (null == timestamp) {\n\t\t\tthrow new SecurityException(\"missing wsu:Timestamp\");\n\t\t}\n\t\tAttributedDateTime expires = timestamp.getExpires();\n\t\tif (null == expires) {\n\t\t\tthrow new SecurityException(\"missing wsu:Timestamp/wsu:Expires\");\n\t\t}\n\t\tDateTime expiresDateTime = new DateTime(expires.getValue());\n\t\tDateTime now = new DateTime();\n\t\tif (now.isAfter(expiresDateTime)) {\n\t\t\tthrow new SecurityException(\"wsu:Timestamp expired\");\n\t\t}",
"\t\tsession.setSignResponseVerified(true);",
"\t\tSignResponseVerificationResult signResponseVerificationResult = new SignResponseVerificationResult(\n\t\t\t\tsignerIdentity);\n\t\treturn signResponseVerificationResult;\n\t}\n}"
] |
[
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [136, 70], "buggy_code_start_loc": [49, 30], "filenames": ["dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java", "dssp-client/src/main/java/be/e_contract/dssp/client/metadata/DigitalSignatureServiceMetadata.java"], "fixing_code_end_loc": [143, 82], "fixing_code_start_loc": [50, 31], "message": "A vulnerability classified as problematic was found in e-Contract dssp up to 1.3.1. Affected by this vulnerability is the function checkSignResponse of the file dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java. The manipulation leads to xml external entity reference. Upgrading to version 1.3.2 is able to address this issue. The name of the patch is ec4238349691ec66dd30b416ec6eaab02d722302. It is recommended to upgrade the affected component. The identifier VDB-217549 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:e-contract:dssp:*:*:*:*:*:*:*:*", "matchCriteriaId": "86A4BE0D-3C46-45CA-8C27-40CAA1320099", "versionEndExcluding": "1.3.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic was found in e-Contract dssp up to 1.3.1. Affected by this vulnerability is the function checkSignResponse of the file dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java. The manipulation leads to xml external entity reference. Upgrading to version 1.3.2 is able to address this issue. The name of the patch is ec4238349691ec66dd30b416ec6eaab02d722302. It is recommended to upgrade the affected component. The identifier VDB-217549 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2016-15011", "lastModified": "2023-01-12T16:11:35.450", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.9, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.4, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-06T10:15:09.997", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/e-Contract/dssp/commit/ec4238349691ec66dd30b416ec6eaab02d722302"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/e-Contract/dssp/releases/tag/dssp-1.3.2"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217549"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.217549"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/e-Contract/dssp/commit/ec4238349691ec66dd30b416ec6eaab02d722302"}, "type": "CWE-611"}
| 261
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Digital Signature Service Protocol Project.\n * Copyright (C) 2013-2016 e-Contract.be BVBA.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License version\n * 3.0 as published by the Free Software Foundation.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, see \n * http://www.gnu.org/licenses/.\n */",
"package be.e_contract.dssp.client;",
"import java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.List;",
"import javax.xml.bind.JAXBContext;\nimport javax.xml.bind.JAXBElement;\nimport javax.xml.bind.JAXBException;\nimport javax.xml.bind.UnmarshalException;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.crypto.MarshalException;\nimport javax.xml.crypto.dsig.XMLSignature;\nimport javax.xml.crypto.dsig.XMLSignatureException;\nimport javax.xml.crypto.dsig.XMLSignatureFactory;\nimport javax.xml.crypto.dsig.dom.DOMValidateContext;\nimport javax.xml.namespace.QName;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;",
"import org.apache.xml.security.exceptions.Base64DecodingException;\nimport org.apache.xml.security.utils.Base64;\nimport org.joda.time.DateTime;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.NodeList;\nimport org.xml.sax.SAXException;",
"import org.xml.sax.SAXParseException;",
"\nimport be.e_contract.dssp.client.exception.ClientRuntimeException;\nimport be.e_contract.dssp.client.exception.SubjectNotAuthorizedException;\nimport be.e_contract.dssp.client.exception.UserCancelException;\nimport be.e_contract.dssp.client.impl.SecurityTokenKeySelector;\nimport be.e_contract.dssp.ws.DigitalSignatureServiceConstants;\nimport be.e_contract.dssp.ws.jaxb.dss.AnyType;\nimport be.e_contract.dssp.ws.jaxb.dss.ObjectFactory;\nimport be.e_contract.dssp.ws.jaxb.dss.Result;\nimport be.e_contract.dssp.ws.jaxb.dss.SignResponse;\nimport be.e_contract.dssp.ws.jaxb.saml.protocol.NameIdentifierType;\nimport be.e_contract.dssp.ws.jaxb.wsa.AttributedURIType;\nimport be.e_contract.dssp.ws.jaxb.wsa.RelatesToType;\nimport be.e_contract.dssp.ws.jaxb.wsu.AttributedDateTime;\nimport be.e_contract.dssp.ws.jaxb.wsu.TimestampType;",
"/**\n * Verifier for browser post dss:SignResponse messages.\n * \n * @author Frank Cornelis\n * \n */\npublic class SignResponseVerifier {",
"\tprivate static final Logger LOGGER = LoggerFactory.getLogger(SignResponseVerifier.class);",
"\tprivate static final QName RESPONSE_ID_QNAME = new QName(\n\t\t\t\"urn:oasis:names:tc:dss:1.0:profiles:asynchronousprocessing:1.0\", \"ResponseID\");",
"\tprivate final static QName TO_QNAME = new QName(\"http://www.w3.org/2005/08/addressing\", \"To\");",
"\tprivate SignResponseVerifier() {\n\t\tsuper();\n\t}",
"\t/**\n\t * Checks the signature on the SignResponse browser POST message.\n\t * \n\t * @param signResponseMessage\n\t * the SignResponse message.\n\t * @param session\n\t * the session object.\n\t * @return the verification result object.\n\t * @throws JAXBException\n\t * @throws ParserConfigurationException\n\t * @throws SAXException\n\t * @throws IOException\n\t * @throws MarshalException\n\t * @throws XMLSignatureException\n\t * @throws Base64DecodingException\n\t * @throws UserCancelException\n\t * @throws ClientRuntimeException\n\t * @throws SubjectNotAuthorizedException\n\t */\n\tpublic static SignResponseVerificationResult checkSignResponse(String signResponseMessage,\n\t\t\tDigitalSignatureServiceSession session) throws JAXBException, ParserConfigurationException, SAXException,\n\t\t\tIOException, MarshalException, XMLSignatureException, Base64DecodingException, UserCancelException,\n\t\t\tClientRuntimeException, SubjectNotAuthorizedException {\n\t\tif (null == session) {\n\t\t\tthrow new IllegalArgumentException(\"missing session\");\n\t\t}",
"\t\tbyte[] decodedSignResponseMessage;\n\t\ttry {\n\t\t\tdecodedSignResponseMessage = Base64.decode(signResponseMessage);\n\t\t} catch (Base64DecodingException e) {\n\t\t\tthrow new SecurityException(\"no Base64\");\n\t\t}",
"\n\t\t// DOM parsing\n\t\tDocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();\n\t\tdocumentBuilderFactory.setNamespaceAware(true);\n\t\tdocumentBuilderFactory.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true);\n\t\tDocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();\n\t\tInputStream signResponseInputStream = new ByteArrayInputStream(decodedSignResponseMessage);\n\t\tDocument signResponseDocument;\n\t\ttry {\n\t\t\tsignResponseDocument = documentBuilder.parse(signResponseInputStream);\n\t\t} catch (SAXParseException e) {\n\t\t\tthrow new SecurityException(\"no valid SignResponse XML\");\n\t\t}\n",
"\t\t// JAXB parsing\n\t\tJAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,\n\t\t\t\tbe.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory.class,\n\t\t\t\tbe.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class, be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class);\n\t\tUnmarshaller unmarshaller = jaxbContext.createUnmarshaller();\n\t\tSignResponse signResponse;\n\t\ttry {",
"\t\t\tsignResponse = (SignResponse) unmarshaller.unmarshal(signResponseDocument);",
"\t\t} catch (UnmarshalException e) {\n\t\t\tthrow new SecurityException(\"no valid SignResponse XML\");\n\t\t}",
"",
"\n\t\t// signature verification\n\t\tNodeList signatureNodeList = signResponseDocument.getElementsByTagNameNS(\"http://www.w3.org/2000/09/xmldsig#\",\n\t\t\t\t\"Signature\");\n\t\tif (signatureNodeList.getLength() != 1) {\n\t\t\tthrow new SecurityException(\"requires 1 ds:Signature element\");\n\t\t}\n\t\tElement signatureElement = (Element) signatureNodeList.item(0);\n\t\tSecurityTokenKeySelector keySelector = new SecurityTokenKeySelector(session.getKey());\n\t\tDOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);\n\t\tXMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(\"DOM\");\n\t\tXMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);\n\t\tboolean validSignature = xmlSignature.validate(domValidateContext);\n\t\tif (false == validSignature) {\n\t\t\tthrow new SecurityException(\"invalid ds:Signature\");\n\t\t}",
"\t\t// verify content\n\t\tString responseId = null;\n\t\tRelatesToType relatesTo = null;\n\t\tAttributedURIType to = null;\n\t\tTimestampType timestamp = null;\n\t\tString signerIdentity = null;\n\t\tAnyType optionalOutputs = signResponse.getOptionalOutputs();\n\t\tList<Object> optionalOutputsList = optionalOutputs.getAny();\n\t\tfor (Object optionalOutputObject : optionalOutputsList) {\n\t\t\tLOGGER.debug(\"optional output object type: {}\", optionalOutputObject.getClass().getName());\n\t\t\tif (optionalOutputObject instanceof JAXBElement) {\n\t\t\t\tJAXBElement optionalOutputElement = (JAXBElement) optionalOutputObject;\n\t\t\t\tLOGGER.debug(\"optional output name: {}\", optionalOutputElement.getName());\n\t\t\t\tLOGGER.debug(\"optional output value type: {}\", optionalOutputElement.getValue().getClass().getName());\n\t\t\t\tif (RESPONSE_ID_QNAME.equals(optionalOutputElement.getName())) {\n\t\t\t\t\tresponseId = (String) optionalOutputElement.getValue();\n\t\t\t\t} else if (optionalOutputElement.getValue() instanceof RelatesToType) {\n\t\t\t\t\trelatesTo = (RelatesToType) optionalOutputElement.getValue();\n\t\t\t\t} else if (TO_QNAME.equals(optionalOutputElement.getName())) {\n\t\t\t\t\tto = (AttributedURIType) optionalOutputElement.getValue();\n\t\t\t\t} else if (optionalOutputElement.getValue() instanceof TimestampType) {\n\t\t\t\t\ttimestamp = (TimestampType) optionalOutputElement.getValue();\n\t\t\t\t} else if (optionalOutputElement.getValue() instanceof NameIdentifierType) {\n\t\t\t\t\tNameIdentifierType nameIdentifier = (NameIdentifierType) optionalOutputElement.getValue();\n\t\t\t\t\tsignerIdentity = nameIdentifier.getValue();\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\tResult result = signResponse.getResult();\n\t\tLOGGER.debug(\"result major: {}\", result.getResultMajor());\n\t\tLOGGER.debug(\"result minor: {}\", result.getResultMinor());\n\t\tif (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(result.getResultMajor())) {\n\t\t\tif (DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR.equals(result.getResultMinor())) {\n\t\t\t\tthrow new UserCancelException();\n\t\t\t}\n\t\t\tif (DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR.equals(result.getResultMinor())) {\n\t\t\t\tthrow new ClientRuntimeException();\n\t\t\t}\n\t\t\tif (DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR.equals(result.getResultMinor())) {\n\t\t\t\tthrow new SubjectNotAuthorizedException(signerIdentity);\n\t\t\t}\n\t\t}\n\t\tif (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(result.getResultMajor())) {\n\t\t\tthrow new SecurityException(\"invalid dss:ResultMajor\");\n\t\t}",
"\t\tif (null == responseId) {\n\t\t\tthrow new SecurityException(\"missing async:ResponseID\");\n\t\t}\n\t\tif (false == responseId.equals(session.getResponseId())) {\n\t\t\tthrow new SecurityException(\"invalid async:ResponseID\");\n\t\t}",
"\t\tif (null == relatesTo) {\n\t\t\tthrow new SecurityException(\"missing wsa:RelatesTo\");\n\t\t}\n\t\tif (false == session.getInResponseTo().equals(relatesTo.getValue())) {\n\t\t\tthrow new SecurityException(\"invalid wsa:RelatesTo\");\n\t\t}",
"\t\tif (null == to) {\n\t\t\tthrow new SecurityException(\"missing wsa:To\");\n\t\t}\n\t\tif (false == session.getDestination().equals(to.getValue())) {\n\t\t\tthrow new SecurityException(\"invalid wsa:To\");\n\t\t}",
"\t\tif (null == timestamp) {\n\t\t\tthrow new SecurityException(\"missing wsu:Timestamp\");\n\t\t}\n\t\tAttributedDateTime expires = timestamp.getExpires();\n\t\tif (null == expires) {\n\t\t\tthrow new SecurityException(\"missing wsu:Timestamp/wsu:Expires\");\n\t\t}\n\t\tDateTime expiresDateTime = new DateTime(expires.getValue());\n\t\tDateTime now = new DateTime();\n\t\tif (now.isAfter(expiresDateTime)) {\n\t\t\tthrow new SecurityException(\"wsu:Timestamp expired\");\n\t\t}",
"\t\tsession.setSignResponseVerified(true);",
"\t\tSignResponseVerificationResult signResponseVerificationResult = new SignResponseVerificationResult(\n\t\t\t\tsignerIdentity);\n\t\treturn signResponseVerificationResult;\n\t}\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [136, 70], "buggy_code_start_loc": [49, 30], "filenames": ["dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java", "dssp-client/src/main/java/be/e_contract/dssp/client/metadata/DigitalSignatureServiceMetadata.java"], "fixing_code_end_loc": [143, 82], "fixing_code_start_loc": [50, 31], "message": "A vulnerability classified as problematic was found in e-Contract dssp up to 1.3.1. Affected by this vulnerability is the function checkSignResponse of the file dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java. The manipulation leads to xml external entity reference. Upgrading to version 1.3.2 is able to address this issue. The name of the patch is ec4238349691ec66dd30b416ec6eaab02d722302. It is recommended to upgrade the affected component. The identifier VDB-217549 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:e-contract:dssp:*:*:*:*:*:*:*:*", "matchCriteriaId": "86A4BE0D-3C46-45CA-8C27-40CAA1320099", "versionEndExcluding": "1.3.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic was found in e-Contract dssp up to 1.3.1. Affected by this vulnerability is the function checkSignResponse of the file dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java. The manipulation leads to xml external entity reference. Upgrading to version 1.3.2 is able to address this issue. The name of the patch is ec4238349691ec66dd30b416ec6eaab02d722302. It is recommended to upgrade the affected component. The identifier VDB-217549 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2016-15011", "lastModified": "2023-01-12T16:11:35.450", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.9, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.4, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-06T10:15:09.997", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/e-Contract/dssp/commit/ec4238349691ec66dd30b416ec6eaab02d722302"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/e-Contract/dssp/releases/tag/dssp-1.3.2"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217549"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.217549"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/e-Contract/dssp/commit/ec4238349691ec66dd30b416ec6eaab02d722302"}, "type": "CWE-611"}
| 261
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Digital Signature Service Protocol Project.\n * Copyright (C) 2016 e-Contract.be BVBA.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License version\n * 3.0 as published by the Free Software Foundation.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, see\n * http://www.gnu.org/licenses/.\n */\npackage be.e_contract.dssp.client.metadata;",
"import java.io.ByteArrayInputStream;\nimport java.io.Serializable;\nimport java.net.URL;\nimport java.security.cert.CertificateFactory;\nimport java.security.cert.X509Certificate;\nimport java.util.List;",
"import javax.xml.bind.JAXBContext;\nimport javax.xml.bind.JAXBElement;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.namespace.QName;",
"",
"\nimport be.e_contract.dssp.ws.jaxb.dssp.DigitalSignatureServiceDescriptorType;\nimport be.e_contract.dssp.ws.jaxb.metadata.EntityDescriptorType;\nimport be.e_contract.dssp.ws.jaxb.metadata.KeyDescriptorType;\nimport be.e_contract.dssp.ws.jaxb.metadata.KeyTypes;\nimport be.e_contract.dssp.ws.jaxb.metadata.ObjectFactory;\nimport be.e_contract.dssp.ws.jaxb.metadata.RoleDescriptorType;\nimport be.e_contract.dssp.ws.jaxb.xmldsig.KeyInfoType;\nimport be.e_contract.dssp.ws.jaxb.xmldsig.X509DataType;",
"/**\n * Digital Signature Service Metadata Consumer. This class is serializable so\n * you can store it within a servlet container's HTTP session.\n *\n * @author Frank Cornelis\n */\npublic class DigitalSignatureServiceMetadata implements Serializable {\n",
"",
"\tprivate final static QName _X509DataTypeX509Certificate_QNAME = new QName(\"http://www.w3.org/2000/09/xmldsig#\",\n\t\t\t\"X509Certificate\");",
"\tprivate final String webServiceAddress;",
"\tprivate final String browserPostAddress;",
"\tprivate final X509Certificate certificate;",
"\t/**\n\t * Main constructor.\n\t * \n\t * @param metadataLocation\n\t * the URL of the DSS metadata document.\n\t * @throws Exception\n\t */\n\tpublic DigitalSignatureServiceMetadata(String metadataLocation) throws Exception {",
"",
"\t\tJAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);\n\t\tUnmarshaller unmarshaller = jaxbContext.createUnmarshaller();\n\t\tJAXBElement<EntityDescriptorType> entityDescriptorElement = (JAXBElement<EntityDescriptorType>) unmarshaller",
"\t\t\t\t.unmarshal(new URL(metadataLocation));",
"\t\tEntityDescriptorType entityDescriptor = entityDescriptorElement.getValue();\n\t\tList<RoleDescriptorType> roleDescriptors = entityDescriptor\n\t\t\t\t.getRoleDescriptorOrIDPSSODescriptorOrSPSSODescriptor();\n\t\tString webServiceAddress = null;\n\t\tString browserPostAddress = null;\n\t\tbyte[] certificateData = null;\n\t\tfor (RoleDescriptorType roleDescriptor : roleDescriptors) {\n\t\t\tif (roleDescriptor instanceof DigitalSignatureServiceDescriptorType) {\n\t\t\t\tDigitalSignatureServiceDescriptorType dssDescriptor = (DigitalSignatureServiceDescriptorType) roleDescriptor;\n\t\t\t\tif (!dssDescriptor.getProtocolSupportEnumeration().contains(\"urn:be:e-contract:dssp\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\twebServiceAddress = dssDescriptor.getWebServiceEndpoint().getEndpointReference().getAddress()\n\t\t\t\t\t\t.getValue();\n\t\t\t\tbrowserPostAddress = dssDescriptor.getBrowserPostEndpoint().getEndpointReference().getAddress()\n\t\t\t\t\t\t.getValue();\n\t\t\t\tList<KeyDescriptorType> keyDescriptors = dssDescriptor.getKeyDescriptor();\n\t\t\t\tfor (KeyDescriptorType keyDescriptor : keyDescriptors) {\n\t\t\t\t\tif (!keyDescriptor.getUse().equals(KeyTypes.SIGNING)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tKeyInfoType keyInfo = keyDescriptor.getKeyInfo();\n\t\t\t\t\tList<Object> keyInfoContent = keyInfo.getContent();\n\t\t\t\t\tfor (Object keyInfoObject : keyInfoContent) {\n\t\t\t\t\t\tif (keyInfoObject instanceof JAXBElement) {\n\t\t\t\t\t\t\tJAXBElement<?> keyInfoElement = (JAXBElement<?>) keyInfoObject;\n\t\t\t\t\t\t\tif (keyInfoElement.getValue() instanceof X509DataType) {\n\t\t\t\t\t\t\t\tX509DataType x509Data = (X509DataType) keyInfoElement.getValue();\n\t\t\t\t\t\t\t\tList<Object> x509DataContent = x509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName();\n\t\t\t\t\t\t\t\tfor (Object x509DataObject : x509DataContent) {\n\t\t\t\t\t\t\t\t\tif (x509DataObject instanceof JAXBElement) {\n\t\t\t\t\t\t\t\t\t\tJAXBElement<?> x509DataElement = (JAXBElement<?>) x509DataObject;\n\t\t\t\t\t\t\t\t\t\tif (x509DataElement.getName().equals(_X509DataTypeX509Certificate_QNAME)) {\n\t\t\t\t\t\t\t\t\t\t\tcertificateData = (byte[]) x509DataElement.getValue();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.webServiceAddress = webServiceAddress;\n\t\tthis.browserPostAddress = browserPostAddress;\n\t\tif (null != certificateData) {\n\t\t\tCertificateFactory certificateFactory = CertificateFactory.getInstance(\"X.509\");\n\t\t\tthis.certificate = (X509Certificate) certificateFactory\n\t\t\t\t\t.generateCertificate(new ByteArrayInputStream(certificateData));\n\t\t} else {\n\t\t\tthis.certificate = null;\n\t\t}\n\t}",
"\t/**\n\t * Gives back the URL of the DSS SOAP web service.\n\t * \n\t * @return\n\t */\n\tpublic String getWebServiceAddress() {\n\t\treturn this.webServiceAddress;\n\t}",
"\t/**\n\t * Gives back the URL of the DSS Browser POST entry point.\n\t * \n\t * @return\n\t */\n\tpublic String getBrowserPostAddress() {\n\t\treturn this.browserPostAddress;\n\t}",
"\t/**\n\t * Gives back the (optional) DSS signing certificate. This certificate is\n\t * used for signing of attestation SAML assertions by the DSS instance.\n\t * \n\t * @return\n\t */\n\tpublic X509Certificate getCertificate() {\n\t\treturn this.certificate;\n\t}\n}"
] |
[
1,
1,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
0,
1,
0,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [136, 70], "buggy_code_start_loc": [49, 30], "filenames": ["dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java", "dssp-client/src/main/java/be/e_contract/dssp/client/metadata/DigitalSignatureServiceMetadata.java"], "fixing_code_end_loc": [143, 82], "fixing_code_start_loc": [50, 31], "message": "A vulnerability classified as problematic was found in e-Contract dssp up to 1.3.1. Affected by this vulnerability is the function checkSignResponse of the file dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java. The manipulation leads to xml external entity reference. Upgrading to version 1.3.2 is able to address this issue. The name of the patch is ec4238349691ec66dd30b416ec6eaab02d722302. It is recommended to upgrade the affected component. The identifier VDB-217549 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:e-contract:dssp:*:*:*:*:*:*:*:*", "matchCriteriaId": "86A4BE0D-3C46-45CA-8C27-40CAA1320099", "versionEndExcluding": "1.3.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic was found in e-Contract dssp up to 1.3.1. Affected by this vulnerability is the function checkSignResponse of the file dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java. The manipulation leads to xml external entity reference. Upgrading to version 1.3.2 is able to address this issue. The name of the patch is ec4238349691ec66dd30b416ec6eaab02d722302. It is recommended to upgrade the affected component. The identifier VDB-217549 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2016-15011", "lastModified": "2023-01-12T16:11:35.450", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.9, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.4, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-06T10:15:09.997", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/e-Contract/dssp/commit/ec4238349691ec66dd30b416ec6eaab02d722302"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/e-Contract/dssp/releases/tag/dssp-1.3.2"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217549"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.217549"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/e-Contract/dssp/commit/ec4238349691ec66dd30b416ec6eaab02d722302"}, "type": "CWE-611"}
| 261
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Digital Signature Service Protocol Project.\n * Copyright (C) 2016 e-Contract.be BVBA.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License version\n * 3.0 as published by the Free Software Foundation.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, see\n * http://www.gnu.org/licenses/.\n */\npackage be.e_contract.dssp.client.metadata;",
"import java.io.ByteArrayInputStream;\nimport java.io.Serializable;\nimport java.net.URL;\nimport java.security.cert.CertificateFactory;\nimport java.security.cert.X509Certificate;\nimport java.util.List;",
"import javax.xml.bind.JAXBContext;\nimport javax.xml.bind.JAXBElement;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.namespace.QName;",
"import javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;",
"import org.w3c.dom.Document;",
"\nimport be.e_contract.dssp.ws.jaxb.dssp.DigitalSignatureServiceDescriptorType;\nimport be.e_contract.dssp.ws.jaxb.metadata.EntityDescriptorType;\nimport be.e_contract.dssp.ws.jaxb.metadata.KeyDescriptorType;\nimport be.e_contract.dssp.ws.jaxb.metadata.KeyTypes;\nimport be.e_contract.dssp.ws.jaxb.metadata.ObjectFactory;\nimport be.e_contract.dssp.ws.jaxb.metadata.RoleDescriptorType;\nimport be.e_contract.dssp.ws.jaxb.xmldsig.KeyInfoType;\nimport be.e_contract.dssp.ws.jaxb.xmldsig.X509DataType;",
"/**\n * Digital Signature Service Metadata Consumer. This class is serializable so\n * you can store it within a servlet container's HTTP session.\n *\n * @author Frank Cornelis\n */\npublic class DigitalSignatureServiceMetadata implements Serializable {\n",
"\tprivate static final long serialVersionUID = 1L;\n",
"\tprivate final static QName _X509DataTypeX509Certificate_QNAME = new QName(\"http://www.w3.org/2000/09/xmldsig#\",\n\t\t\t\"X509Certificate\");",
"\tprivate final String webServiceAddress;",
"\tprivate final String browserPostAddress;",
"\tprivate final X509Certificate certificate;",
"\t/**\n\t * Main constructor.\n\t * \n\t * @param metadataLocation\n\t * the URL of the DSS metadata document.\n\t * @throws Exception\n\t */\n\tpublic DigitalSignatureServiceMetadata(String metadataLocation) throws Exception {",
"\t\tDocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();\n\t\tdocumentBuilderFactory.setNamespaceAware(true);\n\t\tdocumentBuilderFactory.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true);\n\t\tDocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();\n\t\tDocument document = documentBuilder.parse(new URL(metadataLocation).openStream());\n",
"\t\tJAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);\n\t\tUnmarshaller unmarshaller = jaxbContext.createUnmarshaller();\n\t\tJAXBElement<EntityDescriptorType> entityDescriptorElement = (JAXBElement<EntityDescriptorType>) unmarshaller",
"\t\t\t\t.unmarshal(document);",
"\t\tEntityDescriptorType entityDescriptor = entityDescriptorElement.getValue();\n\t\tList<RoleDescriptorType> roleDescriptors = entityDescriptor\n\t\t\t\t.getRoleDescriptorOrIDPSSODescriptorOrSPSSODescriptor();\n\t\tString webServiceAddress = null;\n\t\tString browserPostAddress = null;\n\t\tbyte[] certificateData = null;\n\t\tfor (RoleDescriptorType roleDescriptor : roleDescriptors) {\n\t\t\tif (roleDescriptor instanceof DigitalSignatureServiceDescriptorType) {\n\t\t\t\tDigitalSignatureServiceDescriptorType dssDescriptor = (DigitalSignatureServiceDescriptorType) roleDescriptor;\n\t\t\t\tif (!dssDescriptor.getProtocolSupportEnumeration().contains(\"urn:be:e-contract:dssp\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\twebServiceAddress = dssDescriptor.getWebServiceEndpoint().getEndpointReference().getAddress()\n\t\t\t\t\t\t.getValue();\n\t\t\t\tbrowserPostAddress = dssDescriptor.getBrowserPostEndpoint().getEndpointReference().getAddress()\n\t\t\t\t\t\t.getValue();\n\t\t\t\tList<KeyDescriptorType> keyDescriptors = dssDescriptor.getKeyDescriptor();\n\t\t\t\tfor (KeyDescriptorType keyDescriptor : keyDescriptors) {\n\t\t\t\t\tif (!keyDescriptor.getUse().equals(KeyTypes.SIGNING)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tKeyInfoType keyInfo = keyDescriptor.getKeyInfo();\n\t\t\t\t\tList<Object> keyInfoContent = keyInfo.getContent();\n\t\t\t\t\tfor (Object keyInfoObject : keyInfoContent) {\n\t\t\t\t\t\tif (keyInfoObject instanceof JAXBElement) {\n\t\t\t\t\t\t\tJAXBElement<?> keyInfoElement = (JAXBElement<?>) keyInfoObject;\n\t\t\t\t\t\t\tif (keyInfoElement.getValue() instanceof X509DataType) {\n\t\t\t\t\t\t\t\tX509DataType x509Data = (X509DataType) keyInfoElement.getValue();\n\t\t\t\t\t\t\t\tList<Object> x509DataContent = x509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName();\n\t\t\t\t\t\t\t\tfor (Object x509DataObject : x509DataContent) {\n\t\t\t\t\t\t\t\t\tif (x509DataObject instanceof JAXBElement) {\n\t\t\t\t\t\t\t\t\t\tJAXBElement<?> x509DataElement = (JAXBElement<?>) x509DataObject;\n\t\t\t\t\t\t\t\t\t\tif (x509DataElement.getName().equals(_X509DataTypeX509Certificate_QNAME)) {\n\t\t\t\t\t\t\t\t\t\t\tcertificateData = (byte[]) x509DataElement.getValue();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.webServiceAddress = webServiceAddress;\n\t\tthis.browserPostAddress = browserPostAddress;\n\t\tif (null != certificateData) {\n\t\t\tCertificateFactory certificateFactory = CertificateFactory.getInstance(\"X.509\");\n\t\t\tthis.certificate = (X509Certificate) certificateFactory\n\t\t\t\t\t.generateCertificate(new ByteArrayInputStream(certificateData));\n\t\t} else {\n\t\t\tthis.certificate = null;\n\t\t}\n\t}",
"\t/**\n\t * Gives back the URL of the DSS SOAP web service.\n\t * \n\t * @return\n\t */\n\tpublic String getWebServiceAddress() {\n\t\treturn this.webServiceAddress;\n\t}",
"\t/**\n\t * Gives back the URL of the DSS Browser POST entry point.\n\t * \n\t * @return\n\t */\n\tpublic String getBrowserPostAddress() {\n\t\treturn this.browserPostAddress;\n\t}",
"\t/**\n\t * Gives back the (optional) DSS signing certificate. This certificate is\n\t * used for signing of attestation SAML assertions by the DSS instance.\n\t * \n\t * @return\n\t */\n\tpublic X509Certificate getCertificate() {\n\t\treturn this.certificate;\n\t}\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [136, 70], "buggy_code_start_loc": [49, 30], "filenames": ["dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java", "dssp-client/src/main/java/be/e_contract/dssp/client/metadata/DigitalSignatureServiceMetadata.java"], "fixing_code_end_loc": [143, 82], "fixing_code_start_loc": [50, 31], "message": "A vulnerability classified as problematic was found in e-Contract dssp up to 1.3.1. Affected by this vulnerability is the function checkSignResponse of the file dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java. The manipulation leads to xml external entity reference. Upgrading to version 1.3.2 is able to address this issue. The name of the patch is ec4238349691ec66dd30b416ec6eaab02d722302. It is recommended to upgrade the affected component. The identifier VDB-217549 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:e-contract:dssp:*:*:*:*:*:*:*:*", "matchCriteriaId": "86A4BE0D-3C46-45CA-8C27-40CAA1320099", "versionEndExcluding": "1.3.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic was found in e-Contract dssp up to 1.3.1. Affected by this vulnerability is the function checkSignResponse of the file dssp-client/src/main/java/be/e_contract/dssp/client/SignResponseVerifier.java. The manipulation leads to xml external entity reference. Upgrading to version 1.3.2 is able to address this issue. The name of the patch is ec4238349691ec66dd30b416ec6eaab02d722302. It is recommended to upgrade the affected component. The identifier VDB-217549 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2016-15011", "lastModified": "2023-01-12T16:11:35.450", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.9, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.4, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-06T10:15:09.997", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/e-Contract/dssp/commit/ec4238349691ec66dd30b416ec6eaab02d722302"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/e-Contract/dssp/releases/tag/dssp-1.3.2"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217549"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.217549"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/e-Contract/dssp/commit/ec4238349691ec66dd30b416ec6eaab02d722302"}, "type": "CWE-611"}
| 261
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Implementation of the security services.\n *\n * Authors : Stephen Smalley, <sds@epoch.ncsc.mil>\n *\t James Morris <jmorris@redhat.com>\n *\n * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>\n *\n *\tSupport for enhanced MLS infrastructure.\n *\tSupport for context based audit filters.\n *\n * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>\n *\n *\tAdded conditional policy language extensions\n *\n * Updated: Hewlett-Packard <paul@paul-moore.com>\n *\n * Added support for NetLabel\n * Added support for the policy capability bitmap\n *\n * Updated: Chad Sellers <csellers@tresys.com>\n *\n * Added validation of kernel classes and permissions\n *\n * Updated: KaiGai Kohei <kaigai@ak.jp.nec.com>\n *\n * Added support for bounds domain and audit messaged on masked permissions\n *\n * Updated: Guido Trentalancia <guido@trentalancia.com>\n *\n * Added support for runtime switching of the policy type\n *\n * Copyright (C) 2008, 2009 NEC Corporation\n * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.\n * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.\n * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC\n * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>\n *\tThis program is free software; you can redistribute it and/or modify\n *\tit under the terms of the GNU General Public License as published by\n *\tthe Free Software Foundation, version 2.\n */\n#include <linux/kernel.h>\n#include <linux/slab.h>\n#include <linux/string.h>\n#include <linux/spinlock.h>\n#include <linux/rcupdate.h>\n#include <linux/errno.h>\n#include <linux/in.h>\n#include <linux/sched.h>\n#include <linux/audit.h>\n#include <linux/mutex.h>\n#include <linux/selinux.h>\n#include <linux/flex_array.h>\n#include <linux/vmalloc.h>\n#include <net/netlabel.h>",
"#include \"flask.h\"\n#include \"avc.h\"\n#include \"avc_ss.h\"\n#include \"security.h\"\n#include \"context.h\"\n#include \"policydb.h\"\n#include \"sidtab.h\"\n#include \"services.h\"\n#include \"conditional.h\"\n#include \"mls.h\"\n#include \"objsec.h\"\n#include \"netlabel.h\"\n#include \"xfrm.h\"\n#include \"ebitmap.h\"\n#include \"audit.h\"",
"int selinux_policycap_netpeer;\nint selinux_policycap_openperm;\nint selinux_policycap_alwaysnetwork;",
"static DEFINE_RWLOCK(policy_rwlock);",
"static struct sidtab sidtab;\nstruct policydb policydb;\nint ss_initialized;",
"/*\n * The largest sequence number that has been used when\n * providing an access decision to the access vector cache.\n * The sequence number only changes when a policy change\n * occurs.\n */\nstatic u32 latest_granting;",
"/* Forward declaration. */\nstatic int context_struct_to_string(struct context *context, char **scontext,\n\t\t\t\t u32 *scontext_len);",
"static void context_struct_compute_av(struct context *scontext,\n\t\t\t\t struct context *tcontext,\n\t\t\t\t u16 tclass,\n\t\t\t\t struct av_decision *avd);",
"struct selinux_mapping {\n\tu16 value; /* policy value */\n\tunsigned num_perms;\n\tu32 perms[sizeof(u32) * 8];\n};",
"static struct selinux_mapping *current_mapping;\nstatic u16 current_mapping_size;",
"static int selinux_set_mapping(struct policydb *pol,\n\t\t\t struct security_class_mapping *map,\n\t\t\t struct selinux_mapping **out_map_p,\n\t\t\t u16 *out_map_size)\n{\n\tstruct selinux_mapping *out_map = NULL;\n\tsize_t size = sizeof(struct selinux_mapping);\n\tu16 i, j;\n\tunsigned k;\n\tbool print_unknown_handle = false;",
"\t/* Find number of classes in the input mapping */\n\tif (!map)\n\t\treturn -EINVAL;\n\ti = 0;\n\twhile (map[i].name)\n\t\ti++;",
"\t/* Allocate space for the class records, plus one for class zero */\n\tout_map = kcalloc(++i, size, GFP_ATOMIC);\n\tif (!out_map)\n\t\treturn -ENOMEM;",
"\t/* Store the raw class and permission values */\n\tj = 0;\n\twhile (map[j].name) {\n\t\tstruct security_class_mapping *p_in = map + (j++);\n\t\tstruct selinux_mapping *p_out = out_map + j;",
"\t\t/* An empty class string skips ahead */\n\t\tif (!strcmp(p_in->name, \"\")) {\n\t\t\tp_out->num_perms = 0;\n\t\t\tcontinue;\n\t\t}",
"\t\tp_out->value = string_to_security_class(pol, p_in->name);\n\t\tif (!p_out->value) {\n\t\t\tprintk(KERN_INFO\n\t\t\t \"SELinux: Class %s not defined in policy.\\n\",\n\t\t\t p_in->name);\n\t\t\tif (pol->reject_unknown)\n\t\t\t\tgoto err;\n\t\t\tp_out->num_perms = 0;\n\t\t\tprint_unknown_handle = true;\n\t\t\tcontinue;\n\t\t}",
"\t\tk = 0;\n\t\twhile (p_in->perms && p_in->perms[k]) {\n\t\t\t/* An empty permission string skips ahead */\n\t\t\tif (!*p_in->perms[k]) {\n\t\t\t\tk++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tp_out->perms[k] = string_to_av_perm(pol, p_out->value,\n\t\t\t\t\t\t\t p_in->perms[k]);\n\t\t\tif (!p_out->perms[k]) {\n\t\t\t\tprintk(KERN_INFO\n\t\t\t\t \"SELinux: Permission %s in class %s not defined in policy.\\n\",\n\t\t\t\t p_in->perms[k], p_in->name);\n\t\t\t\tif (pol->reject_unknown)\n\t\t\t\t\tgoto err;\n\t\t\t\tprint_unknown_handle = true;\n\t\t\t}",
"\t\t\tk++;\n\t\t}\n\t\tp_out->num_perms = k;\n\t}",
"\tif (print_unknown_handle)\n\t\tprintk(KERN_INFO \"SELinux: the above unknown classes and permissions will be %s\\n\",\n\t\t pol->allow_unknown ? \"allowed\" : \"denied\");",
"\t*out_map_p = out_map;\n\t*out_map_size = i;\n\treturn 0;\nerr:\n\tkfree(out_map);\n\treturn -EINVAL;\n}",
"/*\n * Get real, policy values from mapped values\n */",
"static u16 unmap_class(u16 tclass)\n{\n\tif (tclass < current_mapping_size)\n\t\treturn current_mapping[tclass].value;",
"\treturn tclass;\n}",
"/*\n * Get kernel value for class from its policy value\n */\nstatic u16 map_class(u16 pol_value)\n{\n\tu16 i;",
"\tfor (i = 1; i < current_mapping_size; i++) {\n\t\tif (current_mapping[i].value == pol_value)\n\t\t\treturn i;\n\t}",
"\treturn SECCLASS_NULL;\n}",
"static void map_decision(u16 tclass, struct av_decision *avd,\n\t\t\t int allow_unknown)\n{\n\tif (tclass < current_mapping_size) {\n\t\tunsigned i, n = current_mapping[tclass].num_perms;\n\t\tu32 result;",
"\t\tfor (i = 0, result = 0; i < n; i++) {\n\t\t\tif (avd->allowed & current_mapping[tclass].perms[i])\n\t\t\t\tresult |= 1<<i;\n\t\t\tif (allow_unknown && !current_mapping[tclass].perms[i])\n\t\t\t\tresult |= 1<<i;\n\t\t}\n\t\tavd->allowed = result;",
"\t\tfor (i = 0, result = 0; i < n; i++)\n\t\t\tif (avd->auditallow & current_mapping[tclass].perms[i])\n\t\t\t\tresult |= 1<<i;\n\t\tavd->auditallow = result;",
"\t\tfor (i = 0, result = 0; i < n; i++) {\n\t\t\tif (avd->auditdeny & current_mapping[tclass].perms[i])\n\t\t\t\tresult |= 1<<i;\n\t\t\tif (!allow_unknown && !current_mapping[tclass].perms[i])\n\t\t\t\tresult |= 1<<i;\n\t\t}\n\t\t/*\n\t\t * In case the kernel has a bug and requests a permission\n\t\t * between num_perms and the maximum permission number, we\n\t\t * should audit that denial\n\t\t */\n\t\tfor (; i < (sizeof(u32)*8); i++)\n\t\t\tresult |= 1<<i;\n\t\tavd->auditdeny = result;\n\t}\n}",
"int security_mls_enabled(void)\n{\n\treturn policydb.mls_enabled;\n}",
"/*\n * Return the boolean value of a constraint expression\n * when it is applied to the specified source and target\n * security contexts.\n *\n * xcontext is a special beast... It is used by the validatetrans rules\n * only. For these rules, scontext is the context before the transition,\n * tcontext is the context after the transition, and xcontext is the context\n * of the process performing the transition. All other callers of\n * constraint_expr_eval should pass in NULL for xcontext.\n */\nstatic int constraint_expr_eval(struct context *scontext,\n\t\t\t\tstruct context *tcontext,\n\t\t\t\tstruct context *xcontext,\n\t\t\t\tstruct constraint_expr *cexpr)\n{\n\tu32 val1, val2;\n\tstruct context *c;\n\tstruct role_datum *r1, *r2;\n\tstruct mls_level *l1, *l2;\n\tstruct constraint_expr *e;\n\tint s[CEXPR_MAXDEPTH];\n\tint sp = -1;",
"\tfor (e = cexpr; e; e = e->next) {\n\t\tswitch (e->expr_type) {\n\t\tcase CEXPR_NOT:\n\t\t\tBUG_ON(sp < 0);\n\t\t\ts[sp] = !s[sp];\n\t\t\tbreak;\n\t\tcase CEXPR_AND:\n\t\t\tBUG_ON(sp < 1);\n\t\t\tsp--;\n\t\t\ts[sp] &= s[sp + 1];\n\t\t\tbreak;\n\t\tcase CEXPR_OR:\n\t\t\tBUG_ON(sp < 1);\n\t\t\tsp--;\n\t\t\ts[sp] |= s[sp + 1];\n\t\t\tbreak;\n\t\tcase CEXPR_ATTR:\n\t\t\tif (sp == (CEXPR_MAXDEPTH - 1))\n\t\t\t\treturn 0;\n\t\t\tswitch (e->attr) {\n\t\t\tcase CEXPR_USER:\n\t\t\t\tval1 = scontext->user;\n\t\t\t\tval2 = tcontext->user;\n\t\t\t\tbreak;\n\t\t\tcase CEXPR_TYPE:\n\t\t\t\tval1 = scontext->type;\n\t\t\t\tval2 = tcontext->type;\n\t\t\t\tbreak;\n\t\t\tcase CEXPR_ROLE:\n\t\t\t\tval1 = scontext->role;\n\t\t\t\tval2 = tcontext->role;\n\t\t\t\tr1 = policydb.role_val_to_struct[val1 - 1];\n\t\t\t\tr2 = policydb.role_val_to_struct[val2 - 1];\n\t\t\t\tswitch (e->op) {\n\t\t\t\tcase CEXPR_DOM:\n\t\t\t\t\ts[++sp] = ebitmap_get_bit(&r1->dominates,\n\t\t\t\t\t\t\t\t val2 - 1);\n\t\t\t\t\tcontinue;\n\t\t\t\tcase CEXPR_DOMBY:\n\t\t\t\t\ts[++sp] = ebitmap_get_bit(&r2->dominates,\n\t\t\t\t\t\t\t\t val1 - 1);\n\t\t\t\t\tcontinue;\n\t\t\t\tcase CEXPR_INCOMP:\n\t\t\t\t\ts[++sp] = (!ebitmap_get_bit(&r1->dominates,\n\t\t\t\t\t\t\t\t val2 - 1) &&\n\t\t\t\t\t\t !ebitmap_get_bit(&r2->dominates,\n\t\t\t\t\t\t\t\t val1 - 1));\n\t\t\t\t\tcontinue;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CEXPR_L1L2:\n\t\t\t\tl1 = &(scontext->range.level[0]);\n\t\t\t\tl2 = &(tcontext->range.level[0]);\n\t\t\t\tgoto mls_ops;\n\t\t\tcase CEXPR_L1H2:\n\t\t\t\tl1 = &(scontext->range.level[0]);\n\t\t\t\tl2 = &(tcontext->range.level[1]);\n\t\t\t\tgoto mls_ops;\n\t\t\tcase CEXPR_H1L2:\n\t\t\t\tl1 = &(scontext->range.level[1]);\n\t\t\t\tl2 = &(tcontext->range.level[0]);\n\t\t\t\tgoto mls_ops;\n\t\t\tcase CEXPR_H1H2:\n\t\t\t\tl1 = &(scontext->range.level[1]);\n\t\t\t\tl2 = &(tcontext->range.level[1]);\n\t\t\t\tgoto mls_ops;\n\t\t\tcase CEXPR_L1H1:\n\t\t\t\tl1 = &(scontext->range.level[0]);\n\t\t\t\tl2 = &(scontext->range.level[1]);\n\t\t\t\tgoto mls_ops;\n\t\t\tcase CEXPR_L2H2:\n\t\t\t\tl1 = &(tcontext->range.level[0]);\n\t\t\t\tl2 = &(tcontext->range.level[1]);\n\t\t\t\tgoto mls_ops;\nmls_ops:\n\t\t\tswitch (e->op) {\n\t\t\tcase CEXPR_EQ:\n\t\t\t\ts[++sp] = mls_level_eq(l1, l2);\n\t\t\t\tcontinue;\n\t\t\tcase CEXPR_NEQ:\n\t\t\t\ts[++sp] = !mls_level_eq(l1, l2);\n\t\t\t\tcontinue;\n\t\t\tcase CEXPR_DOM:\n\t\t\t\ts[++sp] = mls_level_dom(l1, l2);\n\t\t\t\tcontinue;\n\t\t\tcase CEXPR_DOMBY:\n\t\t\t\ts[++sp] = mls_level_dom(l2, l1);\n\t\t\t\tcontinue;\n\t\t\tcase CEXPR_INCOMP:\n\t\t\t\ts[++sp] = mls_level_incomp(l2, l1);\n\t\t\t\tcontinue;\n\t\t\tdefault:\n\t\t\t\tBUG();\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tBUG();\n\t\t\t\treturn 0;\n\t\t\t}",
"\t\t\tswitch (e->op) {\n\t\t\tcase CEXPR_EQ:\n\t\t\t\ts[++sp] = (val1 == val2);\n\t\t\t\tbreak;\n\t\t\tcase CEXPR_NEQ:\n\t\t\t\ts[++sp] = (val1 != val2);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tBUG();\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CEXPR_NAMES:\n\t\t\tif (sp == (CEXPR_MAXDEPTH-1))\n\t\t\t\treturn 0;\n\t\t\tc = scontext;\n\t\t\tif (e->attr & CEXPR_TARGET)\n\t\t\t\tc = tcontext;\n\t\t\telse if (e->attr & CEXPR_XTARGET) {\n\t\t\t\tc = xcontext;\n\t\t\t\tif (!c) {\n\t\t\t\t\tBUG();\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (e->attr & CEXPR_USER)\n\t\t\t\tval1 = c->user;\n\t\t\telse if (e->attr & CEXPR_ROLE)\n\t\t\t\tval1 = c->role;\n\t\t\telse if (e->attr & CEXPR_TYPE)\n\t\t\t\tval1 = c->type;\n\t\t\telse {\n\t\t\t\tBUG();\n\t\t\t\treturn 0;\n\t\t\t}",
"\t\t\tswitch (e->op) {\n\t\t\tcase CEXPR_EQ:\n\t\t\t\ts[++sp] = ebitmap_get_bit(&e->names, val1 - 1);\n\t\t\t\tbreak;\n\t\t\tcase CEXPR_NEQ:\n\t\t\t\ts[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tBUG();\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tBUG();\n\t\t\treturn 0;\n\t\t}\n\t}",
"\tBUG_ON(sp != 0);\n\treturn s[0];\n}",
"/*\n * security_dump_masked_av - dumps masked permissions during\n * security_compute_av due to RBAC, MLS/Constraint and Type bounds.\n */\nstatic int dump_masked_av_helper(void *k, void *d, void *args)\n{\n\tstruct perm_datum *pdatum = d;\n\tchar **permission_names = args;",
"\tBUG_ON(pdatum->value < 1 || pdatum->value > 32);",
"\tpermission_names[pdatum->value - 1] = (char *)k;",
"\treturn 0;\n}",
"static void security_dump_masked_av(struct context *scontext,\n\t\t\t\t struct context *tcontext,\n\t\t\t\t u16 tclass,\n\t\t\t\t u32 permissions,\n\t\t\t\t const char *reason)\n{\n\tstruct common_datum *common_dat;\n\tstruct class_datum *tclass_dat;\n\tstruct audit_buffer *ab;\n\tchar *tclass_name;\n\tchar *scontext_name = NULL;\n\tchar *tcontext_name = NULL;\n\tchar *permission_names[32];\n\tint index;\n\tu32 length;\n\tbool need_comma = false;",
"\tif (!permissions)\n\t\treturn;",
"\ttclass_name = sym_name(&policydb, SYM_CLASSES, tclass - 1);\n\ttclass_dat = policydb.class_val_to_struct[tclass - 1];\n\tcommon_dat = tclass_dat->comdatum;",
"\t/* init permission_names */\n\tif (common_dat &&\n\t hashtab_map(common_dat->permissions.table,\n\t\t\tdump_masked_av_helper, permission_names) < 0)\n\t\tgoto out;",
"\tif (hashtab_map(tclass_dat->permissions.table,\n\t\t\tdump_masked_av_helper, permission_names) < 0)\n\t\tgoto out;",
"\t/* get scontext/tcontext in text form */\n\tif (context_struct_to_string(scontext,\n\t\t\t\t &scontext_name, &length) < 0)\n\t\tgoto out;",
"\tif (context_struct_to_string(tcontext,\n\t\t\t\t &tcontext_name, &length) < 0)\n\t\tgoto out;",
"\t/* audit a message */\n\tab = audit_log_start(current->audit_context,\n\t\t\t GFP_ATOMIC, AUDIT_SELINUX_ERR);\n\tif (!ab)\n\t\tgoto out;",
"\taudit_log_format(ab, \"op=security_compute_av reason=%s \"\n\t\t\t \"scontext=%s tcontext=%s tclass=%s perms=\",\n\t\t\t reason, scontext_name, tcontext_name, tclass_name);",
"\tfor (index = 0; index < 32; index++) {\n\t\tu32 mask = (1 << index);",
"\t\tif ((mask & permissions) == 0)\n\t\t\tcontinue;",
"\t\taudit_log_format(ab, \"%s%s\",\n\t\t\t\t need_comma ? \",\" : \"\",\n\t\t\t\t permission_names[index]\n\t\t\t\t ? permission_names[index] : \"????\");\n\t\tneed_comma = true;\n\t}\n\taudit_log_end(ab);\nout:\n\t/* release scontext/tcontext */\n\tkfree(tcontext_name);\n\tkfree(scontext_name);",
"\treturn;\n}",
"/*\n * security_boundary_permission - drops violated permissions\n * on boundary constraint.\n */\nstatic void type_attribute_bounds_av(struct context *scontext,\n\t\t\t\t struct context *tcontext,\n\t\t\t\t u16 tclass,\n\t\t\t\t struct av_decision *avd)\n{\n\tstruct context lo_scontext;\n\tstruct context lo_tcontext;\n\tstruct av_decision lo_avd;\n\tstruct type_datum *source;\n\tstruct type_datum *target;\n\tu32 masked = 0;",
"\tsource = flex_array_get_ptr(policydb.type_val_to_struct_array,\n\t\t\t\t scontext->type - 1);\n\tBUG_ON(!source);",
"\ttarget = flex_array_get_ptr(policydb.type_val_to_struct_array,\n\t\t\t\t tcontext->type - 1);\n\tBUG_ON(!target);",
"\tif (source->bounds) {\n\t\tmemset(&lo_avd, 0, sizeof(lo_avd));",
"\t\tmemcpy(&lo_scontext, scontext, sizeof(lo_scontext));\n\t\tlo_scontext.type = source->bounds;",
"\t\tcontext_struct_compute_av(&lo_scontext,\n\t\t\t\t\t tcontext,\n\t\t\t\t\t tclass,\n\t\t\t\t\t &lo_avd);\n\t\tif ((lo_avd.allowed & avd->allowed) == avd->allowed)\n\t\t\treturn;\t\t/* no masked permission */\n\t\tmasked = ~lo_avd.allowed & avd->allowed;\n\t}",
"\tif (target->bounds) {\n\t\tmemset(&lo_avd, 0, sizeof(lo_avd));",
"\t\tmemcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));\n\t\tlo_tcontext.type = target->bounds;",
"\t\tcontext_struct_compute_av(scontext,\n\t\t\t\t\t &lo_tcontext,\n\t\t\t\t\t tclass,\n\t\t\t\t\t &lo_avd);\n\t\tif ((lo_avd.allowed & avd->allowed) == avd->allowed)\n\t\t\treturn;\t\t/* no masked permission */\n\t\tmasked = ~lo_avd.allowed & avd->allowed;\n\t}",
"\tif (source->bounds && target->bounds) {\n\t\tmemset(&lo_avd, 0, sizeof(lo_avd));\n\t\t/*\n\t\t * lo_scontext and lo_tcontext are already\n\t\t * set up.\n\t\t */",
"\t\tcontext_struct_compute_av(&lo_scontext,\n\t\t\t\t\t &lo_tcontext,\n\t\t\t\t\t tclass,\n\t\t\t\t\t &lo_avd);\n\t\tif ((lo_avd.allowed & avd->allowed) == avd->allowed)\n\t\t\treturn;\t\t/* no masked permission */\n\t\tmasked = ~lo_avd.allowed & avd->allowed;\n\t}",
"\tif (masked) {\n\t\t/* mask violated permissions */\n\t\tavd->allowed &= ~masked;",
"\t\t/* audit masked permissions */\n\t\tsecurity_dump_masked_av(scontext, tcontext,\n\t\t\t\t\ttclass, masked, \"bounds\");\n\t}\n}",
"/*\n * Compute access vectors based on a context structure pair for\n * the permissions in a particular class.\n */\nstatic void context_struct_compute_av(struct context *scontext,\n\t\t\t\t struct context *tcontext,\n\t\t\t\t u16 tclass,\n\t\t\t\t struct av_decision *avd)\n{\n\tstruct constraint_node *constraint;\n\tstruct role_allow *ra;\n\tstruct avtab_key avkey;\n\tstruct avtab_node *node;\n\tstruct class_datum *tclass_datum;\n\tstruct ebitmap *sattr, *tattr;\n\tstruct ebitmap_node *snode, *tnode;\n\tunsigned int i, j;",
"\tavd->allowed = 0;\n\tavd->auditallow = 0;\n\tavd->auditdeny = 0xffffffff;",
"\tif (unlikely(!tclass || tclass > policydb.p_classes.nprim)) {\n\t\tif (printk_ratelimit())\n\t\t\tprintk(KERN_WARNING \"SELinux: Invalid class %hu\\n\", tclass);\n\t\treturn;\n\t}",
"\ttclass_datum = policydb.class_val_to_struct[tclass - 1];",
"\t/*\n\t * If a specific type enforcement rule was defined for\n\t * this permission check, then use it.\n\t */\n\tavkey.target_class = tclass;\n\tavkey.specified = AVTAB_AV;\n\tsattr = flex_array_get(policydb.type_attr_map_array, scontext->type - 1);\n\tBUG_ON(!sattr);\n\ttattr = flex_array_get(policydb.type_attr_map_array, tcontext->type - 1);\n\tBUG_ON(!tattr);\n\tebitmap_for_each_positive_bit(sattr, snode, i) {\n\t\tebitmap_for_each_positive_bit(tattr, tnode, j) {\n\t\t\tavkey.source_type = i + 1;\n\t\t\tavkey.target_type = j + 1;\n\t\t\tfor (node = avtab_search_node(&policydb.te_avtab, &avkey);\n\t\t\t node;\n\t\t\t node = avtab_search_node_next(node, avkey.specified)) {\n\t\t\t\tif (node->key.specified == AVTAB_ALLOWED)\n\t\t\t\t\tavd->allowed |= node->datum.data;\n\t\t\t\telse if (node->key.specified == AVTAB_AUDITALLOW)\n\t\t\t\t\tavd->auditallow |= node->datum.data;\n\t\t\t\telse if (node->key.specified == AVTAB_AUDITDENY)\n\t\t\t\t\tavd->auditdeny &= node->datum.data;\n\t\t\t}",
"\t\t\t/* Check conditional av table for additional permissions */\n\t\t\tcond_compute_av(&policydb.te_cond_avtab, &avkey, avd);",
"\t\t}\n\t}",
"\t/*\n\t * Remove any permissions prohibited by a constraint (this includes\n\t * the MLS policy).\n\t */\n\tconstraint = tclass_datum->constraints;\n\twhile (constraint) {\n\t\tif ((constraint->permissions & (avd->allowed)) &&\n\t\t !constraint_expr_eval(scontext, tcontext, NULL,\n\t\t\t\t\t constraint->expr)) {\n\t\t\tavd->allowed &= ~(constraint->permissions);\n\t\t}\n\t\tconstraint = constraint->next;\n\t}",
"\t/*\n\t * If checking process transition permission and the\n\t * role is changing, then check the (current_role, new_role)\n\t * pair.\n\t */\n\tif (tclass == policydb.process_class &&\n\t (avd->allowed & policydb.process_trans_perms) &&\n\t scontext->role != tcontext->role) {\n\t\tfor (ra = policydb.role_allow; ra; ra = ra->next) {\n\t\t\tif (scontext->role == ra->role &&\n\t\t\t tcontext->role == ra->new_role)\n\t\t\t\tbreak;\n\t\t}\n\t\tif (!ra)\n\t\t\tavd->allowed &= ~policydb.process_trans_perms;\n\t}",
"\t/*\n\t * If the given source and target types have boundary\n\t * constraint, lazy checks have to mask any violated\n\t * permission and notice it to userspace via audit.\n\t */\n\ttype_attribute_bounds_av(scontext, tcontext,\n\t\t\t\t tclass, avd);\n}",
"static int security_validtrans_handle_fail(struct context *ocontext,\n\t\t\t\t\t struct context *ncontext,\n\t\t\t\t\t struct context *tcontext,\n\t\t\t\t\t u16 tclass)\n{\n\tchar *o = NULL, *n = NULL, *t = NULL;\n\tu32 olen, nlen, tlen;",
"\tif (context_struct_to_string(ocontext, &o, &olen))\n\t\tgoto out;\n\tif (context_struct_to_string(ncontext, &n, &nlen))\n\t\tgoto out;\n\tif (context_struct_to_string(tcontext, &t, &tlen))\n\t\tgoto out;\n\taudit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t \"security_validate_transition: denied for\"\n\t\t \" oldcontext=%s newcontext=%s taskcontext=%s tclass=%s\",\n\t\t o, n, t, sym_name(&policydb, SYM_CLASSES, tclass-1));\nout:\n\tkfree(o);\n\tkfree(n);\n\tkfree(t);",
"\tif (!selinux_enforcing)\n\t\treturn 0;\n\treturn -EPERM;\n}",
"int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,\n\t\t\t\t u16 orig_tclass)\n{\n\tstruct context *ocontext;\n\tstruct context *ncontext;\n\tstruct context *tcontext;\n\tstruct class_datum *tclass_datum;\n\tstruct constraint_node *constraint;\n\tu16 tclass;\n\tint rc = 0;",
"\tif (!ss_initialized)\n\t\treturn 0;",
"\tread_lock(&policy_rwlock);",
"\ttclass = unmap_class(orig_tclass);",
"\tif (!tclass || tclass > policydb.p_classes.nprim) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized class %d\\n\",\n\t\t\t__func__, tclass);\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}\n\ttclass_datum = policydb.class_val_to_struct[tclass - 1];",
"\tocontext = sidtab_search(&sidtab, oldsid);\n\tif (!ocontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, oldsid);\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}",
"\tncontext = sidtab_search(&sidtab, newsid);\n\tif (!ncontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, newsid);\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}",
"\ttcontext = sidtab_search(&sidtab, tasksid);\n\tif (!tcontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, tasksid);\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}",
"\tconstraint = tclass_datum->validatetrans;\n\twhile (constraint) {\n\t\tif (!constraint_expr_eval(ocontext, ncontext, tcontext,\n\t\t\t\t\t constraint->expr)) {\n\t\t\trc = security_validtrans_handle_fail(ocontext, ncontext,\n\t\t\t\t\t\t\t tcontext, tclass);\n\t\t\tgoto out;\n\t\t}\n\t\tconstraint = constraint->next;\n\t}",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"/*\n * security_bounded_transition - check whether the given\n * transition is directed to bounded, or not.\n * It returns 0, if @newsid is bounded by @oldsid.\n * Otherwise, it returns error code.\n *\n * @oldsid : current security identifier\n * @newsid : destinated security identifier\n */\nint security_bounded_transition(u32 old_sid, u32 new_sid)\n{\n\tstruct context *old_context, *new_context;\n\tstruct type_datum *type;\n\tint index;\n\tint rc;",
"\tread_lock(&policy_rwlock);",
"\trc = -EINVAL;\n\told_context = sidtab_search(&sidtab, old_sid);\n\tif (!old_context) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %u\\n\",\n\t\t __func__, old_sid);\n\t\tgoto out;\n\t}",
"\trc = -EINVAL;\n\tnew_context = sidtab_search(&sidtab, new_sid);\n\tif (!new_context) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %u\\n\",\n\t\t __func__, new_sid);\n\t\tgoto out;\n\t}",
"\trc = 0;\n\t/* type/domain unchanged */\n\tif (old_context->type == new_context->type)\n\t\tgoto out;",
"\tindex = new_context->type;\n\twhile (true) {\n\t\ttype = flex_array_get_ptr(policydb.type_val_to_struct_array,\n\t\t\t\t\t index - 1);\n\t\tBUG_ON(!type);",
"\t\t/* not bounded anymore */\n\t\trc = -EPERM;\n\t\tif (!type->bounds)\n\t\t\tbreak;",
"\t\t/* @newsid is bounded by @oldsid */\n\t\trc = 0;\n\t\tif (type->bounds == old_context->type)\n\t\t\tbreak;",
"\t\tindex = type->bounds;\n\t}",
"\tif (rc) {\n\t\tchar *old_name = NULL;\n\t\tchar *new_name = NULL;\n\t\tu32 length;",
"\t\tif (!context_struct_to_string(old_context,\n\t\t\t\t\t &old_name, &length) &&\n\t\t !context_struct_to_string(new_context,\n\t\t\t\t\t &new_name, &length)) {\n\t\t\taudit_log(current->audit_context,\n\t\t\t\t GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t\t\t \"op=security_bounded_transition \"\n\t\t\t\t \"result=denied \"\n\t\t\t\t \"oldcontext=%s newcontext=%s\",\n\t\t\t\t old_name, new_name);\n\t\t}\n\t\tkfree(new_name);\n\t\tkfree(old_name);\n\t}\nout:\n\tread_unlock(&policy_rwlock);",
"\treturn rc;\n}",
"static void avd_init(struct av_decision *avd)\n{\n\tavd->allowed = 0;\n\tavd->auditallow = 0;\n\tavd->auditdeny = 0xffffffff;\n\tavd->seqno = latest_granting;\n\tavd->flags = 0;\n}",
"\n/**\n * security_compute_av - Compute access vector decisions.\n * @ssid: source security identifier\n * @tsid: target security identifier\n * @tclass: target security class\n * @avd: access vector decisions\n *\n * Compute a set of access vector decisions based on the\n * SID pair (@ssid, @tsid) for the permissions in @tclass.\n */\nvoid security_compute_av(u32 ssid,\n\t\t\t u32 tsid,\n\t\t\t u16 orig_tclass,\n\t\t\t struct av_decision *avd)\n{\n\tu16 tclass;\n\tstruct context *scontext = NULL, *tcontext = NULL;",
"\tread_lock(&policy_rwlock);\n\tavd_init(avd);\n\tif (!ss_initialized)\n\t\tgoto allow;",
"\tscontext = sidtab_search(&sidtab, ssid);\n\tif (!scontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, ssid);\n\t\tgoto out;\n\t}",
"\t/* permissive domain? */\n\tif (ebitmap_get_bit(&policydb.permissive_map, scontext->type))\n\t\tavd->flags |= AVD_FLAGS_PERMISSIVE;",
"\ttcontext = sidtab_search(&sidtab, tsid);\n\tif (!tcontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, tsid);\n\t\tgoto out;\n\t}",
"\ttclass = unmap_class(orig_tclass);\n\tif (unlikely(orig_tclass && !tclass)) {\n\t\tif (policydb.allow_unknown)\n\t\t\tgoto allow;\n\t\tgoto out;\n\t}\n\tcontext_struct_compute_av(scontext, tcontext, tclass, avd);\n\tmap_decision(orig_tclass, avd, policydb.allow_unknown);\nout:\n\tread_unlock(&policy_rwlock);\n\treturn;\nallow:\n\tavd->allowed = 0xffffffff;\n\tgoto out;\n}",
"void security_compute_av_user(u32 ssid,\n\t\t\t u32 tsid,\n\t\t\t u16 tclass,\n\t\t\t struct av_decision *avd)\n{\n\tstruct context *scontext = NULL, *tcontext = NULL;",
"\tread_lock(&policy_rwlock);\n\tavd_init(avd);\n\tif (!ss_initialized)\n\t\tgoto allow;",
"\tscontext = sidtab_search(&sidtab, ssid);\n\tif (!scontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, ssid);\n\t\tgoto out;\n\t}",
"\t/* permissive domain? */\n\tif (ebitmap_get_bit(&policydb.permissive_map, scontext->type))\n\t\tavd->flags |= AVD_FLAGS_PERMISSIVE;",
"\ttcontext = sidtab_search(&sidtab, tsid);\n\tif (!tcontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, tsid);\n\t\tgoto out;\n\t}",
"\tif (unlikely(!tclass)) {\n\t\tif (policydb.allow_unknown)\n\t\t\tgoto allow;\n\t\tgoto out;\n\t}",
"\tcontext_struct_compute_av(scontext, tcontext, tclass, avd);\n out:\n\tread_unlock(&policy_rwlock);\n\treturn;\nallow:\n\tavd->allowed = 0xffffffff;\n\tgoto out;\n}",
"/*\n * Write the security context string representation of\n * the context structure `context' into a dynamically\n * allocated string of the correct size. Set `*scontext'\n * to point to this string and set `*scontext_len' to\n * the length of the string.\n */\nstatic int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)\n{\n\tchar *scontextp;",
"\tif (scontext)\n\t\t*scontext = NULL;\n\t*scontext_len = 0;",
"\tif (context->len) {\n\t\t*scontext_len = context->len;\n\t\tif (scontext) {\n\t\t\t*scontext = kstrdup(context->str, GFP_ATOMIC);\n\t\t\tif (!(*scontext))\n\t\t\t\treturn -ENOMEM;\n\t\t}\n\t\treturn 0;\n\t}",
"\t/* Compute the size of the context. */\n\t*scontext_len += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) + 1;\n\t*scontext_len += strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) + 1;\n\t*scontext_len += strlen(sym_name(&policydb, SYM_TYPES, context->type - 1)) + 1;\n\t*scontext_len += mls_compute_context_len(context);",
"\tif (!scontext)\n\t\treturn 0;",
"\t/* Allocate space for the context; caller must free this space. */\n\tscontextp = kmalloc(*scontext_len, GFP_ATOMIC);\n\tif (!scontextp)\n\t\treturn -ENOMEM;\n\t*scontext = scontextp;",
"\t/*\n\t * Copy the user name, role name and type name into the context.\n\t */\n\tsprintf(scontextp, \"%s:%s:%s\",\n\t\tsym_name(&policydb, SYM_USERS, context->user - 1),\n\t\tsym_name(&policydb, SYM_ROLES, context->role - 1),\n\t\tsym_name(&policydb, SYM_TYPES, context->type - 1));\n\tscontextp += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) +\n\t\t 1 + strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) +\n\t\t 1 + strlen(sym_name(&policydb, SYM_TYPES, context->type - 1));",
"\tmls_sid_to_context(context, &scontextp);",
"\t*scontextp = 0;",
"\treturn 0;\n}",
"#include \"initial_sid_to_string.h\"",
"const char *security_get_initial_sid_context(u32 sid)\n{\n\tif (unlikely(sid > SECINITSID_NUM))\n\t\treturn NULL;\n\treturn initial_sid_to_string[sid];\n}",
"static int security_sid_to_context_core(u32 sid, char **scontext,\n\t\t\t\t\tu32 *scontext_len, int force)\n{\n\tstruct context *context;\n\tint rc = 0;",
"\tif (scontext)\n\t\t*scontext = NULL;\n\t*scontext_len = 0;",
"\tif (!ss_initialized) {\n\t\tif (sid <= SECINITSID_NUM) {\n\t\t\tchar *scontextp;",
"\t\t\t*scontext_len = strlen(initial_sid_to_string[sid]) + 1;\n\t\t\tif (!scontext)\n\t\t\t\tgoto out;\n\t\t\tscontextp = kmalloc(*scontext_len, GFP_ATOMIC);\n\t\t\tif (!scontextp) {\n\t\t\t\trc = -ENOMEM;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tstrcpy(scontextp, initial_sid_to_string[sid]);\n\t\t\t*scontext = scontextp;\n\t\t\tgoto out;\n\t\t}\n\t\tprintk(KERN_ERR \"SELinux: %s: called before initial \"\n\t\t \"load_policy on unknown SID %d\\n\", __func__, sid);\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}\n\tread_lock(&policy_rwlock);\n\tif (force)\n\t\tcontext = sidtab_search_force(&sidtab, sid);\n\telse\n\t\tcontext = sidtab_search(&sidtab, sid);\n\tif (!context) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, sid);\n\t\trc = -EINVAL;\n\t\tgoto out_unlock;\n\t}\n\trc = context_struct_to_string(context, scontext, scontext_len);\nout_unlock:\n\tread_unlock(&policy_rwlock);\nout:\n\treturn rc;",
"}",
"/**\n * security_sid_to_context - Obtain a context for a given SID.\n * @sid: security identifier, SID\n * @scontext: security context\n * @scontext_len: length in bytes\n *\n * Write the string representation of the context associated with @sid\n * into a dynamically allocated string of the correct size. Set @scontext\n * to point to this string and set @scontext_len to the length of the string.\n */\nint security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)\n{\n\treturn security_sid_to_context_core(sid, scontext, scontext_len, 0);\n}",
"int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len)\n{\n\treturn security_sid_to_context_core(sid, scontext, scontext_len, 1);\n}",
"/*\n * Caveat: Mutates scontext.\n */\nstatic int string_to_context_struct(struct policydb *pol,\n\t\t\t\t struct sidtab *sidtabp,\n\t\t\t\t char *scontext,\n\t\t\t\t u32 scontext_len,\n\t\t\t\t struct context *ctx,\n\t\t\t\t u32 def_sid)\n{\n\tstruct role_datum *role;\n\tstruct type_datum *typdatum;\n\tstruct user_datum *usrdatum;\n\tchar *scontextp, *p, oldc;\n\tint rc = 0;",
"\tcontext_init(ctx);",
"\t/* Parse the security context. */",
"\trc = -EINVAL;\n\tscontextp = (char *) scontext;",
"\t/* Extract the user. */\n\tp = scontextp;\n\twhile (*p && *p != ':')\n\t\tp++;",
"\tif (*p == 0)\n\t\tgoto out;",
"\t*p++ = 0;",
"\tusrdatum = hashtab_search(pol->p_users.table, scontextp);\n\tif (!usrdatum)\n\t\tgoto out;",
"\tctx->user = usrdatum->value;",
"\t/* Extract role. */\n\tscontextp = p;\n\twhile (*p && *p != ':')\n\t\tp++;",
"\tif (*p == 0)\n\t\tgoto out;",
"\t*p++ = 0;",
"\trole = hashtab_search(pol->p_roles.table, scontextp);\n\tif (!role)\n\t\tgoto out;\n\tctx->role = role->value;",
"\t/* Extract type. */\n\tscontextp = p;\n\twhile (*p && *p != ':')\n\t\tp++;\n\toldc = *p;\n\t*p++ = 0;",
"\ttypdatum = hashtab_search(pol->p_types.table, scontextp);\n\tif (!typdatum || typdatum->attribute)\n\t\tgoto out;",
"\tctx->type = typdatum->value;",
"\trc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);\n\tif (rc)\n\t\tgoto out;",
"\trc = -EINVAL;\n\tif ((p - scontext) < scontext_len)\n\t\tgoto out;",
"\t/* Check the validity of the new context. */\n\tif (!policydb_context_isvalid(pol, ctx))\n\t\tgoto out;\n\trc = 0;\nout:\n\tif (rc)\n\t\tcontext_destroy(ctx);\n\treturn rc;\n}",
"static int security_context_to_sid_core(const char *scontext, u32 scontext_len,\n\t\t\t\t\tu32 *sid, u32 def_sid, gfp_t gfp_flags,\n\t\t\t\t\tint force)\n{\n\tchar *scontext2, *str = NULL;\n\tstruct context context;\n\tint rc = 0;\n",
"",
"\tif (!ss_initialized) {\n\t\tint i;",
"\t\tfor (i = 1; i < SECINITSID_NUM; i++) {\n\t\t\tif (!strcmp(initial_sid_to_string[i], scontext)) {\n\t\t\t\t*sid = i;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\t*sid = SECINITSID_KERNEL;\n\t\treturn 0;\n\t}\n\t*sid = SECSID_NULL;",
"\t/* Copy the string so that we can modify the copy as we parse it. */\n\tscontext2 = kmalloc(scontext_len + 1, gfp_flags);\n\tif (!scontext2)\n\t\treturn -ENOMEM;\n\tmemcpy(scontext2, scontext, scontext_len);\n\tscontext2[scontext_len] = 0;",
"\tif (force) {\n\t\t/* Save another copy for storing in uninterpreted form */\n\t\trc = -ENOMEM;\n\t\tstr = kstrdup(scontext2, gfp_flags);\n\t\tif (!str)\n\t\t\tgoto out;\n\t}",
"\tread_lock(&policy_rwlock);\n\trc = string_to_context_struct(&policydb, &sidtab, scontext2,\n\t\t\t\t scontext_len, &context, def_sid);\n\tif (rc == -EINVAL && force) {\n\t\tcontext.str = str;\n\t\tcontext.len = scontext_len;\n\t\tstr = NULL;\n\t} else if (rc)\n\t\tgoto out_unlock;\n\trc = sidtab_context_to_sid(&sidtab, &context, sid);\n\tcontext_destroy(&context);\nout_unlock:\n\tread_unlock(&policy_rwlock);\nout:\n\tkfree(scontext2);\n\tkfree(str);\n\treturn rc;\n}",
"/**\n * security_context_to_sid - Obtain a SID for a given security context.\n * @scontext: security context\n * @scontext_len: length in bytes\n * @sid: security identifier, SID\n *\n * Obtains a SID associated with the security context that\n * has the string representation specified by @scontext.\n * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient\n * memory is available, or 0 on success.\n */\nint security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid)\n{\n\treturn security_context_to_sid_core(scontext, scontext_len,\n\t\t\t\t\t sid, SECSID_NULL, GFP_KERNEL, 0);\n}",
"/**\n * security_context_to_sid_default - Obtain a SID for a given security context,\n * falling back to specified default if needed.\n *\n * @scontext: security context\n * @scontext_len: length in bytes\n * @sid: security identifier, SID\n * @def_sid: default SID to assign on error\n *\n * Obtains a SID associated with the security context that\n * has the string representation specified by @scontext.\n * The default SID is passed to the MLS layer to be used to allow\n * kernel labeling of the MLS field if the MLS field is not present\n * (for upgrading to MLS without full relabel).\n * Implicitly forces adding of the context even if it cannot be mapped yet.\n * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient\n * memory is available, or 0 on success.\n */\nint security_context_to_sid_default(const char *scontext, u32 scontext_len,\n\t\t\t\t u32 *sid, u32 def_sid, gfp_t gfp_flags)\n{\n\treturn security_context_to_sid_core(scontext, scontext_len,\n\t\t\t\t\t sid, def_sid, gfp_flags, 1);\n}",
"int security_context_to_sid_force(const char *scontext, u32 scontext_len,\n\t\t\t\t u32 *sid)\n{\n\treturn security_context_to_sid_core(scontext, scontext_len,\n\t\t\t\t\t sid, SECSID_NULL, GFP_KERNEL, 1);\n}",
"static int compute_sid_handle_invalid_context(\n\tstruct context *scontext,\n\tstruct context *tcontext,\n\tu16 tclass,\n\tstruct context *newcontext)\n{\n\tchar *s = NULL, *t = NULL, *n = NULL;\n\tu32 slen, tlen, nlen;",
"\tif (context_struct_to_string(scontext, &s, &slen))\n\t\tgoto out;\n\tif (context_struct_to_string(tcontext, &t, &tlen))\n\t\tgoto out;\n\tif (context_struct_to_string(newcontext, &n, &nlen))\n\t\tgoto out;\n\taudit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t \"security_compute_sid: invalid context %s\"\n\t\t \" for scontext=%s\"\n\t\t \" tcontext=%s\"\n\t\t \" tclass=%s\",\n\t\t n, s, t, sym_name(&policydb, SYM_CLASSES, tclass-1));\nout:\n\tkfree(s);\n\tkfree(t);\n\tkfree(n);\n\tif (!selinux_enforcing)\n\t\treturn 0;\n\treturn -EACCES;\n}",
"static void filename_compute_type(struct policydb *p, struct context *newcontext,\n\t\t\t\t u32 stype, u32 ttype, u16 tclass,\n\t\t\t\t const char *objname)\n{\n\tstruct filename_trans ft;\n\tstruct filename_trans_datum *otype;",
"\t/*\n\t * Most filename trans rules are going to live in specific directories\n\t * like /dev or /var/run. This bitmap will quickly skip rule searches\n\t * if the ttype does not contain any rules.\n\t */\n\tif (!ebitmap_get_bit(&p->filename_trans_ttypes, ttype))\n\t\treturn;",
"\tft.stype = stype;\n\tft.ttype = ttype;\n\tft.tclass = tclass;\n\tft.name = objname;",
"\totype = hashtab_search(p->filename_trans, &ft);\n\tif (otype)\n\t\tnewcontext->type = otype->otype;\n}",
"static int security_compute_sid(u32 ssid,\n\t\t\t\tu32 tsid,\n\t\t\t\tu16 orig_tclass,\n\t\t\t\tu32 specified,\n\t\t\t\tconst char *objname,\n\t\t\t\tu32 *out_sid,\n\t\t\t\tbool kern)\n{\n\tstruct class_datum *cladatum = NULL;\n\tstruct context *scontext = NULL, *tcontext = NULL, newcontext;\n\tstruct role_trans *roletr = NULL;\n\tstruct avtab_key avkey;\n\tstruct avtab_datum *avdatum;\n\tstruct avtab_node *node;\n\tu16 tclass;\n\tint rc = 0;\n\tbool sock;",
"\tif (!ss_initialized) {\n\t\tswitch (orig_tclass) {\n\t\tcase SECCLASS_PROCESS: /* kernel value */\n\t\t\t*out_sid = ssid;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t*out_sid = tsid;\n\t\t\tbreak;\n\t\t}\n\t\tgoto out;\n\t}",
"\tcontext_init(&newcontext);",
"\tread_lock(&policy_rwlock);",
"\tif (kern) {\n\t\ttclass = unmap_class(orig_tclass);\n\t\tsock = security_is_socket_class(orig_tclass);\n\t} else {\n\t\ttclass = orig_tclass;\n\t\tsock = security_is_socket_class(map_class(tclass));\n\t}",
"\tscontext = sidtab_search(&sidtab, ssid);\n\tif (!scontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, ssid);\n\t\trc = -EINVAL;\n\t\tgoto out_unlock;\n\t}\n\ttcontext = sidtab_search(&sidtab, tsid);\n\tif (!tcontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, tsid);\n\t\trc = -EINVAL;\n\t\tgoto out_unlock;\n\t}",
"\tif (tclass && tclass <= policydb.p_classes.nprim)\n\t\tcladatum = policydb.class_val_to_struct[tclass - 1];",
"\t/* Set the user identity. */\n\tswitch (specified) {\n\tcase AVTAB_TRANSITION:\n\tcase AVTAB_CHANGE:\n\t\tif (cladatum && cladatum->default_user == DEFAULT_TARGET) {\n\t\t\tnewcontext.user = tcontext->user;\n\t\t} else {\n\t\t\t/* notice this gets both DEFAULT_SOURCE and unset */\n\t\t\t/* Use the process user identity. */\n\t\t\tnewcontext.user = scontext->user;\n\t\t}\n\t\tbreak;\n\tcase AVTAB_MEMBER:\n\t\t/* Use the related object owner. */\n\t\tnewcontext.user = tcontext->user;\n\t\tbreak;\n\t}",
"\t/* Set the role to default values. */\n\tif (cladatum && cladatum->default_role == DEFAULT_SOURCE) {\n\t\tnewcontext.role = scontext->role;\n\t} else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {\n\t\tnewcontext.role = tcontext->role;\n\t} else {\n\t\tif ((tclass == policydb.process_class) || (sock == true))\n\t\t\tnewcontext.role = scontext->role;\n\t\telse\n\t\t\tnewcontext.role = OBJECT_R_VAL;\n\t}",
"\t/* Set the type to default values. */\n\tif (cladatum && cladatum->default_type == DEFAULT_SOURCE) {\n\t\tnewcontext.type = scontext->type;\n\t} else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {\n\t\tnewcontext.type = tcontext->type;\n\t} else {\n\t\tif ((tclass == policydb.process_class) || (sock == true)) {\n\t\t\t/* Use the type of process. */\n\t\t\tnewcontext.type = scontext->type;\n\t\t} else {\n\t\t\t/* Use the type of the related object. */\n\t\t\tnewcontext.type = tcontext->type;\n\t\t}\n\t}",
"\t/* Look for a type transition/member/change rule. */\n\tavkey.source_type = scontext->type;\n\tavkey.target_type = tcontext->type;\n\tavkey.target_class = tclass;\n\tavkey.specified = specified;\n\tavdatum = avtab_search(&policydb.te_avtab, &avkey);",
"\t/* If no permanent rule, also check for enabled conditional rules */\n\tif (!avdatum) {\n\t\tnode = avtab_search_node(&policydb.te_cond_avtab, &avkey);\n\t\tfor (; node; node = avtab_search_node_next(node, specified)) {\n\t\t\tif (node->key.specified & AVTAB_ENABLED) {\n\t\t\t\tavdatum = &node->datum;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}",
"\tif (avdatum) {\n\t\t/* Use the type from the type transition/member/change rule. */\n\t\tnewcontext.type = avdatum->data;\n\t}",
"\t/* if we have a objname this is a file trans check so check those rules */\n\tif (objname)\n\t\tfilename_compute_type(&policydb, &newcontext, scontext->type,\n\t\t\t\t tcontext->type, tclass, objname);",
"\t/* Check for class-specific changes. */\n\tif (specified & AVTAB_TRANSITION) {\n\t\t/* Look for a role transition rule. */\n\t\tfor (roletr = policydb.role_tr; roletr; roletr = roletr->next) {\n\t\t\tif ((roletr->role == scontext->role) &&\n\t\t\t (roletr->type == tcontext->type) &&\n\t\t\t (roletr->tclass == tclass)) {\n\t\t\t\t/* Use the role transition rule. */\n\t\t\t\tnewcontext.role = roletr->new_role;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}",
"\t/* Set the MLS attributes.\n\t This is done last because it may allocate memory. */\n\trc = mls_compute_sid(scontext, tcontext, tclass, specified,\n\t\t\t &newcontext, sock);\n\tif (rc)\n\t\tgoto out_unlock;",
"\t/* Check the validity of the context. */\n\tif (!policydb_context_isvalid(&policydb, &newcontext)) {\n\t\trc = compute_sid_handle_invalid_context(scontext,\n\t\t\t\t\t\t\ttcontext,\n\t\t\t\t\t\t\ttclass,\n\t\t\t\t\t\t\t&newcontext);\n\t\tif (rc)\n\t\t\tgoto out_unlock;\n\t}\n\t/* Obtain the sid for the context. */\n\trc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);\nout_unlock:\n\tread_unlock(&policy_rwlock);\n\tcontext_destroy(&newcontext);\nout:\n\treturn rc;\n}",
"/**\n * security_transition_sid - Compute the SID for a new subject/object.\n * @ssid: source security identifier\n * @tsid: target security identifier\n * @tclass: target security class\n * @out_sid: security identifier for new subject/object\n *\n * Compute a SID to use for labeling a new subject or object in the\n * class @tclass based on a SID pair (@ssid, @tsid).\n * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM\n * if insufficient memory is available, or %0 if the new SID was\n * computed successfully.\n */\nint security_transition_sid(u32 ssid, u32 tsid, u16 tclass,\n\t\t\t const struct qstr *qstr, u32 *out_sid)\n{\n\treturn security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,\n\t\t\t\t qstr ? qstr->name : NULL, out_sid, true);\n}",
"int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,\n\t\t\t\t const char *objname, u32 *out_sid)\n{\n\treturn security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,\n\t\t\t\t objname, out_sid, false);\n}",
"/**\n * security_member_sid - Compute the SID for member selection.\n * @ssid: source security identifier\n * @tsid: target security identifier\n * @tclass: target security class\n * @out_sid: security identifier for selected member\n *\n * Compute a SID to use when selecting a member of a polyinstantiated\n * object of class @tclass based on a SID pair (@ssid, @tsid).\n * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM\n * if insufficient memory is available, or %0 if the SID was\n * computed successfully.\n */\nint security_member_sid(u32 ssid,\n\t\t\tu32 tsid,\n\t\t\tu16 tclass,\n\t\t\tu32 *out_sid)\n{\n\treturn security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, NULL,\n\t\t\t\t out_sid, false);\n}",
"/**\n * security_change_sid - Compute the SID for object relabeling.\n * @ssid: source security identifier\n * @tsid: target security identifier\n * @tclass: target security class\n * @out_sid: security identifier for selected member\n *\n * Compute a SID to use for relabeling an object of class @tclass\n * based on a SID pair (@ssid, @tsid).\n * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM\n * if insufficient memory is available, or %0 if the SID was\n * computed successfully.\n */\nint security_change_sid(u32 ssid,\n\t\t\tu32 tsid,\n\t\t\tu16 tclass,\n\t\t\tu32 *out_sid)\n{\n\treturn security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL,\n\t\t\t\t out_sid, false);\n}",
"/* Clone the SID into the new SID table. */\nstatic int clone_sid(u32 sid,\n\t\t struct context *context,\n\t\t void *arg)\n{\n\tstruct sidtab *s = arg;",
"\tif (sid > SECINITSID_NUM)\n\t\treturn sidtab_insert(s, sid, context);\n\telse\n\t\treturn 0;\n}",
"static inline int convert_context_handle_invalid_context(struct context *context)\n{\n\tchar *s;\n\tu32 len;",
"\tif (selinux_enforcing)\n\t\treturn -EINVAL;",
"\tif (!context_struct_to_string(context, &s, &len)) {\n\t\tprintk(KERN_WARNING \"SELinux: Context %s would be invalid if enforcing\\n\", s);\n\t\tkfree(s);\n\t}\n\treturn 0;\n}",
"struct convert_context_args {\n\tstruct policydb *oldp;\n\tstruct policydb *newp;\n};",
"/*\n * Convert the values in the security context\n * structure `c' from the values specified\n * in the policy `p->oldp' to the values specified\n * in the policy `p->newp'. Verify that the\n * context is valid under the new policy.\n */\nstatic int convert_context(u32 key,\n\t\t\t struct context *c,\n\t\t\t void *p)\n{\n\tstruct convert_context_args *args;\n\tstruct context oldc;\n\tstruct ocontext *oc;\n\tstruct mls_range *range;\n\tstruct role_datum *role;\n\tstruct type_datum *typdatum;\n\tstruct user_datum *usrdatum;\n\tchar *s;\n\tu32 len;\n\tint rc = 0;",
"\tif (key <= SECINITSID_NUM)\n\t\tgoto out;",
"\targs = p;",
"\tif (c->str) {\n\t\tstruct context ctx;",
"\t\trc = -ENOMEM;\n\t\ts = kstrdup(c->str, GFP_KERNEL);\n\t\tif (!s)\n\t\t\tgoto out;",
"\t\trc = string_to_context_struct(args->newp, NULL, s,\n\t\t\t\t\t c->len, &ctx, SECSID_NULL);\n\t\tkfree(s);\n\t\tif (!rc) {\n\t\t\tprintk(KERN_INFO \"SELinux: Context %s became valid (mapped).\\n\",\n\t\t\t c->str);\n\t\t\t/* Replace string with mapped representation. */\n\t\t\tkfree(c->str);\n\t\t\tmemcpy(c, &ctx, sizeof(*c));\n\t\t\tgoto out;\n\t\t} else if (rc == -EINVAL) {\n\t\t\t/* Retain string representation for later mapping. */\n\t\t\trc = 0;\n\t\t\tgoto out;\n\t\t} else {\n\t\t\t/* Other error condition, e.g. ENOMEM. */\n\t\t\tprintk(KERN_ERR \"SELinux: Unable to map context %s, rc = %d.\\n\",\n\t\t\t c->str, -rc);\n\t\t\tgoto out;\n\t\t}\n\t}",
"\trc = context_cpy(&oldc, c);\n\tif (rc)\n\t\tgoto out;",
"\t/* Convert the user. */\n\trc = -EINVAL;\n\tusrdatum = hashtab_search(args->newp->p_users.table,\n\t\t\t\t sym_name(args->oldp, SYM_USERS, c->user - 1));\n\tif (!usrdatum)\n\t\tgoto bad;\n\tc->user = usrdatum->value;",
"\t/* Convert the role. */\n\trc = -EINVAL;\n\trole = hashtab_search(args->newp->p_roles.table,\n\t\t\t sym_name(args->oldp, SYM_ROLES, c->role - 1));\n\tif (!role)\n\t\tgoto bad;\n\tc->role = role->value;",
"\t/* Convert the type. */\n\trc = -EINVAL;\n\ttypdatum = hashtab_search(args->newp->p_types.table,\n\t\t\t\t sym_name(args->oldp, SYM_TYPES, c->type - 1));\n\tif (!typdatum)\n\t\tgoto bad;\n\tc->type = typdatum->value;",
"\t/* Convert the MLS fields if dealing with MLS policies */\n\tif (args->oldp->mls_enabled && args->newp->mls_enabled) {\n\t\trc = mls_convert_context(args->oldp, args->newp, c);\n\t\tif (rc)\n\t\t\tgoto bad;\n\t} else if (args->oldp->mls_enabled && !args->newp->mls_enabled) {\n\t\t/*\n\t\t * Switching between MLS and non-MLS policy:\n\t\t * free any storage used by the MLS fields in the\n\t\t * context for all existing entries in the sidtab.\n\t\t */\n\t\tmls_context_destroy(c);\n\t} else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {\n\t\t/*\n\t\t * Switching between non-MLS and MLS policy:\n\t\t * ensure that the MLS fields of the context for all\n\t\t * existing entries in the sidtab are filled in with a\n\t\t * suitable default value, likely taken from one of the\n\t\t * initial SIDs.\n\t\t */\n\t\toc = args->newp->ocontexts[OCON_ISID];\n\t\twhile (oc && oc->sid[0] != SECINITSID_UNLABELED)\n\t\t\toc = oc->next;\n\t\trc = -EINVAL;\n\t\tif (!oc) {\n\t\t\tprintk(KERN_ERR \"SELinux: unable to look up\"\n\t\t\t\t\" the initial SIDs list\\n\");\n\t\t\tgoto bad;\n\t\t}\n\t\trange = &oc->context[0].range;\n\t\trc = mls_range_set(c, range);\n\t\tif (rc)\n\t\t\tgoto bad;\n\t}",
"\t/* Check the validity of the new context. */\n\tif (!policydb_context_isvalid(args->newp, c)) {\n\t\trc = convert_context_handle_invalid_context(&oldc);\n\t\tif (rc)\n\t\t\tgoto bad;\n\t}",
"\tcontext_destroy(&oldc);",
"\trc = 0;\nout:\n\treturn rc;\nbad:\n\t/* Map old representation to string and save it. */\n\trc = context_struct_to_string(&oldc, &s, &len);\n\tif (rc)\n\t\treturn rc;\n\tcontext_destroy(&oldc);\n\tcontext_destroy(c);\n\tc->str = s;\n\tc->len = len;\n\tprintk(KERN_INFO \"SELinux: Context %s became invalid (unmapped).\\n\",\n\t c->str);\n\trc = 0;\n\tgoto out;\n}",
"static void security_load_policycaps(void)\n{\n\tselinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps,\n\t\t\t\t\t\t POLICYDB_CAPABILITY_NETPEER);\n\tselinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps,\n\t\t\t\t\t\t POLICYDB_CAPABILITY_OPENPERM);\n\tselinux_policycap_alwaysnetwork = ebitmap_get_bit(&policydb.policycaps,\n\t\t\t\t\t\t POLICYDB_CAPABILITY_ALWAYSNETWORK);\n}",
"static int security_preserve_bools(struct policydb *p);",
"/**\n * security_load_policy - Load a security policy configuration.\n * @data: binary policy data\n * @len: length of data in bytes\n *\n * Load a new set of security policy configuration data,\n * validate it and convert the SID table as necessary.\n * This function will flush the access vector cache after\n * loading the new policy.\n */\nint security_load_policy(void *data, size_t len)\n{\n\tstruct policydb *oldpolicydb, *newpolicydb;\n\tstruct sidtab oldsidtab, newsidtab;\n\tstruct selinux_mapping *oldmap, *map = NULL;\n\tstruct convert_context_args args;\n\tu32 seqno;\n\tu16 map_size;\n\tint rc = 0;\n\tstruct policy_file file = { data, len }, *fp = &file;",
"\toldpolicydb = kzalloc(2 * sizeof(*oldpolicydb), GFP_KERNEL);\n\tif (!oldpolicydb) {\n\t\trc = -ENOMEM;\n\t\tgoto out;\n\t}\n\tnewpolicydb = oldpolicydb + 1;",
"\tif (!ss_initialized) {\n\t\tavtab_cache_init();\n\t\trc = policydb_read(&policydb, fp);\n\t\tif (rc) {\n\t\t\tavtab_cache_destroy();\n\t\t\tgoto out;\n\t\t}",
"\t\tpolicydb.len = len;\n\t\trc = selinux_set_mapping(&policydb, secclass_map,\n\t\t\t\t\t ¤t_mapping,\n\t\t\t\t\t ¤t_mapping_size);\n\t\tif (rc) {\n\t\t\tpolicydb_destroy(&policydb);\n\t\t\tavtab_cache_destroy();\n\t\t\tgoto out;\n\t\t}",
"\t\trc = policydb_load_isids(&policydb, &sidtab);\n\t\tif (rc) {\n\t\t\tpolicydb_destroy(&policydb);\n\t\t\tavtab_cache_destroy();\n\t\t\tgoto out;\n\t\t}",
"\t\tsecurity_load_policycaps();\n\t\tss_initialized = 1;\n\t\tseqno = ++latest_granting;\n\t\tselinux_complete_init();\n\t\tavc_ss_reset(seqno);\n\t\tselnl_notify_policyload(seqno);\n\t\tselinux_status_update_policyload(seqno);\n\t\tselinux_netlbl_cache_invalidate();\n\t\tselinux_xfrm_notify_policyload();\n\t\tgoto out;\n\t}",
"#if 0\n\tsidtab_hash_eval(&sidtab, \"sids\");\n#endif",
"\trc = policydb_read(newpolicydb, fp);\n\tif (rc)\n\t\tgoto out;",
"\tnewpolicydb->len = len;\n\t/* If switching between different policy types, log MLS status */\n\tif (policydb.mls_enabled && !newpolicydb->mls_enabled)\n\t\tprintk(KERN_INFO \"SELinux: Disabling MLS support...\\n\");\n\telse if (!policydb.mls_enabled && newpolicydb->mls_enabled)\n\t\tprintk(KERN_INFO \"SELinux: Enabling MLS support...\\n\");",
"\trc = policydb_load_isids(newpolicydb, &newsidtab);\n\tif (rc) {\n\t\tprintk(KERN_ERR \"SELinux: unable to load the initial SIDs\\n\");\n\t\tpolicydb_destroy(newpolicydb);\n\t\tgoto out;\n\t}",
"\trc = selinux_set_mapping(newpolicydb, secclass_map, &map, &map_size);\n\tif (rc)\n\t\tgoto err;",
"\trc = security_preserve_bools(newpolicydb);\n\tif (rc) {\n\t\tprintk(KERN_ERR \"SELinux: unable to preserve booleans\\n\");\n\t\tgoto err;\n\t}",
"\t/* Clone the SID table. */\n\tsidtab_shutdown(&sidtab);",
"\trc = sidtab_map(&sidtab, clone_sid, &newsidtab);\n\tif (rc)\n\t\tgoto err;",
"\t/*\n\t * Convert the internal representations of contexts\n\t * in the new SID table.\n\t */\n\targs.oldp = &policydb;\n\targs.newp = newpolicydb;\n\trc = sidtab_map(&newsidtab, convert_context, &args);\n\tif (rc) {\n\t\tprintk(KERN_ERR \"SELinux: unable to convert the internal\"\n\t\t\t\" representation of contexts in the new SID\"\n\t\t\t\" table\\n\");\n\t\tgoto err;\n\t}",
"\t/* Save the old policydb and SID table to free later. */\n\tmemcpy(oldpolicydb, &policydb, sizeof(policydb));\n\tsidtab_set(&oldsidtab, &sidtab);",
"\t/* Install the new policydb and SID table. */\n\twrite_lock_irq(&policy_rwlock);\n\tmemcpy(&policydb, newpolicydb, sizeof(policydb));\n\tsidtab_set(&sidtab, &newsidtab);\n\tsecurity_load_policycaps();\n\toldmap = current_mapping;\n\tcurrent_mapping = map;\n\tcurrent_mapping_size = map_size;\n\tseqno = ++latest_granting;\n\twrite_unlock_irq(&policy_rwlock);",
"\t/* Free the old policydb and SID table. */\n\tpolicydb_destroy(oldpolicydb);\n\tsidtab_destroy(&oldsidtab);\n\tkfree(oldmap);",
"\tavc_ss_reset(seqno);\n\tselnl_notify_policyload(seqno);\n\tselinux_status_update_policyload(seqno);\n\tselinux_netlbl_cache_invalidate();\n\tselinux_xfrm_notify_policyload();",
"\trc = 0;\n\tgoto out;",
"err:\n\tkfree(map);\n\tsidtab_destroy(&newsidtab);\n\tpolicydb_destroy(newpolicydb);",
"out:\n\tkfree(oldpolicydb);\n\treturn rc;\n}",
"size_t security_policydb_len(void)\n{\n\tsize_t len;",
"\tread_lock(&policy_rwlock);\n\tlen = policydb.len;\n\tread_unlock(&policy_rwlock);",
"\treturn len;\n}",
"/**\n * security_port_sid - Obtain the SID for a port.\n * @protocol: protocol number\n * @port: port number\n * @out_sid: security identifier\n */\nint security_port_sid(u8 protocol, u16 port, u32 *out_sid)\n{\n\tstruct ocontext *c;\n\tint rc = 0;",
"\tread_lock(&policy_rwlock);",
"\tc = policydb.ocontexts[OCON_PORT];\n\twhile (c) {\n\t\tif (c->u.port.protocol == protocol &&\n\t\t c->u.port.low_port <= port &&\n\t\t c->u.port.high_port >= port)\n\t\t\tbreak;\n\t\tc = c->next;\n\t}",
"\tif (c) {\n\t\tif (!c->sid[0]) {\n\t\t\trc = sidtab_context_to_sid(&sidtab,\n\t\t\t\t\t\t &c->context[0],\n\t\t\t\t\t\t &c->sid[0]);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t}\n\t\t*out_sid = c->sid[0];\n\t} else {\n\t\t*out_sid = SECINITSID_PORT;\n\t}",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"/**\n * security_netif_sid - Obtain the SID for a network interface.\n * @name: interface name\n * @if_sid: interface SID\n */\nint security_netif_sid(char *name, u32 *if_sid)\n{\n\tint rc = 0;\n\tstruct ocontext *c;",
"\tread_lock(&policy_rwlock);",
"\tc = policydb.ocontexts[OCON_NETIF];\n\twhile (c) {\n\t\tif (strcmp(name, c->u.name) == 0)\n\t\t\tbreak;\n\t\tc = c->next;\n\t}",
"\tif (c) {\n\t\tif (!c->sid[0] || !c->sid[1]) {\n\t\t\trc = sidtab_context_to_sid(&sidtab,\n\t\t\t\t\t\t &c->context[0],\n\t\t\t\t\t\t &c->sid[0]);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t\trc = sidtab_context_to_sid(&sidtab,\n\t\t\t\t\t\t &c->context[1],\n\t\t\t\t\t\t &c->sid[1]);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t}\n\t\t*if_sid = c->sid[0];\n\t} else\n\t\t*if_sid = SECINITSID_NETIF;",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)\n{\n\tint i, fail = 0;",
"\tfor (i = 0; i < 4; i++)\n\t\tif (addr[i] != (input[i] & mask[i])) {\n\t\t\tfail = 1;\n\t\t\tbreak;\n\t\t}",
"\treturn !fail;\n}",
"/**\n * security_node_sid - Obtain the SID for a node (host).\n * @domain: communication domain aka address family\n * @addrp: address\n * @addrlen: address length in bytes\n * @out_sid: security identifier\n */\nint security_node_sid(u16 domain,\n\t\t void *addrp,\n\t\t u32 addrlen,\n\t\t u32 *out_sid)\n{\n\tint rc;\n\tstruct ocontext *c;",
"\tread_lock(&policy_rwlock);",
"\tswitch (domain) {\n\tcase AF_INET: {\n\t\tu32 addr;",
"\t\trc = -EINVAL;\n\t\tif (addrlen != sizeof(u32))\n\t\t\tgoto out;",
"\t\taddr = *((u32 *)addrp);",
"\t\tc = policydb.ocontexts[OCON_NODE];\n\t\twhile (c) {\n\t\t\tif (c->u.node.addr == (addr & c->u.node.mask))\n\t\t\t\tbreak;\n\t\t\tc = c->next;\n\t\t}\n\t\tbreak;\n\t}",
"\tcase AF_INET6:\n\t\trc = -EINVAL;\n\t\tif (addrlen != sizeof(u64) * 2)\n\t\t\tgoto out;\n\t\tc = policydb.ocontexts[OCON_NODE6];\n\t\twhile (c) {\n\t\t\tif (match_ipv6_addrmask(addrp, c->u.node6.addr,\n\t\t\t\t\t\tc->u.node6.mask))\n\t\t\t\tbreak;\n\t\t\tc = c->next;\n\t\t}\n\t\tbreak;",
"\tdefault:\n\t\trc = 0;\n\t\t*out_sid = SECINITSID_NODE;\n\t\tgoto out;\n\t}",
"\tif (c) {\n\t\tif (!c->sid[0]) {\n\t\t\trc = sidtab_context_to_sid(&sidtab,\n\t\t\t\t\t\t &c->context[0],\n\t\t\t\t\t\t &c->sid[0]);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t}\n\t\t*out_sid = c->sid[0];\n\t} else {\n\t\t*out_sid = SECINITSID_NODE;\n\t}",
"\trc = 0;\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"#define SIDS_NEL 25",
"/**\n * security_get_user_sids - Obtain reachable SIDs for a user.\n * @fromsid: starting SID\n * @username: username\n * @sids: array of reachable SIDs for user\n * @nel: number of elements in @sids\n *\n * Generate the set of SIDs for legal security contexts\n * for a given user that can be reached by @fromsid.\n * Set *@sids to point to a dynamically allocated\n * array containing the set of SIDs. Set *@nel to the\n * number of elements in the array.\n */",
"int security_get_user_sids(u32 fromsid,\n\t\t\t char *username,\n\t\t\t u32 **sids,\n\t\t\t u32 *nel)\n{\n\tstruct context *fromcon, usercon;\n\tu32 *mysids = NULL, *mysids2, sid;\n\tu32 mynel = 0, maxnel = SIDS_NEL;\n\tstruct user_datum *user;\n\tstruct role_datum *role;\n\tstruct ebitmap_node *rnode, *tnode;\n\tint rc = 0, i, j;",
"\t*sids = NULL;\n\t*nel = 0;",
"\tif (!ss_initialized)\n\t\tgoto out;",
"\tread_lock(&policy_rwlock);",
"\tcontext_init(&usercon);",
"\trc = -EINVAL;\n\tfromcon = sidtab_search(&sidtab, fromsid);\n\tif (!fromcon)\n\t\tgoto out_unlock;",
"\trc = -EINVAL;\n\tuser = hashtab_search(policydb.p_users.table, username);\n\tif (!user)\n\t\tgoto out_unlock;",
"\tusercon.user = user->value;",
"\trc = -ENOMEM;\n\tmysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);\n\tif (!mysids)\n\t\tgoto out_unlock;",
"\tebitmap_for_each_positive_bit(&user->roles, rnode, i) {\n\t\trole = policydb.role_val_to_struct[i];\n\t\tusercon.role = i + 1;\n\t\tebitmap_for_each_positive_bit(&role->types, tnode, j) {\n\t\t\tusercon.type = j + 1;",
"\t\t\tif (mls_setup_user_range(fromcon, user, &usercon))\n\t\t\t\tcontinue;",
"\t\t\trc = sidtab_context_to_sid(&sidtab, &usercon, &sid);\n\t\t\tif (rc)\n\t\t\t\tgoto out_unlock;\n\t\t\tif (mynel < maxnel) {\n\t\t\t\tmysids[mynel++] = sid;\n\t\t\t} else {\n\t\t\t\trc = -ENOMEM;\n\t\t\t\tmaxnel += SIDS_NEL;\n\t\t\t\tmysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);\n\t\t\t\tif (!mysids2)\n\t\t\t\t\tgoto out_unlock;\n\t\t\t\tmemcpy(mysids2, mysids, mynel * sizeof(*mysids2));\n\t\t\t\tkfree(mysids);\n\t\t\t\tmysids = mysids2;\n\t\t\t\tmysids[mynel++] = sid;\n\t\t\t}\n\t\t}\n\t}\n\trc = 0;\nout_unlock:\n\tread_unlock(&policy_rwlock);\n\tif (rc || !mynel) {\n\t\tkfree(mysids);\n\t\tgoto out;\n\t}",
"\trc = -ENOMEM;\n\tmysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);\n\tif (!mysids2) {\n\t\tkfree(mysids);\n\t\tgoto out;\n\t}\n\tfor (i = 0, j = 0; i < mynel; i++) {\n\t\tstruct av_decision dummy_avd;\n\t\trc = avc_has_perm_noaudit(fromsid, mysids[i],\n\t\t\t\t\t SECCLASS_PROCESS, /* kernel value */\n\t\t\t\t\t PROCESS__TRANSITION, AVC_STRICT,\n\t\t\t\t\t &dummy_avd);\n\t\tif (!rc)\n\t\t\tmysids2[j++] = mysids[i];\n\t\tcond_resched();\n\t}\n\trc = 0;\n\tkfree(mysids);\n\t*sids = mysids2;\n\t*nel = j;\nout:\n\treturn rc;\n}",
"/**\n * security_genfs_sid - Obtain a SID for a file in a filesystem\n * @fstype: filesystem type\n * @path: path from root of mount\n * @sclass: file security class\n * @sid: SID for path\n *\n * Obtain a SID to use for a file in a filesystem that\n * cannot support xattr or use a fixed labeling behavior like\n * transition SIDs or task SIDs.\n */\nint security_genfs_sid(const char *fstype,\n\t\t char *path,\n\t\t u16 orig_sclass,\n\t\t u32 *sid)\n{\n\tint len;\n\tu16 sclass;\n\tstruct genfs *genfs;\n\tstruct ocontext *c;\n\tint rc, cmp = 0;",
"\twhile (path[0] == '/' && path[1] == '/')\n\t\tpath++;",
"\tread_lock(&policy_rwlock);",
"\tsclass = unmap_class(orig_sclass);\n\t*sid = SECINITSID_UNLABELED;",
"\tfor (genfs = policydb.genfs; genfs; genfs = genfs->next) {\n\t\tcmp = strcmp(fstype, genfs->fstype);\n\t\tif (cmp <= 0)\n\t\t\tbreak;\n\t}",
"\trc = -ENOENT;\n\tif (!genfs || cmp)\n\t\tgoto out;",
"\tfor (c = genfs->head; c; c = c->next) {\n\t\tlen = strlen(c->u.name);\n\t\tif ((!c->v.sclass || sclass == c->v.sclass) &&\n\t\t (strncmp(c->u.name, path, len) == 0))\n\t\t\tbreak;\n\t}",
"\trc = -ENOENT;\n\tif (!c)\n\t\tgoto out;",
"\tif (!c->sid[0]) {\n\t\trc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]);\n\t\tif (rc)\n\t\t\tgoto out;\n\t}",
"\t*sid = c->sid[0];\n\trc = 0;\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"/**\n * security_fs_use - Determine how to handle labeling for a filesystem.\n * @sb: superblock in question\n */\nint security_fs_use(struct super_block *sb)\n{\n\tint rc = 0;\n\tstruct ocontext *c;\n\tstruct superblock_security_struct *sbsec = sb->s_security;\n\tconst char *fstype = sb->s_type->name;",
"\tread_lock(&policy_rwlock);",
"\tc = policydb.ocontexts[OCON_FSUSE];\n\twhile (c) {\n\t\tif (strcmp(fstype, c->u.name) == 0)\n\t\t\tbreak;\n\t\tc = c->next;\n\t}",
"\tif (c) {\n\t\tsbsec->behavior = c->v.behavior;\n\t\tif (!c->sid[0]) {\n\t\t\trc = sidtab_context_to_sid(&sidtab, &c->context[0],\n\t\t\t\t\t\t &c->sid[0]);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t}\n\t\tsbsec->sid = c->sid[0];\n\t} else {\n\t\trc = security_genfs_sid(fstype, \"/\", SECCLASS_DIR, &sbsec->sid);\n\t\tif (rc) {\n\t\t\tsbsec->behavior = SECURITY_FS_USE_NONE;\n\t\t\trc = 0;\n\t\t} else {\n\t\t\tsbsec->behavior = SECURITY_FS_USE_GENFS;\n\t\t}\n\t}",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"int security_get_bools(int *len, char ***names, int **values)\n{\n\tint i, rc;",
"\tread_lock(&policy_rwlock);\n\t*names = NULL;\n\t*values = NULL;",
"\trc = 0;\n\t*len = policydb.p_bools.nprim;\n\tif (!*len)\n\t\tgoto out;",
"\trc = -ENOMEM;\n\t*names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);\n\tif (!*names)\n\t\tgoto err;",
"\trc = -ENOMEM;\n\t*values = kcalloc(*len, sizeof(int), GFP_ATOMIC);\n\tif (!*values)\n\t\tgoto err;",
"\tfor (i = 0; i < *len; i++) {\n\t\tsize_t name_len;",
"\t\t(*values)[i] = policydb.bool_val_to_struct[i]->state;\n\t\tname_len = strlen(sym_name(&policydb, SYM_BOOLS, i)) + 1;",
"\t\trc = -ENOMEM;\n\t\t(*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);\n\t\tif (!(*names)[i])\n\t\t\tgoto err;",
"\t\tstrncpy((*names)[i], sym_name(&policydb, SYM_BOOLS, i), name_len);\n\t\t(*names)[i][name_len - 1] = 0;\n\t}\n\trc = 0;\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\nerr:\n\tif (*names) {\n\t\tfor (i = 0; i < *len; i++)\n\t\t\tkfree((*names)[i]);\n\t}\n\tkfree(*values);\n\tgoto out;\n}",
"\nint security_set_bools(int len, int *values)\n{\n\tint i, rc;\n\tint lenp, seqno = 0;\n\tstruct cond_node *cur;",
"\twrite_lock_irq(&policy_rwlock);",
"\trc = -EFAULT;\n\tlenp = policydb.p_bools.nprim;\n\tif (len != lenp)\n\t\tgoto out;",
"\tfor (i = 0; i < len; i++) {\n\t\tif (!!values[i] != policydb.bool_val_to_struct[i]->state) {\n\t\t\taudit_log(current->audit_context, GFP_ATOMIC,\n\t\t\t\tAUDIT_MAC_CONFIG_CHANGE,\n\t\t\t\t\"bool=%s val=%d old_val=%d auid=%u ses=%u\",\n\t\t\t\tsym_name(&policydb, SYM_BOOLS, i),\n\t\t\t\t!!values[i],\n\t\t\t\tpolicydb.bool_val_to_struct[i]->state,\n\t\t\t\tfrom_kuid(&init_user_ns, audit_get_loginuid(current)),\n\t\t\t\taudit_get_sessionid(current));\n\t\t}\n\t\tif (values[i])\n\t\t\tpolicydb.bool_val_to_struct[i]->state = 1;\n\t\telse\n\t\t\tpolicydb.bool_val_to_struct[i]->state = 0;\n\t}",
"\tfor (cur = policydb.cond_list; cur; cur = cur->next) {\n\t\trc = evaluate_cond_node(&policydb, cur);\n\t\tif (rc)\n\t\t\tgoto out;\n\t}",
"\tseqno = ++latest_granting;\n\trc = 0;\nout:\n\twrite_unlock_irq(&policy_rwlock);\n\tif (!rc) {\n\t\tavc_ss_reset(seqno);\n\t\tselnl_notify_policyload(seqno);\n\t\tselinux_status_update_policyload(seqno);\n\t\tselinux_xfrm_notify_policyload();\n\t}\n\treturn rc;\n}",
"int security_get_bool_value(int bool)\n{\n\tint rc;\n\tint len;",
"\tread_lock(&policy_rwlock);",
"\trc = -EFAULT;\n\tlen = policydb.p_bools.nprim;\n\tif (bool >= len)\n\t\tgoto out;",
"\trc = policydb.bool_val_to_struct[bool]->state;\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"static int security_preserve_bools(struct policydb *p)\n{\n\tint rc, nbools = 0, *bvalues = NULL, i;\n\tchar **bnames = NULL;\n\tstruct cond_bool_datum *booldatum;\n\tstruct cond_node *cur;",
"\trc = security_get_bools(&nbools, &bnames, &bvalues);\n\tif (rc)\n\t\tgoto out;\n\tfor (i = 0; i < nbools; i++) {\n\t\tbooldatum = hashtab_search(p->p_bools.table, bnames[i]);\n\t\tif (booldatum)\n\t\t\tbooldatum->state = bvalues[i];\n\t}\n\tfor (cur = p->cond_list; cur; cur = cur->next) {\n\t\trc = evaluate_cond_node(p, cur);\n\t\tif (rc)\n\t\t\tgoto out;\n\t}",
"out:\n\tif (bnames) {\n\t\tfor (i = 0; i < nbools; i++)\n\t\t\tkfree(bnames[i]);\n\t}\n\tkfree(bnames);\n\tkfree(bvalues);\n\treturn rc;\n}",
"/*\n * security_sid_mls_copy() - computes a new sid based on the given\n * sid and the mls portion of mls_sid.\n */\nint security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)\n{\n\tstruct context *context1;\n\tstruct context *context2;\n\tstruct context newcon;\n\tchar *s;\n\tu32 len;\n\tint rc;",
"\trc = 0;\n\tif (!ss_initialized || !policydb.mls_enabled) {\n\t\t*new_sid = sid;\n\t\tgoto out;\n\t}",
"\tcontext_init(&newcon);",
"\tread_lock(&policy_rwlock);",
"\trc = -EINVAL;\n\tcontext1 = sidtab_search(&sidtab, sid);\n\tif (!context1) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, sid);\n\t\tgoto out_unlock;\n\t}",
"\trc = -EINVAL;\n\tcontext2 = sidtab_search(&sidtab, mls_sid);\n\tif (!context2) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, mls_sid);\n\t\tgoto out_unlock;\n\t}",
"\tnewcon.user = context1->user;\n\tnewcon.role = context1->role;\n\tnewcon.type = context1->type;\n\trc = mls_context_cpy(&newcon, context2);\n\tif (rc)\n\t\tgoto out_unlock;",
"\t/* Check the validity of the new context. */\n\tif (!policydb_context_isvalid(&policydb, &newcon)) {\n\t\trc = convert_context_handle_invalid_context(&newcon);\n\t\tif (rc) {\n\t\t\tif (!context_struct_to_string(&newcon, &s, &len)) {\n\t\t\t\taudit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t\t\t\t \"security_sid_mls_copy: invalid context %s\", s);\n\t\t\t\tkfree(s);\n\t\t\t}\n\t\t\tgoto out_unlock;\n\t\t}\n\t}",
"\trc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);\nout_unlock:\n\tread_unlock(&policy_rwlock);\n\tcontext_destroy(&newcon);\nout:\n\treturn rc;\n}",
"/**\n * security_net_peersid_resolve - Compare and resolve two network peer SIDs\n * @nlbl_sid: NetLabel SID\n * @nlbl_type: NetLabel labeling protocol type\n * @xfrm_sid: XFRM SID\n *\n * Description:\n * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be\n * resolved into a single SID it is returned via @peer_sid and the function\n * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function\n * returns a negative value. A table summarizing the behavior is below:\n *\n * | function return | @sid\n * ------------------------------+-----------------+-----------------\n * no peer labels | 0 | SECSID_NULL\n * single peer label | 0 | <peer_label>\n * multiple, consistent labels | 0 | <peer_label>\n * multiple, inconsistent labels | -<errno> | SECSID_NULL\n *\n */\nint security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,\n\t\t\t\t u32 xfrm_sid,\n\t\t\t\t u32 *peer_sid)\n{\n\tint rc;\n\tstruct context *nlbl_ctx;\n\tstruct context *xfrm_ctx;",
"\t*peer_sid = SECSID_NULL;",
"\t/* handle the common (which also happens to be the set of easy) cases\n\t * right away, these two if statements catch everything involving a\n\t * single or absent peer SID/label */\n\tif (xfrm_sid == SECSID_NULL) {\n\t\t*peer_sid = nlbl_sid;\n\t\treturn 0;\n\t}\n\t/* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a \"fallback\" label\n\t * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label\n\t * is present */\n\tif (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {\n\t\t*peer_sid = xfrm_sid;\n\t\treturn 0;\n\t}",
"\t/* we don't need to check ss_initialized here since the only way both\n\t * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the\n\t * security server was initialized and ss_initialized was true */\n\tif (!policydb.mls_enabled)\n\t\treturn 0;",
"\tread_lock(&policy_rwlock);",
"\trc = -EINVAL;\n\tnlbl_ctx = sidtab_search(&sidtab, nlbl_sid);\n\tif (!nlbl_ctx) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, nlbl_sid);\n\t\tgoto out;\n\t}\n\trc = -EINVAL;\n\txfrm_ctx = sidtab_search(&sidtab, xfrm_sid);\n\tif (!xfrm_ctx) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, xfrm_sid);\n\t\tgoto out;\n\t}\n\trc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);\n\tif (rc)\n\t\tgoto out;",
"\t/* at present NetLabel SIDs/labels really only carry MLS\n\t * information so if the MLS portion of the NetLabel SID\n\t * matches the MLS portion of the labeled XFRM SID/label\n\t * then pass along the XFRM SID as it is the most\n\t * expressive */\n\t*peer_sid = xfrm_sid;\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"static int get_classes_callback(void *k, void *d, void *args)\n{\n\tstruct class_datum *datum = d;\n\tchar *name = k, **classes = args;\n\tint value = datum->value - 1;",
"\tclasses[value] = kstrdup(name, GFP_ATOMIC);\n\tif (!classes[value])\n\t\treturn -ENOMEM;",
"\treturn 0;\n}",
"int security_get_classes(char ***classes, int *nclasses)\n{\n\tint rc;",
"\tread_lock(&policy_rwlock);",
"\trc = -ENOMEM;\n\t*nclasses = policydb.p_classes.nprim;\n\t*classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);\n\tif (!*classes)\n\t\tgoto out;",
"\trc = hashtab_map(policydb.p_classes.table, get_classes_callback,\n\t\t\t*classes);\n\tif (rc) {\n\t\tint i;\n\t\tfor (i = 0; i < *nclasses; i++)\n\t\t\tkfree((*classes)[i]);\n\t\tkfree(*classes);\n\t}",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"static int get_permissions_callback(void *k, void *d, void *args)\n{\n\tstruct perm_datum *datum = d;\n\tchar *name = k, **perms = args;\n\tint value = datum->value - 1;",
"\tperms[value] = kstrdup(name, GFP_ATOMIC);\n\tif (!perms[value])\n\t\treturn -ENOMEM;",
"\treturn 0;\n}",
"int security_get_permissions(char *class, char ***perms, int *nperms)\n{\n\tint rc, i;\n\tstruct class_datum *match;",
"\tread_lock(&policy_rwlock);",
"\trc = -EINVAL;\n\tmatch = hashtab_search(policydb.p_classes.table, class);\n\tif (!match) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized class %s\\n\",\n\t\t\t__func__, class);\n\t\tgoto out;\n\t}",
"\trc = -ENOMEM;\n\t*nperms = match->permissions.nprim;\n\t*perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);\n\tif (!*perms)\n\t\tgoto out;",
"\tif (match->comdatum) {\n\t\trc = hashtab_map(match->comdatum->permissions.table,\n\t\t\t\tget_permissions_callback, *perms);\n\t\tif (rc)\n\t\t\tgoto err;\n\t}",
"\trc = hashtab_map(match->permissions.table, get_permissions_callback,\n\t\t\t*perms);\n\tif (rc)\n\t\tgoto err;",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;",
"err:\n\tread_unlock(&policy_rwlock);\n\tfor (i = 0; i < *nperms; i++)\n\t\tkfree((*perms)[i]);\n\tkfree(*perms);\n\treturn rc;\n}",
"int security_get_reject_unknown(void)\n{\n\treturn policydb.reject_unknown;\n}",
"int security_get_allow_unknown(void)\n{\n\treturn policydb.allow_unknown;\n}",
"/**\n * security_policycap_supported - Check for a specific policy capability\n * @req_cap: capability\n *\n * Description:\n * This function queries the currently loaded policy to see if it supports the\n * capability specified by @req_cap. Returns true (1) if the capability is\n * supported, false (0) if it isn't supported.\n *\n */\nint security_policycap_supported(unsigned int req_cap)\n{\n\tint rc;",
"\tread_lock(&policy_rwlock);\n\trc = ebitmap_get_bit(&policydb.policycaps, req_cap);\n\tread_unlock(&policy_rwlock);",
"\treturn rc;\n}",
"struct selinux_audit_rule {\n\tu32 au_seqno;\n\tstruct context au_ctxt;\n};",
"void selinux_audit_rule_free(void *vrule)\n{\n\tstruct selinux_audit_rule *rule = vrule;",
"\tif (rule) {\n\t\tcontext_destroy(&rule->au_ctxt);\n\t\tkfree(rule);\n\t}\n}",
"int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)\n{\n\tstruct selinux_audit_rule *tmprule;\n\tstruct role_datum *roledatum;\n\tstruct type_datum *typedatum;\n\tstruct user_datum *userdatum;\n\tstruct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;\n\tint rc = 0;",
"\t*rule = NULL;",
"\tif (!ss_initialized)\n\t\treturn -EOPNOTSUPP;",
"\tswitch (field) {\n\tcase AUDIT_SUBJ_USER:\n\tcase AUDIT_SUBJ_ROLE:\n\tcase AUDIT_SUBJ_TYPE:\n\tcase AUDIT_OBJ_USER:\n\tcase AUDIT_OBJ_ROLE:\n\tcase AUDIT_OBJ_TYPE:\n\t\t/* only 'equals' and 'not equals' fit user, role, and type */\n\t\tif (op != Audit_equal && op != Audit_not_equal)\n\t\t\treturn -EINVAL;\n\t\tbreak;\n\tcase AUDIT_SUBJ_SEN:\n\tcase AUDIT_SUBJ_CLR:\n\tcase AUDIT_OBJ_LEV_LOW:\n\tcase AUDIT_OBJ_LEV_HIGH:\n\t\t/* we do not allow a range, indicated by the presence of '-' */\n\t\tif (strchr(rulestr, '-'))\n\t\t\treturn -EINVAL;\n\t\tbreak;\n\tdefault:\n\t\t/* only the above fields are valid */\n\t\treturn -EINVAL;\n\t}",
"\ttmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);\n\tif (!tmprule)\n\t\treturn -ENOMEM;",
"\tcontext_init(&tmprule->au_ctxt);",
"\tread_lock(&policy_rwlock);",
"\ttmprule->au_seqno = latest_granting;",
"\tswitch (field) {\n\tcase AUDIT_SUBJ_USER:\n\tcase AUDIT_OBJ_USER:\n\t\trc = -EINVAL;\n\t\tuserdatum = hashtab_search(policydb.p_users.table, rulestr);\n\t\tif (!userdatum)\n\t\t\tgoto out;\n\t\ttmprule->au_ctxt.user = userdatum->value;\n\t\tbreak;\n\tcase AUDIT_SUBJ_ROLE:\n\tcase AUDIT_OBJ_ROLE:\n\t\trc = -EINVAL;\n\t\troledatum = hashtab_search(policydb.p_roles.table, rulestr);\n\t\tif (!roledatum)\n\t\t\tgoto out;\n\t\ttmprule->au_ctxt.role = roledatum->value;\n\t\tbreak;\n\tcase AUDIT_SUBJ_TYPE:\n\tcase AUDIT_OBJ_TYPE:\n\t\trc = -EINVAL;\n\t\ttypedatum = hashtab_search(policydb.p_types.table, rulestr);\n\t\tif (!typedatum)\n\t\t\tgoto out;\n\t\ttmprule->au_ctxt.type = typedatum->value;\n\t\tbreak;\n\tcase AUDIT_SUBJ_SEN:\n\tcase AUDIT_SUBJ_CLR:\n\tcase AUDIT_OBJ_LEV_LOW:\n\tcase AUDIT_OBJ_LEV_HIGH:\n\t\trc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);\n\t\tif (rc)\n\t\t\tgoto out;\n\t\tbreak;\n\t}\n\trc = 0;\nout:\n\tread_unlock(&policy_rwlock);",
"\tif (rc) {\n\t\tselinux_audit_rule_free(tmprule);\n\t\ttmprule = NULL;\n\t}",
"\t*rule = tmprule;",
"\treturn rc;\n}",
"/* Check to see if the rule contains any selinux fields */\nint selinux_audit_rule_known(struct audit_krule *rule)\n{\n\tint i;",
"\tfor (i = 0; i < rule->field_count; i++) {\n\t\tstruct audit_field *f = &rule->fields[i];\n\t\tswitch (f->type) {\n\t\tcase AUDIT_SUBJ_USER:\n\t\tcase AUDIT_SUBJ_ROLE:\n\t\tcase AUDIT_SUBJ_TYPE:\n\t\tcase AUDIT_SUBJ_SEN:\n\t\tcase AUDIT_SUBJ_CLR:\n\t\tcase AUDIT_OBJ_USER:\n\t\tcase AUDIT_OBJ_ROLE:\n\t\tcase AUDIT_OBJ_TYPE:\n\t\tcase AUDIT_OBJ_LEV_LOW:\n\t\tcase AUDIT_OBJ_LEV_HIGH:\n\t\t\treturn 1;\n\t\t}\n\t}",
"\treturn 0;\n}",
"int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,\n\t\t\t struct audit_context *actx)\n{\n\tstruct context *ctxt;\n\tstruct mls_level *level;\n\tstruct selinux_audit_rule *rule = vrule;\n\tint match = 0;",
"\tif (!rule) {\n\t\taudit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t\t \"selinux_audit_rule_match: missing rule\\n\");\n\t\treturn -ENOENT;\n\t}",
"\tread_lock(&policy_rwlock);",
"\tif (rule->au_seqno < latest_granting) {\n\t\taudit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t\t \"selinux_audit_rule_match: stale rule\\n\");\n\t\tmatch = -ESTALE;\n\t\tgoto out;\n\t}",
"\tctxt = sidtab_search(&sidtab, sid);\n\tif (!ctxt) {\n\t\taudit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t\t \"selinux_audit_rule_match: unrecognized SID %d\\n\",\n\t\t\t sid);\n\t\tmatch = -ENOENT;\n\t\tgoto out;\n\t}",
"\t/* a field/op pair that is not caught here will simply fall through\n\t without a match */\n\tswitch (field) {\n\tcase AUDIT_SUBJ_USER:\n\tcase AUDIT_OBJ_USER:\n\t\tswitch (op) {\n\t\tcase Audit_equal:\n\t\t\tmatch = (ctxt->user == rule->au_ctxt.user);\n\t\t\tbreak;\n\t\tcase Audit_not_equal:\n\t\t\tmatch = (ctxt->user != rule->au_ctxt.user);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase AUDIT_SUBJ_ROLE:\n\tcase AUDIT_OBJ_ROLE:\n\t\tswitch (op) {\n\t\tcase Audit_equal:\n\t\t\tmatch = (ctxt->role == rule->au_ctxt.role);\n\t\t\tbreak;\n\t\tcase Audit_not_equal:\n\t\t\tmatch = (ctxt->role != rule->au_ctxt.role);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase AUDIT_SUBJ_TYPE:\n\tcase AUDIT_OBJ_TYPE:\n\t\tswitch (op) {\n\t\tcase Audit_equal:\n\t\t\tmatch = (ctxt->type == rule->au_ctxt.type);\n\t\t\tbreak;\n\t\tcase Audit_not_equal:\n\t\t\tmatch = (ctxt->type != rule->au_ctxt.type);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase AUDIT_SUBJ_SEN:\n\tcase AUDIT_SUBJ_CLR:\n\tcase AUDIT_OBJ_LEV_LOW:\n\tcase AUDIT_OBJ_LEV_HIGH:\n\t\tlevel = ((field == AUDIT_SUBJ_SEN ||\n\t\t\t field == AUDIT_OBJ_LEV_LOW) ?\n\t\t\t &ctxt->range.level[0] : &ctxt->range.level[1]);\n\t\tswitch (op) {\n\t\tcase Audit_equal:\n\t\t\tmatch = mls_level_eq(&rule->au_ctxt.range.level[0],\n\t\t\t\t\t level);\n\t\t\tbreak;\n\t\tcase Audit_not_equal:\n\t\t\tmatch = !mls_level_eq(&rule->au_ctxt.range.level[0],\n\t\t\t\t\t level);\n\t\t\tbreak;\n\t\tcase Audit_lt:\n\t\t\tmatch = (mls_level_dom(&rule->au_ctxt.range.level[0],\n\t\t\t\t\t level) &&\n\t\t\t\t !mls_level_eq(&rule->au_ctxt.range.level[0],\n\t\t\t\t\t level));\n\t\t\tbreak;\n\t\tcase Audit_le:\n\t\t\tmatch = mls_level_dom(&rule->au_ctxt.range.level[0],\n\t\t\t\t\t level);\n\t\t\tbreak;\n\t\tcase Audit_gt:\n\t\t\tmatch = (mls_level_dom(level,\n\t\t\t\t\t &rule->au_ctxt.range.level[0]) &&\n\t\t\t\t !mls_level_eq(level,\n\t\t\t\t\t &rule->au_ctxt.range.level[0]));\n\t\t\tbreak;\n\t\tcase Audit_ge:\n\t\t\tmatch = mls_level_dom(level,\n\t\t\t\t\t &rule->au_ctxt.range.level[0]);\n\t\t\tbreak;\n\t\t}\n\t}",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn match;\n}",
"static int (*aurule_callback)(void) = audit_update_lsm_rules;",
"static int aurule_avc_callback(u32 event)\n{\n\tint err = 0;",
"\tif (event == AVC_CALLBACK_RESET && aurule_callback)\n\t\terr = aurule_callback();\n\treturn err;\n}",
"static int __init aurule_init(void)\n{\n\tint err;",
"\terr = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);\n\tif (err)\n\t\tpanic(\"avc_add_callback() failed, error %d\\n\", err);",
"\treturn err;\n}\n__initcall(aurule_init);",
"#ifdef CONFIG_NETLABEL\n/**\n * security_netlbl_cache_add - Add an entry to the NetLabel cache\n * @secattr: the NetLabel packet security attributes\n * @sid: the SELinux SID\n *\n * Description:\n * Attempt to cache the context in @ctx, which was derived from the packet in\n * @skb, in the NetLabel subsystem cache. This function assumes @secattr has\n * already been initialized.\n *\n */\nstatic void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,\n\t\t\t\t u32 sid)\n{\n\tu32 *sid_cache;",
"\tsid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);\n\tif (sid_cache == NULL)\n\t\treturn;\n\tsecattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);\n\tif (secattr->cache == NULL) {\n\t\tkfree(sid_cache);\n\t\treturn;\n\t}",
"\t*sid_cache = sid;\n\tsecattr->cache->free = kfree;\n\tsecattr->cache->data = sid_cache;\n\tsecattr->flags |= NETLBL_SECATTR_CACHE;\n}",
"/**\n * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID\n * @secattr: the NetLabel packet security attributes\n * @sid: the SELinux SID\n *\n * Description:\n * Convert the given NetLabel security attributes in @secattr into a\n * SELinux SID. If the @secattr field does not contain a full SELinux\n * SID/context then use SECINITSID_NETMSG as the foundation. If possible the\n * 'cache' field of @secattr is set and the CACHE flag is set; this is to\n * allow the @secattr to be used by NetLabel to cache the secattr to SID\n * conversion for future lookups. Returns zero on success, negative values on\n * failure.\n *\n */\nint security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,\n\t\t\t\t u32 *sid)\n{\n\tint rc;\n\tstruct context *ctx;\n\tstruct context ctx_new;",
"\tif (!ss_initialized) {\n\t\t*sid = SECSID_NULL;\n\t\treturn 0;\n\t}",
"\tread_lock(&policy_rwlock);",
"\tif (secattr->flags & NETLBL_SECATTR_CACHE)\n\t\t*sid = *(u32 *)secattr->cache->data;\n\telse if (secattr->flags & NETLBL_SECATTR_SECID)\n\t\t*sid = secattr->attr.secid;\n\telse if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {\n\t\trc = -EIDRM;\n\t\tctx = sidtab_search(&sidtab, SECINITSID_NETMSG);\n\t\tif (ctx == NULL)\n\t\t\tgoto out;",
"\t\tcontext_init(&ctx_new);\n\t\tctx_new.user = ctx->user;\n\t\tctx_new.role = ctx->role;\n\t\tctx_new.type = ctx->type;\n\t\tmls_import_netlbl_lvl(&ctx_new, secattr);\n\t\tif (secattr->flags & NETLBL_SECATTR_MLS_CAT) {\n\t\t\trc = ebitmap_netlbl_import(&ctx_new.range.level[0].cat,\n\t\t\t\t\t\t secattr->attr.mls.cat);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t\tmemcpy(&ctx_new.range.level[1].cat,\n\t\t\t &ctx_new.range.level[0].cat,\n\t\t\t sizeof(ctx_new.range.level[0].cat));\n\t\t}\n\t\trc = -EIDRM;\n\t\tif (!mls_context_isvalid(&policydb, &ctx_new))\n\t\t\tgoto out_free;",
"\t\trc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);\n\t\tif (rc)\n\t\t\tgoto out_free;",
"\t\tsecurity_netlbl_cache_add(secattr, *sid);",
"\t\tebitmap_destroy(&ctx_new.range.level[0].cat);\n\t} else\n\t\t*sid = SECSID_NULL;",
"\tread_unlock(&policy_rwlock);\n\treturn 0;\nout_free:\n\tebitmap_destroy(&ctx_new.range.level[0].cat);\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"/**\n * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr\n * @sid: the SELinux SID\n * @secattr: the NetLabel packet security attributes\n *\n * Description:\n * Convert the given SELinux SID in @sid into a NetLabel security attribute.\n * Returns zero on success, negative values on failure.\n *\n */\nint security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)\n{\n\tint rc;\n\tstruct context *ctx;",
"\tif (!ss_initialized)\n\t\treturn 0;",
"\tread_lock(&policy_rwlock);",
"\trc = -ENOENT;\n\tctx = sidtab_search(&sidtab, sid);\n\tif (ctx == NULL)\n\t\tgoto out;",
"\trc = -ENOMEM;\n\tsecattr->domain = kstrdup(sym_name(&policydb, SYM_TYPES, ctx->type - 1),\n\t\t\t\t GFP_ATOMIC);\n\tif (secattr->domain == NULL)\n\t\tgoto out;",
"\tsecattr->attr.secid = sid;\n\tsecattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;\n\tmls_export_netlbl_lvl(ctx, secattr);\n\trc = mls_export_netlbl_cat(ctx, secattr);\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}\n#endif /* CONFIG_NETLABEL */",
"/**\n * security_read_policy - read the policy.\n * @data: binary policy data\n * @len: length of data in bytes\n *\n */\nint security_read_policy(void **data, size_t *len)\n{\n\tint rc;\n\tstruct policy_file fp;",
"\tif (!ss_initialized)\n\t\treturn -EINVAL;",
"\t*len = security_policydb_len();",
"\t*data = vmalloc_user(*len);\n\tif (!*data)\n\t\treturn -ENOMEM;",
"\tfp.data = *data;\n\tfp.len = *len;",
"\tread_lock(&policy_rwlock);\n\trc = policydb_write(&policydb, &fp);\n\tread_unlock(&policy_rwlock);",
"\tif (rc)\n\t\treturn rc;",
"\t*len = (unsigned long)fp.data - (unsigned long)*data;\n\treturn 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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [1234], "buggy_code_start_loc": [1234], "filenames": ["security/selinux/ss/services.c"], "fixing_code_end_loc": [1239], "fixing_code_start_loc": [1235], "message": "The security_context_to_sid_core function in security/selinux/ss/services.c in the Linux kernel before 3.13.4 allows local users to cause a denial of service (system crash) by leveraging the CAP_MAC_ADMIN capability to set a zero-length security context.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "C5D0B9E7-C5EF-4C15-BD87-FA13FD781E06", "versionEndExcluding": "3.13.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:suse:linux_enterprise_server:10:sp4:*:*:ltss:*:*:*", "matchCriteriaId": "35BBD83D-BDC7-4678-BE94-639F59281139", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:10.04:*:*:*:-:*:*:*", "matchCriteriaId": "01EDA41C-6B2E-49AF-B503-EB3882265C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:esm:*:*:*", "matchCriteriaId": "8D305F7A-D159-4716-AB26-5E38BB5CD991", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.10:*:*:*:*:*:*:*", "matchCriteriaId": "E2076871-2E80-4605-A470-A41C1A8EC7EE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:13.10:*:*:*:*:*:*:*", "matchCriteriaId": "7F61F047-129C-41A6-8A27-FFCBB8563E91", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The security_context_to_sid_core function in security/selinux/ss/services.c in the Linux kernel before 3.13.4 allows local users to cause a denial of service (system crash) by leveraging the CAP_MAC_ADMIN capability to set a zero-length security context."}, {"lang": "es", "value": "La funci\u00f3n security_context_to_sid_core en security/selinux/ss/services.c en el kernel de Linux anterior a 3.13.4 permite a usuarios locales causar una denegaci\u00f3n de servicio (ca\u00edda del sistema) mediante el aprovechamiento de la funcionalidad CAP_MAC_ADMIN para configurar un contexto de seguridad de longitud cero."}], "evaluatorComment": null, "id": "CVE-2014-1874", "lastModified": "2023-02-13T00:38:31.907", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.9, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-02-28T06:18:54.587", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git%3Ba=commit%3Bh=2172fa709ab32ca60e86179dc67d0857be8e2c98"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://linux.oracle.com/errata/ELSA-2014-0771.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://linux.oracle.com/errata/ELSA-2014-3043.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-04/msg00020.html"}, {"source": "secalert@redhat.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "http://www.kernel.org/pub/linux/kernel/v3.x/ChangeLog-3.13.4"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/02/07/2"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/65459"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2128-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2129-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2133-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2134-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2135-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2136-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2137-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2138-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2139-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2140-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2141-1"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1062356"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/2172fa709ab32ca60e86179dc67d0857be8e2c98"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-20"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/2172fa709ab32ca60e86179dc67d0857be8e2c98"}, "type": "CWE-20"}
| 262
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * Implementation of the security services.\n *\n * Authors : Stephen Smalley, <sds@epoch.ncsc.mil>\n *\t James Morris <jmorris@redhat.com>\n *\n * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>\n *\n *\tSupport for enhanced MLS infrastructure.\n *\tSupport for context based audit filters.\n *\n * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>\n *\n *\tAdded conditional policy language extensions\n *\n * Updated: Hewlett-Packard <paul@paul-moore.com>\n *\n * Added support for NetLabel\n * Added support for the policy capability bitmap\n *\n * Updated: Chad Sellers <csellers@tresys.com>\n *\n * Added validation of kernel classes and permissions\n *\n * Updated: KaiGai Kohei <kaigai@ak.jp.nec.com>\n *\n * Added support for bounds domain and audit messaged on masked permissions\n *\n * Updated: Guido Trentalancia <guido@trentalancia.com>\n *\n * Added support for runtime switching of the policy type\n *\n * Copyright (C) 2008, 2009 NEC Corporation\n * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.\n * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.\n * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC\n * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>\n *\tThis program is free software; you can redistribute it and/or modify\n *\tit under the terms of the GNU General Public License as published by\n *\tthe Free Software Foundation, version 2.\n */\n#include <linux/kernel.h>\n#include <linux/slab.h>\n#include <linux/string.h>\n#include <linux/spinlock.h>\n#include <linux/rcupdate.h>\n#include <linux/errno.h>\n#include <linux/in.h>\n#include <linux/sched.h>\n#include <linux/audit.h>\n#include <linux/mutex.h>\n#include <linux/selinux.h>\n#include <linux/flex_array.h>\n#include <linux/vmalloc.h>\n#include <net/netlabel.h>",
"#include \"flask.h\"\n#include \"avc.h\"\n#include \"avc_ss.h\"\n#include \"security.h\"\n#include \"context.h\"\n#include \"policydb.h\"\n#include \"sidtab.h\"\n#include \"services.h\"\n#include \"conditional.h\"\n#include \"mls.h\"\n#include \"objsec.h\"\n#include \"netlabel.h\"\n#include \"xfrm.h\"\n#include \"ebitmap.h\"\n#include \"audit.h\"",
"int selinux_policycap_netpeer;\nint selinux_policycap_openperm;\nint selinux_policycap_alwaysnetwork;",
"static DEFINE_RWLOCK(policy_rwlock);",
"static struct sidtab sidtab;\nstruct policydb policydb;\nint ss_initialized;",
"/*\n * The largest sequence number that has been used when\n * providing an access decision to the access vector cache.\n * The sequence number only changes when a policy change\n * occurs.\n */\nstatic u32 latest_granting;",
"/* Forward declaration. */\nstatic int context_struct_to_string(struct context *context, char **scontext,\n\t\t\t\t u32 *scontext_len);",
"static void context_struct_compute_av(struct context *scontext,\n\t\t\t\t struct context *tcontext,\n\t\t\t\t u16 tclass,\n\t\t\t\t struct av_decision *avd);",
"struct selinux_mapping {\n\tu16 value; /* policy value */\n\tunsigned num_perms;\n\tu32 perms[sizeof(u32) * 8];\n};",
"static struct selinux_mapping *current_mapping;\nstatic u16 current_mapping_size;",
"static int selinux_set_mapping(struct policydb *pol,\n\t\t\t struct security_class_mapping *map,\n\t\t\t struct selinux_mapping **out_map_p,\n\t\t\t u16 *out_map_size)\n{\n\tstruct selinux_mapping *out_map = NULL;\n\tsize_t size = sizeof(struct selinux_mapping);\n\tu16 i, j;\n\tunsigned k;\n\tbool print_unknown_handle = false;",
"\t/* Find number of classes in the input mapping */\n\tif (!map)\n\t\treturn -EINVAL;\n\ti = 0;\n\twhile (map[i].name)\n\t\ti++;",
"\t/* Allocate space for the class records, plus one for class zero */\n\tout_map = kcalloc(++i, size, GFP_ATOMIC);\n\tif (!out_map)\n\t\treturn -ENOMEM;",
"\t/* Store the raw class and permission values */\n\tj = 0;\n\twhile (map[j].name) {\n\t\tstruct security_class_mapping *p_in = map + (j++);\n\t\tstruct selinux_mapping *p_out = out_map + j;",
"\t\t/* An empty class string skips ahead */\n\t\tif (!strcmp(p_in->name, \"\")) {\n\t\t\tp_out->num_perms = 0;\n\t\t\tcontinue;\n\t\t}",
"\t\tp_out->value = string_to_security_class(pol, p_in->name);\n\t\tif (!p_out->value) {\n\t\t\tprintk(KERN_INFO\n\t\t\t \"SELinux: Class %s not defined in policy.\\n\",\n\t\t\t p_in->name);\n\t\t\tif (pol->reject_unknown)\n\t\t\t\tgoto err;\n\t\t\tp_out->num_perms = 0;\n\t\t\tprint_unknown_handle = true;\n\t\t\tcontinue;\n\t\t}",
"\t\tk = 0;\n\t\twhile (p_in->perms && p_in->perms[k]) {\n\t\t\t/* An empty permission string skips ahead */\n\t\t\tif (!*p_in->perms[k]) {\n\t\t\t\tk++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tp_out->perms[k] = string_to_av_perm(pol, p_out->value,\n\t\t\t\t\t\t\t p_in->perms[k]);\n\t\t\tif (!p_out->perms[k]) {\n\t\t\t\tprintk(KERN_INFO\n\t\t\t\t \"SELinux: Permission %s in class %s not defined in policy.\\n\",\n\t\t\t\t p_in->perms[k], p_in->name);\n\t\t\t\tif (pol->reject_unknown)\n\t\t\t\t\tgoto err;\n\t\t\t\tprint_unknown_handle = true;\n\t\t\t}",
"\t\t\tk++;\n\t\t}\n\t\tp_out->num_perms = k;\n\t}",
"\tif (print_unknown_handle)\n\t\tprintk(KERN_INFO \"SELinux: the above unknown classes and permissions will be %s\\n\",\n\t\t pol->allow_unknown ? \"allowed\" : \"denied\");",
"\t*out_map_p = out_map;\n\t*out_map_size = i;\n\treturn 0;\nerr:\n\tkfree(out_map);\n\treturn -EINVAL;\n}",
"/*\n * Get real, policy values from mapped values\n */",
"static u16 unmap_class(u16 tclass)\n{\n\tif (tclass < current_mapping_size)\n\t\treturn current_mapping[tclass].value;",
"\treturn tclass;\n}",
"/*\n * Get kernel value for class from its policy value\n */\nstatic u16 map_class(u16 pol_value)\n{\n\tu16 i;",
"\tfor (i = 1; i < current_mapping_size; i++) {\n\t\tif (current_mapping[i].value == pol_value)\n\t\t\treturn i;\n\t}",
"\treturn SECCLASS_NULL;\n}",
"static void map_decision(u16 tclass, struct av_decision *avd,\n\t\t\t int allow_unknown)\n{\n\tif (tclass < current_mapping_size) {\n\t\tunsigned i, n = current_mapping[tclass].num_perms;\n\t\tu32 result;",
"\t\tfor (i = 0, result = 0; i < n; i++) {\n\t\t\tif (avd->allowed & current_mapping[tclass].perms[i])\n\t\t\t\tresult |= 1<<i;\n\t\t\tif (allow_unknown && !current_mapping[tclass].perms[i])\n\t\t\t\tresult |= 1<<i;\n\t\t}\n\t\tavd->allowed = result;",
"\t\tfor (i = 0, result = 0; i < n; i++)\n\t\t\tif (avd->auditallow & current_mapping[tclass].perms[i])\n\t\t\t\tresult |= 1<<i;\n\t\tavd->auditallow = result;",
"\t\tfor (i = 0, result = 0; i < n; i++) {\n\t\t\tif (avd->auditdeny & current_mapping[tclass].perms[i])\n\t\t\t\tresult |= 1<<i;\n\t\t\tif (!allow_unknown && !current_mapping[tclass].perms[i])\n\t\t\t\tresult |= 1<<i;\n\t\t}\n\t\t/*\n\t\t * In case the kernel has a bug and requests a permission\n\t\t * between num_perms and the maximum permission number, we\n\t\t * should audit that denial\n\t\t */\n\t\tfor (; i < (sizeof(u32)*8); i++)\n\t\t\tresult |= 1<<i;\n\t\tavd->auditdeny = result;\n\t}\n}",
"int security_mls_enabled(void)\n{\n\treturn policydb.mls_enabled;\n}",
"/*\n * Return the boolean value of a constraint expression\n * when it is applied to the specified source and target\n * security contexts.\n *\n * xcontext is a special beast... It is used by the validatetrans rules\n * only. For these rules, scontext is the context before the transition,\n * tcontext is the context after the transition, and xcontext is the context\n * of the process performing the transition. All other callers of\n * constraint_expr_eval should pass in NULL for xcontext.\n */\nstatic int constraint_expr_eval(struct context *scontext,\n\t\t\t\tstruct context *tcontext,\n\t\t\t\tstruct context *xcontext,\n\t\t\t\tstruct constraint_expr *cexpr)\n{\n\tu32 val1, val2;\n\tstruct context *c;\n\tstruct role_datum *r1, *r2;\n\tstruct mls_level *l1, *l2;\n\tstruct constraint_expr *e;\n\tint s[CEXPR_MAXDEPTH];\n\tint sp = -1;",
"\tfor (e = cexpr; e; e = e->next) {\n\t\tswitch (e->expr_type) {\n\t\tcase CEXPR_NOT:\n\t\t\tBUG_ON(sp < 0);\n\t\t\ts[sp] = !s[sp];\n\t\t\tbreak;\n\t\tcase CEXPR_AND:\n\t\t\tBUG_ON(sp < 1);\n\t\t\tsp--;\n\t\t\ts[sp] &= s[sp + 1];\n\t\t\tbreak;\n\t\tcase CEXPR_OR:\n\t\t\tBUG_ON(sp < 1);\n\t\t\tsp--;\n\t\t\ts[sp] |= s[sp + 1];\n\t\t\tbreak;\n\t\tcase CEXPR_ATTR:\n\t\t\tif (sp == (CEXPR_MAXDEPTH - 1))\n\t\t\t\treturn 0;\n\t\t\tswitch (e->attr) {\n\t\t\tcase CEXPR_USER:\n\t\t\t\tval1 = scontext->user;\n\t\t\t\tval2 = tcontext->user;\n\t\t\t\tbreak;\n\t\t\tcase CEXPR_TYPE:\n\t\t\t\tval1 = scontext->type;\n\t\t\t\tval2 = tcontext->type;\n\t\t\t\tbreak;\n\t\t\tcase CEXPR_ROLE:\n\t\t\t\tval1 = scontext->role;\n\t\t\t\tval2 = tcontext->role;\n\t\t\t\tr1 = policydb.role_val_to_struct[val1 - 1];\n\t\t\t\tr2 = policydb.role_val_to_struct[val2 - 1];\n\t\t\t\tswitch (e->op) {\n\t\t\t\tcase CEXPR_DOM:\n\t\t\t\t\ts[++sp] = ebitmap_get_bit(&r1->dominates,\n\t\t\t\t\t\t\t\t val2 - 1);\n\t\t\t\t\tcontinue;\n\t\t\t\tcase CEXPR_DOMBY:\n\t\t\t\t\ts[++sp] = ebitmap_get_bit(&r2->dominates,\n\t\t\t\t\t\t\t\t val1 - 1);\n\t\t\t\t\tcontinue;\n\t\t\t\tcase CEXPR_INCOMP:\n\t\t\t\t\ts[++sp] = (!ebitmap_get_bit(&r1->dominates,\n\t\t\t\t\t\t\t\t val2 - 1) &&\n\t\t\t\t\t\t !ebitmap_get_bit(&r2->dominates,\n\t\t\t\t\t\t\t\t val1 - 1));\n\t\t\t\t\tcontinue;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CEXPR_L1L2:\n\t\t\t\tl1 = &(scontext->range.level[0]);\n\t\t\t\tl2 = &(tcontext->range.level[0]);\n\t\t\t\tgoto mls_ops;\n\t\t\tcase CEXPR_L1H2:\n\t\t\t\tl1 = &(scontext->range.level[0]);\n\t\t\t\tl2 = &(tcontext->range.level[1]);\n\t\t\t\tgoto mls_ops;\n\t\t\tcase CEXPR_H1L2:\n\t\t\t\tl1 = &(scontext->range.level[1]);\n\t\t\t\tl2 = &(tcontext->range.level[0]);\n\t\t\t\tgoto mls_ops;\n\t\t\tcase CEXPR_H1H2:\n\t\t\t\tl1 = &(scontext->range.level[1]);\n\t\t\t\tl2 = &(tcontext->range.level[1]);\n\t\t\t\tgoto mls_ops;\n\t\t\tcase CEXPR_L1H1:\n\t\t\t\tl1 = &(scontext->range.level[0]);\n\t\t\t\tl2 = &(scontext->range.level[1]);\n\t\t\t\tgoto mls_ops;\n\t\t\tcase CEXPR_L2H2:\n\t\t\t\tl1 = &(tcontext->range.level[0]);\n\t\t\t\tl2 = &(tcontext->range.level[1]);\n\t\t\t\tgoto mls_ops;\nmls_ops:\n\t\t\tswitch (e->op) {\n\t\t\tcase CEXPR_EQ:\n\t\t\t\ts[++sp] = mls_level_eq(l1, l2);\n\t\t\t\tcontinue;\n\t\t\tcase CEXPR_NEQ:\n\t\t\t\ts[++sp] = !mls_level_eq(l1, l2);\n\t\t\t\tcontinue;\n\t\t\tcase CEXPR_DOM:\n\t\t\t\ts[++sp] = mls_level_dom(l1, l2);\n\t\t\t\tcontinue;\n\t\t\tcase CEXPR_DOMBY:\n\t\t\t\ts[++sp] = mls_level_dom(l2, l1);\n\t\t\t\tcontinue;\n\t\t\tcase CEXPR_INCOMP:\n\t\t\t\ts[++sp] = mls_level_incomp(l2, l1);\n\t\t\t\tcontinue;\n\t\t\tdefault:\n\t\t\t\tBUG();\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tBUG();\n\t\t\t\treturn 0;\n\t\t\t}",
"\t\t\tswitch (e->op) {\n\t\t\tcase CEXPR_EQ:\n\t\t\t\ts[++sp] = (val1 == val2);\n\t\t\t\tbreak;\n\t\t\tcase CEXPR_NEQ:\n\t\t\t\ts[++sp] = (val1 != val2);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tBUG();\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CEXPR_NAMES:\n\t\t\tif (sp == (CEXPR_MAXDEPTH-1))\n\t\t\t\treturn 0;\n\t\t\tc = scontext;\n\t\t\tif (e->attr & CEXPR_TARGET)\n\t\t\t\tc = tcontext;\n\t\t\telse if (e->attr & CEXPR_XTARGET) {\n\t\t\t\tc = xcontext;\n\t\t\t\tif (!c) {\n\t\t\t\t\tBUG();\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (e->attr & CEXPR_USER)\n\t\t\t\tval1 = c->user;\n\t\t\telse if (e->attr & CEXPR_ROLE)\n\t\t\t\tval1 = c->role;\n\t\t\telse if (e->attr & CEXPR_TYPE)\n\t\t\t\tval1 = c->type;\n\t\t\telse {\n\t\t\t\tBUG();\n\t\t\t\treturn 0;\n\t\t\t}",
"\t\t\tswitch (e->op) {\n\t\t\tcase CEXPR_EQ:\n\t\t\t\ts[++sp] = ebitmap_get_bit(&e->names, val1 - 1);\n\t\t\t\tbreak;\n\t\t\tcase CEXPR_NEQ:\n\t\t\t\ts[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tBUG();\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tBUG();\n\t\t\treturn 0;\n\t\t}\n\t}",
"\tBUG_ON(sp != 0);\n\treturn s[0];\n}",
"/*\n * security_dump_masked_av - dumps masked permissions during\n * security_compute_av due to RBAC, MLS/Constraint and Type bounds.\n */\nstatic int dump_masked_av_helper(void *k, void *d, void *args)\n{\n\tstruct perm_datum *pdatum = d;\n\tchar **permission_names = args;",
"\tBUG_ON(pdatum->value < 1 || pdatum->value > 32);",
"\tpermission_names[pdatum->value - 1] = (char *)k;",
"\treturn 0;\n}",
"static void security_dump_masked_av(struct context *scontext,\n\t\t\t\t struct context *tcontext,\n\t\t\t\t u16 tclass,\n\t\t\t\t u32 permissions,\n\t\t\t\t const char *reason)\n{\n\tstruct common_datum *common_dat;\n\tstruct class_datum *tclass_dat;\n\tstruct audit_buffer *ab;\n\tchar *tclass_name;\n\tchar *scontext_name = NULL;\n\tchar *tcontext_name = NULL;\n\tchar *permission_names[32];\n\tint index;\n\tu32 length;\n\tbool need_comma = false;",
"\tif (!permissions)\n\t\treturn;",
"\ttclass_name = sym_name(&policydb, SYM_CLASSES, tclass - 1);\n\ttclass_dat = policydb.class_val_to_struct[tclass - 1];\n\tcommon_dat = tclass_dat->comdatum;",
"\t/* init permission_names */\n\tif (common_dat &&\n\t hashtab_map(common_dat->permissions.table,\n\t\t\tdump_masked_av_helper, permission_names) < 0)\n\t\tgoto out;",
"\tif (hashtab_map(tclass_dat->permissions.table,\n\t\t\tdump_masked_av_helper, permission_names) < 0)\n\t\tgoto out;",
"\t/* get scontext/tcontext in text form */\n\tif (context_struct_to_string(scontext,\n\t\t\t\t &scontext_name, &length) < 0)\n\t\tgoto out;",
"\tif (context_struct_to_string(tcontext,\n\t\t\t\t &tcontext_name, &length) < 0)\n\t\tgoto out;",
"\t/* audit a message */\n\tab = audit_log_start(current->audit_context,\n\t\t\t GFP_ATOMIC, AUDIT_SELINUX_ERR);\n\tif (!ab)\n\t\tgoto out;",
"\taudit_log_format(ab, \"op=security_compute_av reason=%s \"\n\t\t\t \"scontext=%s tcontext=%s tclass=%s perms=\",\n\t\t\t reason, scontext_name, tcontext_name, tclass_name);",
"\tfor (index = 0; index < 32; index++) {\n\t\tu32 mask = (1 << index);",
"\t\tif ((mask & permissions) == 0)\n\t\t\tcontinue;",
"\t\taudit_log_format(ab, \"%s%s\",\n\t\t\t\t need_comma ? \",\" : \"\",\n\t\t\t\t permission_names[index]\n\t\t\t\t ? permission_names[index] : \"????\");\n\t\tneed_comma = true;\n\t}\n\taudit_log_end(ab);\nout:\n\t/* release scontext/tcontext */\n\tkfree(tcontext_name);\n\tkfree(scontext_name);",
"\treturn;\n}",
"/*\n * security_boundary_permission - drops violated permissions\n * on boundary constraint.\n */\nstatic void type_attribute_bounds_av(struct context *scontext,\n\t\t\t\t struct context *tcontext,\n\t\t\t\t u16 tclass,\n\t\t\t\t struct av_decision *avd)\n{\n\tstruct context lo_scontext;\n\tstruct context lo_tcontext;\n\tstruct av_decision lo_avd;\n\tstruct type_datum *source;\n\tstruct type_datum *target;\n\tu32 masked = 0;",
"\tsource = flex_array_get_ptr(policydb.type_val_to_struct_array,\n\t\t\t\t scontext->type - 1);\n\tBUG_ON(!source);",
"\ttarget = flex_array_get_ptr(policydb.type_val_to_struct_array,\n\t\t\t\t tcontext->type - 1);\n\tBUG_ON(!target);",
"\tif (source->bounds) {\n\t\tmemset(&lo_avd, 0, sizeof(lo_avd));",
"\t\tmemcpy(&lo_scontext, scontext, sizeof(lo_scontext));\n\t\tlo_scontext.type = source->bounds;",
"\t\tcontext_struct_compute_av(&lo_scontext,\n\t\t\t\t\t tcontext,\n\t\t\t\t\t tclass,\n\t\t\t\t\t &lo_avd);\n\t\tif ((lo_avd.allowed & avd->allowed) == avd->allowed)\n\t\t\treturn;\t\t/* no masked permission */\n\t\tmasked = ~lo_avd.allowed & avd->allowed;\n\t}",
"\tif (target->bounds) {\n\t\tmemset(&lo_avd, 0, sizeof(lo_avd));",
"\t\tmemcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));\n\t\tlo_tcontext.type = target->bounds;",
"\t\tcontext_struct_compute_av(scontext,\n\t\t\t\t\t &lo_tcontext,\n\t\t\t\t\t tclass,\n\t\t\t\t\t &lo_avd);\n\t\tif ((lo_avd.allowed & avd->allowed) == avd->allowed)\n\t\t\treturn;\t\t/* no masked permission */\n\t\tmasked = ~lo_avd.allowed & avd->allowed;\n\t}",
"\tif (source->bounds && target->bounds) {\n\t\tmemset(&lo_avd, 0, sizeof(lo_avd));\n\t\t/*\n\t\t * lo_scontext and lo_tcontext are already\n\t\t * set up.\n\t\t */",
"\t\tcontext_struct_compute_av(&lo_scontext,\n\t\t\t\t\t &lo_tcontext,\n\t\t\t\t\t tclass,\n\t\t\t\t\t &lo_avd);\n\t\tif ((lo_avd.allowed & avd->allowed) == avd->allowed)\n\t\t\treturn;\t\t/* no masked permission */\n\t\tmasked = ~lo_avd.allowed & avd->allowed;\n\t}",
"\tif (masked) {\n\t\t/* mask violated permissions */\n\t\tavd->allowed &= ~masked;",
"\t\t/* audit masked permissions */\n\t\tsecurity_dump_masked_av(scontext, tcontext,\n\t\t\t\t\ttclass, masked, \"bounds\");\n\t}\n}",
"/*\n * Compute access vectors based on a context structure pair for\n * the permissions in a particular class.\n */\nstatic void context_struct_compute_av(struct context *scontext,\n\t\t\t\t struct context *tcontext,\n\t\t\t\t u16 tclass,\n\t\t\t\t struct av_decision *avd)\n{\n\tstruct constraint_node *constraint;\n\tstruct role_allow *ra;\n\tstruct avtab_key avkey;\n\tstruct avtab_node *node;\n\tstruct class_datum *tclass_datum;\n\tstruct ebitmap *sattr, *tattr;\n\tstruct ebitmap_node *snode, *tnode;\n\tunsigned int i, j;",
"\tavd->allowed = 0;\n\tavd->auditallow = 0;\n\tavd->auditdeny = 0xffffffff;",
"\tif (unlikely(!tclass || tclass > policydb.p_classes.nprim)) {\n\t\tif (printk_ratelimit())\n\t\t\tprintk(KERN_WARNING \"SELinux: Invalid class %hu\\n\", tclass);\n\t\treturn;\n\t}",
"\ttclass_datum = policydb.class_val_to_struct[tclass - 1];",
"\t/*\n\t * If a specific type enforcement rule was defined for\n\t * this permission check, then use it.\n\t */\n\tavkey.target_class = tclass;\n\tavkey.specified = AVTAB_AV;\n\tsattr = flex_array_get(policydb.type_attr_map_array, scontext->type - 1);\n\tBUG_ON(!sattr);\n\ttattr = flex_array_get(policydb.type_attr_map_array, tcontext->type - 1);\n\tBUG_ON(!tattr);\n\tebitmap_for_each_positive_bit(sattr, snode, i) {\n\t\tebitmap_for_each_positive_bit(tattr, tnode, j) {\n\t\t\tavkey.source_type = i + 1;\n\t\t\tavkey.target_type = j + 1;\n\t\t\tfor (node = avtab_search_node(&policydb.te_avtab, &avkey);\n\t\t\t node;\n\t\t\t node = avtab_search_node_next(node, avkey.specified)) {\n\t\t\t\tif (node->key.specified == AVTAB_ALLOWED)\n\t\t\t\t\tavd->allowed |= node->datum.data;\n\t\t\t\telse if (node->key.specified == AVTAB_AUDITALLOW)\n\t\t\t\t\tavd->auditallow |= node->datum.data;\n\t\t\t\telse if (node->key.specified == AVTAB_AUDITDENY)\n\t\t\t\t\tavd->auditdeny &= node->datum.data;\n\t\t\t}",
"\t\t\t/* Check conditional av table for additional permissions */\n\t\t\tcond_compute_av(&policydb.te_cond_avtab, &avkey, avd);",
"\t\t}\n\t}",
"\t/*\n\t * Remove any permissions prohibited by a constraint (this includes\n\t * the MLS policy).\n\t */\n\tconstraint = tclass_datum->constraints;\n\twhile (constraint) {\n\t\tif ((constraint->permissions & (avd->allowed)) &&\n\t\t !constraint_expr_eval(scontext, tcontext, NULL,\n\t\t\t\t\t constraint->expr)) {\n\t\t\tavd->allowed &= ~(constraint->permissions);\n\t\t}\n\t\tconstraint = constraint->next;\n\t}",
"\t/*\n\t * If checking process transition permission and the\n\t * role is changing, then check the (current_role, new_role)\n\t * pair.\n\t */\n\tif (tclass == policydb.process_class &&\n\t (avd->allowed & policydb.process_trans_perms) &&\n\t scontext->role != tcontext->role) {\n\t\tfor (ra = policydb.role_allow; ra; ra = ra->next) {\n\t\t\tif (scontext->role == ra->role &&\n\t\t\t tcontext->role == ra->new_role)\n\t\t\t\tbreak;\n\t\t}\n\t\tif (!ra)\n\t\t\tavd->allowed &= ~policydb.process_trans_perms;\n\t}",
"\t/*\n\t * If the given source and target types have boundary\n\t * constraint, lazy checks have to mask any violated\n\t * permission and notice it to userspace via audit.\n\t */\n\ttype_attribute_bounds_av(scontext, tcontext,\n\t\t\t\t tclass, avd);\n}",
"static int security_validtrans_handle_fail(struct context *ocontext,\n\t\t\t\t\t struct context *ncontext,\n\t\t\t\t\t struct context *tcontext,\n\t\t\t\t\t u16 tclass)\n{\n\tchar *o = NULL, *n = NULL, *t = NULL;\n\tu32 olen, nlen, tlen;",
"\tif (context_struct_to_string(ocontext, &o, &olen))\n\t\tgoto out;\n\tif (context_struct_to_string(ncontext, &n, &nlen))\n\t\tgoto out;\n\tif (context_struct_to_string(tcontext, &t, &tlen))\n\t\tgoto out;\n\taudit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t \"security_validate_transition: denied for\"\n\t\t \" oldcontext=%s newcontext=%s taskcontext=%s tclass=%s\",\n\t\t o, n, t, sym_name(&policydb, SYM_CLASSES, tclass-1));\nout:\n\tkfree(o);\n\tkfree(n);\n\tkfree(t);",
"\tif (!selinux_enforcing)\n\t\treturn 0;\n\treturn -EPERM;\n}",
"int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,\n\t\t\t\t u16 orig_tclass)\n{\n\tstruct context *ocontext;\n\tstruct context *ncontext;\n\tstruct context *tcontext;\n\tstruct class_datum *tclass_datum;\n\tstruct constraint_node *constraint;\n\tu16 tclass;\n\tint rc = 0;",
"\tif (!ss_initialized)\n\t\treturn 0;",
"\tread_lock(&policy_rwlock);",
"\ttclass = unmap_class(orig_tclass);",
"\tif (!tclass || tclass > policydb.p_classes.nprim) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized class %d\\n\",\n\t\t\t__func__, tclass);\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}\n\ttclass_datum = policydb.class_val_to_struct[tclass - 1];",
"\tocontext = sidtab_search(&sidtab, oldsid);\n\tif (!ocontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, oldsid);\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}",
"\tncontext = sidtab_search(&sidtab, newsid);\n\tif (!ncontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, newsid);\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}",
"\ttcontext = sidtab_search(&sidtab, tasksid);\n\tif (!tcontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, tasksid);\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}",
"\tconstraint = tclass_datum->validatetrans;\n\twhile (constraint) {\n\t\tif (!constraint_expr_eval(ocontext, ncontext, tcontext,\n\t\t\t\t\t constraint->expr)) {\n\t\t\trc = security_validtrans_handle_fail(ocontext, ncontext,\n\t\t\t\t\t\t\t tcontext, tclass);\n\t\t\tgoto out;\n\t\t}\n\t\tconstraint = constraint->next;\n\t}",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"/*\n * security_bounded_transition - check whether the given\n * transition is directed to bounded, or not.\n * It returns 0, if @newsid is bounded by @oldsid.\n * Otherwise, it returns error code.\n *\n * @oldsid : current security identifier\n * @newsid : destinated security identifier\n */\nint security_bounded_transition(u32 old_sid, u32 new_sid)\n{\n\tstruct context *old_context, *new_context;\n\tstruct type_datum *type;\n\tint index;\n\tint rc;",
"\tread_lock(&policy_rwlock);",
"\trc = -EINVAL;\n\told_context = sidtab_search(&sidtab, old_sid);\n\tif (!old_context) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %u\\n\",\n\t\t __func__, old_sid);\n\t\tgoto out;\n\t}",
"\trc = -EINVAL;\n\tnew_context = sidtab_search(&sidtab, new_sid);\n\tif (!new_context) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %u\\n\",\n\t\t __func__, new_sid);\n\t\tgoto out;\n\t}",
"\trc = 0;\n\t/* type/domain unchanged */\n\tif (old_context->type == new_context->type)\n\t\tgoto out;",
"\tindex = new_context->type;\n\twhile (true) {\n\t\ttype = flex_array_get_ptr(policydb.type_val_to_struct_array,\n\t\t\t\t\t index - 1);\n\t\tBUG_ON(!type);",
"\t\t/* not bounded anymore */\n\t\trc = -EPERM;\n\t\tif (!type->bounds)\n\t\t\tbreak;",
"\t\t/* @newsid is bounded by @oldsid */\n\t\trc = 0;\n\t\tif (type->bounds == old_context->type)\n\t\t\tbreak;",
"\t\tindex = type->bounds;\n\t}",
"\tif (rc) {\n\t\tchar *old_name = NULL;\n\t\tchar *new_name = NULL;\n\t\tu32 length;",
"\t\tif (!context_struct_to_string(old_context,\n\t\t\t\t\t &old_name, &length) &&\n\t\t !context_struct_to_string(new_context,\n\t\t\t\t\t &new_name, &length)) {\n\t\t\taudit_log(current->audit_context,\n\t\t\t\t GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t\t\t \"op=security_bounded_transition \"\n\t\t\t\t \"result=denied \"\n\t\t\t\t \"oldcontext=%s newcontext=%s\",\n\t\t\t\t old_name, new_name);\n\t\t}\n\t\tkfree(new_name);\n\t\tkfree(old_name);\n\t}\nout:\n\tread_unlock(&policy_rwlock);",
"\treturn rc;\n}",
"static void avd_init(struct av_decision *avd)\n{\n\tavd->allowed = 0;\n\tavd->auditallow = 0;\n\tavd->auditdeny = 0xffffffff;\n\tavd->seqno = latest_granting;\n\tavd->flags = 0;\n}",
"\n/**\n * security_compute_av - Compute access vector decisions.\n * @ssid: source security identifier\n * @tsid: target security identifier\n * @tclass: target security class\n * @avd: access vector decisions\n *\n * Compute a set of access vector decisions based on the\n * SID pair (@ssid, @tsid) for the permissions in @tclass.\n */\nvoid security_compute_av(u32 ssid,\n\t\t\t u32 tsid,\n\t\t\t u16 orig_tclass,\n\t\t\t struct av_decision *avd)\n{\n\tu16 tclass;\n\tstruct context *scontext = NULL, *tcontext = NULL;",
"\tread_lock(&policy_rwlock);\n\tavd_init(avd);\n\tif (!ss_initialized)\n\t\tgoto allow;",
"\tscontext = sidtab_search(&sidtab, ssid);\n\tif (!scontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, ssid);\n\t\tgoto out;\n\t}",
"\t/* permissive domain? */\n\tif (ebitmap_get_bit(&policydb.permissive_map, scontext->type))\n\t\tavd->flags |= AVD_FLAGS_PERMISSIVE;",
"\ttcontext = sidtab_search(&sidtab, tsid);\n\tif (!tcontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, tsid);\n\t\tgoto out;\n\t}",
"\ttclass = unmap_class(orig_tclass);\n\tif (unlikely(orig_tclass && !tclass)) {\n\t\tif (policydb.allow_unknown)\n\t\t\tgoto allow;\n\t\tgoto out;\n\t}\n\tcontext_struct_compute_av(scontext, tcontext, tclass, avd);\n\tmap_decision(orig_tclass, avd, policydb.allow_unknown);\nout:\n\tread_unlock(&policy_rwlock);\n\treturn;\nallow:\n\tavd->allowed = 0xffffffff;\n\tgoto out;\n}",
"void security_compute_av_user(u32 ssid,\n\t\t\t u32 tsid,\n\t\t\t u16 tclass,\n\t\t\t struct av_decision *avd)\n{\n\tstruct context *scontext = NULL, *tcontext = NULL;",
"\tread_lock(&policy_rwlock);\n\tavd_init(avd);\n\tif (!ss_initialized)\n\t\tgoto allow;",
"\tscontext = sidtab_search(&sidtab, ssid);\n\tif (!scontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, ssid);\n\t\tgoto out;\n\t}",
"\t/* permissive domain? */\n\tif (ebitmap_get_bit(&policydb.permissive_map, scontext->type))\n\t\tavd->flags |= AVD_FLAGS_PERMISSIVE;",
"\ttcontext = sidtab_search(&sidtab, tsid);\n\tif (!tcontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, tsid);\n\t\tgoto out;\n\t}",
"\tif (unlikely(!tclass)) {\n\t\tif (policydb.allow_unknown)\n\t\t\tgoto allow;\n\t\tgoto out;\n\t}",
"\tcontext_struct_compute_av(scontext, tcontext, tclass, avd);\n out:\n\tread_unlock(&policy_rwlock);\n\treturn;\nallow:\n\tavd->allowed = 0xffffffff;\n\tgoto out;\n}",
"/*\n * Write the security context string representation of\n * the context structure `context' into a dynamically\n * allocated string of the correct size. Set `*scontext'\n * to point to this string and set `*scontext_len' to\n * the length of the string.\n */\nstatic int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)\n{\n\tchar *scontextp;",
"\tif (scontext)\n\t\t*scontext = NULL;\n\t*scontext_len = 0;",
"\tif (context->len) {\n\t\t*scontext_len = context->len;\n\t\tif (scontext) {\n\t\t\t*scontext = kstrdup(context->str, GFP_ATOMIC);\n\t\t\tif (!(*scontext))\n\t\t\t\treturn -ENOMEM;\n\t\t}\n\t\treturn 0;\n\t}",
"\t/* Compute the size of the context. */\n\t*scontext_len += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) + 1;\n\t*scontext_len += strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) + 1;\n\t*scontext_len += strlen(sym_name(&policydb, SYM_TYPES, context->type - 1)) + 1;\n\t*scontext_len += mls_compute_context_len(context);",
"\tif (!scontext)\n\t\treturn 0;",
"\t/* Allocate space for the context; caller must free this space. */\n\tscontextp = kmalloc(*scontext_len, GFP_ATOMIC);\n\tif (!scontextp)\n\t\treturn -ENOMEM;\n\t*scontext = scontextp;",
"\t/*\n\t * Copy the user name, role name and type name into the context.\n\t */\n\tsprintf(scontextp, \"%s:%s:%s\",\n\t\tsym_name(&policydb, SYM_USERS, context->user - 1),\n\t\tsym_name(&policydb, SYM_ROLES, context->role - 1),\n\t\tsym_name(&policydb, SYM_TYPES, context->type - 1));\n\tscontextp += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) +\n\t\t 1 + strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) +\n\t\t 1 + strlen(sym_name(&policydb, SYM_TYPES, context->type - 1));",
"\tmls_sid_to_context(context, &scontextp);",
"\t*scontextp = 0;",
"\treturn 0;\n}",
"#include \"initial_sid_to_string.h\"",
"const char *security_get_initial_sid_context(u32 sid)\n{\n\tif (unlikely(sid > SECINITSID_NUM))\n\t\treturn NULL;\n\treturn initial_sid_to_string[sid];\n}",
"static int security_sid_to_context_core(u32 sid, char **scontext,\n\t\t\t\t\tu32 *scontext_len, int force)\n{\n\tstruct context *context;\n\tint rc = 0;",
"\tif (scontext)\n\t\t*scontext = NULL;\n\t*scontext_len = 0;",
"\tif (!ss_initialized) {\n\t\tif (sid <= SECINITSID_NUM) {\n\t\t\tchar *scontextp;",
"\t\t\t*scontext_len = strlen(initial_sid_to_string[sid]) + 1;\n\t\t\tif (!scontext)\n\t\t\t\tgoto out;\n\t\t\tscontextp = kmalloc(*scontext_len, GFP_ATOMIC);\n\t\t\tif (!scontextp) {\n\t\t\t\trc = -ENOMEM;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tstrcpy(scontextp, initial_sid_to_string[sid]);\n\t\t\t*scontext = scontextp;\n\t\t\tgoto out;\n\t\t}\n\t\tprintk(KERN_ERR \"SELinux: %s: called before initial \"\n\t\t \"load_policy on unknown SID %d\\n\", __func__, sid);\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}\n\tread_lock(&policy_rwlock);\n\tif (force)\n\t\tcontext = sidtab_search_force(&sidtab, sid);\n\telse\n\t\tcontext = sidtab_search(&sidtab, sid);\n\tif (!context) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, sid);\n\t\trc = -EINVAL;\n\t\tgoto out_unlock;\n\t}\n\trc = context_struct_to_string(context, scontext, scontext_len);\nout_unlock:\n\tread_unlock(&policy_rwlock);\nout:\n\treturn rc;",
"}",
"/**\n * security_sid_to_context - Obtain a context for a given SID.\n * @sid: security identifier, SID\n * @scontext: security context\n * @scontext_len: length in bytes\n *\n * Write the string representation of the context associated with @sid\n * into a dynamically allocated string of the correct size. Set @scontext\n * to point to this string and set @scontext_len to the length of the string.\n */\nint security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)\n{\n\treturn security_sid_to_context_core(sid, scontext, scontext_len, 0);\n}",
"int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len)\n{\n\treturn security_sid_to_context_core(sid, scontext, scontext_len, 1);\n}",
"/*\n * Caveat: Mutates scontext.\n */\nstatic int string_to_context_struct(struct policydb *pol,\n\t\t\t\t struct sidtab *sidtabp,\n\t\t\t\t char *scontext,\n\t\t\t\t u32 scontext_len,\n\t\t\t\t struct context *ctx,\n\t\t\t\t u32 def_sid)\n{\n\tstruct role_datum *role;\n\tstruct type_datum *typdatum;\n\tstruct user_datum *usrdatum;\n\tchar *scontextp, *p, oldc;\n\tint rc = 0;",
"\tcontext_init(ctx);",
"\t/* Parse the security context. */",
"\trc = -EINVAL;\n\tscontextp = (char *) scontext;",
"\t/* Extract the user. */\n\tp = scontextp;\n\twhile (*p && *p != ':')\n\t\tp++;",
"\tif (*p == 0)\n\t\tgoto out;",
"\t*p++ = 0;",
"\tusrdatum = hashtab_search(pol->p_users.table, scontextp);\n\tif (!usrdatum)\n\t\tgoto out;",
"\tctx->user = usrdatum->value;",
"\t/* Extract role. */\n\tscontextp = p;\n\twhile (*p && *p != ':')\n\t\tp++;",
"\tif (*p == 0)\n\t\tgoto out;",
"\t*p++ = 0;",
"\trole = hashtab_search(pol->p_roles.table, scontextp);\n\tif (!role)\n\t\tgoto out;\n\tctx->role = role->value;",
"\t/* Extract type. */\n\tscontextp = p;\n\twhile (*p && *p != ':')\n\t\tp++;\n\toldc = *p;\n\t*p++ = 0;",
"\ttypdatum = hashtab_search(pol->p_types.table, scontextp);\n\tif (!typdatum || typdatum->attribute)\n\t\tgoto out;",
"\tctx->type = typdatum->value;",
"\trc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);\n\tif (rc)\n\t\tgoto out;",
"\trc = -EINVAL;\n\tif ((p - scontext) < scontext_len)\n\t\tgoto out;",
"\t/* Check the validity of the new context. */\n\tif (!policydb_context_isvalid(pol, ctx))\n\t\tgoto out;\n\trc = 0;\nout:\n\tif (rc)\n\t\tcontext_destroy(ctx);\n\treturn rc;\n}",
"static int security_context_to_sid_core(const char *scontext, u32 scontext_len,\n\t\t\t\t\tu32 *sid, u32 def_sid, gfp_t gfp_flags,\n\t\t\t\t\tint force)\n{\n\tchar *scontext2, *str = NULL;\n\tstruct context context;\n\tint rc = 0;\n",
"\t/* An empty security context is never valid. */\n\tif (!scontext_len)\n\t\treturn -EINVAL;\n",
"\tif (!ss_initialized) {\n\t\tint i;",
"\t\tfor (i = 1; i < SECINITSID_NUM; i++) {\n\t\t\tif (!strcmp(initial_sid_to_string[i], scontext)) {\n\t\t\t\t*sid = i;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\t*sid = SECINITSID_KERNEL;\n\t\treturn 0;\n\t}\n\t*sid = SECSID_NULL;",
"\t/* Copy the string so that we can modify the copy as we parse it. */\n\tscontext2 = kmalloc(scontext_len + 1, gfp_flags);\n\tif (!scontext2)\n\t\treturn -ENOMEM;\n\tmemcpy(scontext2, scontext, scontext_len);\n\tscontext2[scontext_len] = 0;",
"\tif (force) {\n\t\t/* Save another copy for storing in uninterpreted form */\n\t\trc = -ENOMEM;\n\t\tstr = kstrdup(scontext2, gfp_flags);\n\t\tif (!str)\n\t\t\tgoto out;\n\t}",
"\tread_lock(&policy_rwlock);\n\trc = string_to_context_struct(&policydb, &sidtab, scontext2,\n\t\t\t\t scontext_len, &context, def_sid);\n\tif (rc == -EINVAL && force) {\n\t\tcontext.str = str;\n\t\tcontext.len = scontext_len;\n\t\tstr = NULL;\n\t} else if (rc)\n\t\tgoto out_unlock;\n\trc = sidtab_context_to_sid(&sidtab, &context, sid);\n\tcontext_destroy(&context);\nout_unlock:\n\tread_unlock(&policy_rwlock);\nout:\n\tkfree(scontext2);\n\tkfree(str);\n\treturn rc;\n}",
"/**\n * security_context_to_sid - Obtain a SID for a given security context.\n * @scontext: security context\n * @scontext_len: length in bytes\n * @sid: security identifier, SID\n *\n * Obtains a SID associated with the security context that\n * has the string representation specified by @scontext.\n * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient\n * memory is available, or 0 on success.\n */\nint security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid)\n{\n\treturn security_context_to_sid_core(scontext, scontext_len,\n\t\t\t\t\t sid, SECSID_NULL, GFP_KERNEL, 0);\n}",
"/**\n * security_context_to_sid_default - Obtain a SID for a given security context,\n * falling back to specified default if needed.\n *\n * @scontext: security context\n * @scontext_len: length in bytes\n * @sid: security identifier, SID\n * @def_sid: default SID to assign on error\n *\n * Obtains a SID associated with the security context that\n * has the string representation specified by @scontext.\n * The default SID is passed to the MLS layer to be used to allow\n * kernel labeling of the MLS field if the MLS field is not present\n * (for upgrading to MLS without full relabel).\n * Implicitly forces adding of the context even if it cannot be mapped yet.\n * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient\n * memory is available, or 0 on success.\n */\nint security_context_to_sid_default(const char *scontext, u32 scontext_len,\n\t\t\t\t u32 *sid, u32 def_sid, gfp_t gfp_flags)\n{\n\treturn security_context_to_sid_core(scontext, scontext_len,\n\t\t\t\t\t sid, def_sid, gfp_flags, 1);\n}",
"int security_context_to_sid_force(const char *scontext, u32 scontext_len,\n\t\t\t\t u32 *sid)\n{\n\treturn security_context_to_sid_core(scontext, scontext_len,\n\t\t\t\t\t sid, SECSID_NULL, GFP_KERNEL, 1);\n}",
"static int compute_sid_handle_invalid_context(\n\tstruct context *scontext,\n\tstruct context *tcontext,\n\tu16 tclass,\n\tstruct context *newcontext)\n{\n\tchar *s = NULL, *t = NULL, *n = NULL;\n\tu32 slen, tlen, nlen;",
"\tif (context_struct_to_string(scontext, &s, &slen))\n\t\tgoto out;\n\tif (context_struct_to_string(tcontext, &t, &tlen))\n\t\tgoto out;\n\tif (context_struct_to_string(newcontext, &n, &nlen))\n\t\tgoto out;\n\taudit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t \"security_compute_sid: invalid context %s\"\n\t\t \" for scontext=%s\"\n\t\t \" tcontext=%s\"\n\t\t \" tclass=%s\",\n\t\t n, s, t, sym_name(&policydb, SYM_CLASSES, tclass-1));\nout:\n\tkfree(s);\n\tkfree(t);\n\tkfree(n);\n\tif (!selinux_enforcing)\n\t\treturn 0;\n\treturn -EACCES;\n}",
"static void filename_compute_type(struct policydb *p, struct context *newcontext,\n\t\t\t\t u32 stype, u32 ttype, u16 tclass,\n\t\t\t\t const char *objname)\n{\n\tstruct filename_trans ft;\n\tstruct filename_trans_datum *otype;",
"\t/*\n\t * Most filename trans rules are going to live in specific directories\n\t * like /dev or /var/run. This bitmap will quickly skip rule searches\n\t * if the ttype does not contain any rules.\n\t */\n\tif (!ebitmap_get_bit(&p->filename_trans_ttypes, ttype))\n\t\treturn;",
"\tft.stype = stype;\n\tft.ttype = ttype;\n\tft.tclass = tclass;\n\tft.name = objname;",
"\totype = hashtab_search(p->filename_trans, &ft);\n\tif (otype)\n\t\tnewcontext->type = otype->otype;\n}",
"static int security_compute_sid(u32 ssid,\n\t\t\t\tu32 tsid,\n\t\t\t\tu16 orig_tclass,\n\t\t\t\tu32 specified,\n\t\t\t\tconst char *objname,\n\t\t\t\tu32 *out_sid,\n\t\t\t\tbool kern)\n{\n\tstruct class_datum *cladatum = NULL;\n\tstruct context *scontext = NULL, *tcontext = NULL, newcontext;\n\tstruct role_trans *roletr = NULL;\n\tstruct avtab_key avkey;\n\tstruct avtab_datum *avdatum;\n\tstruct avtab_node *node;\n\tu16 tclass;\n\tint rc = 0;\n\tbool sock;",
"\tif (!ss_initialized) {\n\t\tswitch (orig_tclass) {\n\t\tcase SECCLASS_PROCESS: /* kernel value */\n\t\t\t*out_sid = ssid;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t*out_sid = tsid;\n\t\t\tbreak;\n\t\t}\n\t\tgoto out;\n\t}",
"\tcontext_init(&newcontext);",
"\tread_lock(&policy_rwlock);",
"\tif (kern) {\n\t\ttclass = unmap_class(orig_tclass);\n\t\tsock = security_is_socket_class(orig_tclass);\n\t} else {\n\t\ttclass = orig_tclass;\n\t\tsock = security_is_socket_class(map_class(tclass));\n\t}",
"\tscontext = sidtab_search(&sidtab, ssid);\n\tif (!scontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, ssid);\n\t\trc = -EINVAL;\n\t\tgoto out_unlock;\n\t}\n\ttcontext = sidtab_search(&sidtab, tsid);\n\tif (!tcontext) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, tsid);\n\t\trc = -EINVAL;\n\t\tgoto out_unlock;\n\t}",
"\tif (tclass && tclass <= policydb.p_classes.nprim)\n\t\tcladatum = policydb.class_val_to_struct[tclass - 1];",
"\t/* Set the user identity. */\n\tswitch (specified) {\n\tcase AVTAB_TRANSITION:\n\tcase AVTAB_CHANGE:\n\t\tif (cladatum && cladatum->default_user == DEFAULT_TARGET) {\n\t\t\tnewcontext.user = tcontext->user;\n\t\t} else {\n\t\t\t/* notice this gets both DEFAULT_SOURCE and unset */\n\t\t\t/* Use the process user identity. */\n\t\t\tnewcontext.user = scontext->user;\n\t\t}\n\t\tbreak;\n\tcase AVTAB_MEMBER:\n\t\t/* Use the related object owner. */\n\t\tnewcontext.user = tcontext->user;\n\t\tbreak;\n\t}",
"\t/* Set the role to default values. */\n\tif (cladatum && cladatum->default_role == DEFAULT_SOURCE) {\n\t\tnewcontext.role = scontext->role;\n\t} else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {\n\t\tnewcontext.role = tcontext->role;\n\t} else {\n\t\tif ((tclass == policydb.process_class) || (sock == true))\n\t\t\tnewcontext.role = scontext->role;\n\t\telse\n\t\t\tnewcontext.role = OBJECT_R_VAL;\n\t}",
"\t/* Set the type to default values. */\n\tif (cladatum && cladatum->default_type == DEFAULT_SOURCE) {\n\t\tnewcontext.type = scontext->type;\n\t} else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {\n\t\tnewcontext.type = tcontext->type;\n\t} else {\n\t\tif ((tclass == policydb.process_class) || (sock == true)) {\n\t\t\t/* Use the type of process. */\n\t\t\tnewcontext.type = scontext->type;\n\t\t} else {\n\t\t\t/* Use the type of the related object. */\n\t\t\tnewcontext.type = tcontext->type;\n\t\t}\n\t}",
"\t/* Look for a type transition/member/change rule. */\n\tavkey.source_type = scontext->type;\n\tavkey.target_type = tcontext->type;\n\tavkey.target_class = tclass;\n\tavkey.specified = specified;\n\tavdatum = avtab_search(&policydb.te_avtab, &avkey);",
"\t/* If no permanent rule, also check for enabled conditional rules */\n\tif (!avdatum) {\n\t\tnode = avtab_search_node(&policydb.te_cond_avtab, &avkey);\n\t\tfor (; node; node = avtab_search_node_next(node, specified)) {\n\t\t\tif (node->key.specified & AVTAB_ENABLED) {\n\t\t\t\tavdatum = &node->datum;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}",
"\tif (avdatum) {\n\t\t/* Use the type from the type transition/member/change rule. */\n\t\tnewcontext.type = avdatum->data;\n\t}",
"\t/* if we have a objname this is a file trans check so check those rules */\n\tif (objname)\n\t\tfilename_compute_type(&policydb, &newcontext, scontext->type,\n\t\t\t\t tcontext->type, tclass, objname);",
"\t/* Check for class-specific changes. */\n\tif (specified & AVTAB_TRANSITION) {\n\t\t/* Look for a role transition rule. */\n\t\tfor (roletr = policydb.role_tr; roletr; roletr = roletr->next) {\n\t\t\tif ((roletr->role == scontext->role) &&\n\t\t\t (roletr->type == tcontext->type) &&\n\t\t\t (roletr->tclass == tclass)) {\n\t\t\t\t/* Use the role transition rule. */\n\t\t\t\tnewcontext.role = roletr->new_role;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}",
"\t/* Set the MLS attributes.\n\t This is done last because it may allocate memory. */\n\trc = mls_compute_sid(scontext, tcontext, tclass, specified,\n\t\t\t &newcontext, sock);\n\tif (rc)\n\t\tgoto out_unlock;",
"\t/* Check the validity of the context. */\n\tif (!policydb_context_isvalid(&policydb, &newcontext)) {\n\t\trc = compute_sid_handle_invalid_context(scontext,\n\t\t\t\t\t\t\ttcontext,\n\t\t\t\t\t\t\ttclass,\n\t\t\t\t\t\t\t&newcontext);\n\t\tif (rc)\n\t\t\tgoto out_unlock;\n\t}\n\t/* Obtain the sid for the context. */\n\trc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);\nout_unlock:\n\tread_unlock(&policy_rwlock);\n\tcontext_destroy(&newcontext);\nout:\n\treturn rc;\n}",
"/**\n * security_transition_sid - Compute the SID for a new subject/object.\n * @ssid: source security identifier\n * @tsid: target security identifier\n * @tclass: target security class\n * @out_sid: security identifier for new subject/object\n *\n * Compute a SID to use for labeling a new subject or object in the\n * class @tclass based on a SID pair (@ssid, @tsid).\n * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM\n * if insufficient memory is available, or %0 if the new SID was\n * computed successfully.\n */\nint security_transition_sid(u32 ssid, u32 tsid, u16 tclass,\n\t\t\t const struct qstr *qstr, u32 *out_sid)\n{\n\treturn security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,\n\t\t\t\t qstr ? qstr->name : NULL, out_sid, true);\n}",
"int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,\n\t\t\t\t const char *objname, u32 *out_sid)\n{\n\treturn security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,\n\t\t\t\t objname, out_sid, false);\n}",
"/**\n * security_member_sid - Compute the SID for member selection.\n * @ssid: source security identifier\n * @tsid: target security identifier\n * @tclass: target security class\n * @out_sid: security identifier for selected member\n *\n * Compute a SID to use when selecting a member of a polyinstantiated\n * object of class @tclass based on a SID pair (@ssid, @tsid).\n * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM\n * if insufficient memory is available, or %0 if the SID was\n * computed successfully.\n */\nint security_member_sid(u32 ssid,\n\t\t\tu32 tsid,\n\t\t\tu16 tclass,\n\t\t\tu32 *out_sid)\n{\n\treturn security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, NULL,\n\t\t\t\t out_sid, false);\n}",
"/**\n * security_change_sid - Compute the SID for object relabeling.\n * @ssid: source security identifier\n * @tsid: target security identifier\n * @tclass: target security class\n * @out_sid: security identifier for selected member\n *\n * Compute a SID to use for relabeling an object of class @tclass\n * based on a SID pair (@ssid, @tsid).\n * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM\n * if insufficient memory is available, or %0 if the SID was\n * computed successfully.\n */\nint security_change_sid(u32 ssid,\n\t\t\tu32 tsid,\n\t\t\tu16 tclass,\n\t\t\tu32 *out_sid)\n{\n\treturn security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL,\n\t\t\t\t out_sid, false);\n}",
"/* Clone the SID into the new SID table. */\nstatic int clone_sid(u32 sid,\n\t\t struct context *context,\n\t\t void *arg)\n{\n\tstruct sidtab *s = arg;",
"\tif (sid > SECINITSID_NUM)\n\t\treturn sidtab_insert(s, sid, context);\n\telse\n\t\treturn 0;\n}",
"static inline int convert_context_handle_invalid_context(struct context *context)\n{\n\tchar *s;\n\tu32 len;",
"\tif (selinux_enforcing)\n\t\treturn -EINVAL;",
"\tif (!context_struct_to_string(context, &s, &len)) {\n\t\tprintk(KERN_WARNING \"SELinux: Context %s would be invalid if enforcing\\n\", s);\n\t\tkfree(s);\n\t}\n\treturn 0;\n}",
"struct convert_context_args {\n\tstruct policydb *oldp;\n\tstruct policydb *newp;\n};",
"/*\n * Convert the values in the security context\n * structure `c' from the values specified\n * in the policy `p->oldp' to the values specified\n * in the policy `p->newp'. Verify that the\n * context is valid under the new policy.\n */\nstatic int convert_context(u32 key,\n\t\t\t struct context *c,\n\t\t\t void *p)\n{\n\tstruct convert_context_args *args;\n\tstruct context oldc;\n\tstruct ocontext *oc;\n\tstruct mls_range *range;\n\tstruct role_datum *role;\n\tstruct type_datum *typdatum;\n\tstruct user_datum *usrdatum;\n\tchar *s;\n\tu32 len;\n\tint rc = 0;",
"\tif (key <= SECINITSID_NUM)\n\t\tgoto out;",
"\targs = p;",
"\tif (c->str) {\n\t\tstruct context ctx;",
"\t\trc = -ENOMEM;\n\t\ts = kstrdup(c->str, GFP_KERNEL);\n\t\tif (!s)\n\t\t\tgoto out;",
"\t\trc = string_to_context_struct(args->newp, NULL, s,\n\t\t\t\t\t c->len, &ctx, SECSID_NULL);\n\t\tkfree(s);\n\t\tif (!rc) {\n\t\t\tprintk(KERN_INFO \"SELinux: Context %s became valid (mapped).\\n\",\n\t\t\t c->str);\n\t\t\t/* Replace string with mapped representation. */\n\t\t\tkfree(c->str);\n\t\t\tmemcpy(c, &ctx, sizeof(*c));\n\t\t\tgoto out;\n\t\t} else if (rc == -EINVAL) {\n\t\t\t/* Retain string representation for later mapping. */\n\t\t\trc = 0;\n\t\t\tgoto out;\n\t\t} else {\n\t\t\t/* Other error condition, e.g. ENOMEM. */\n\t\t\tprintk(KERN_ERR \"SELinux: Unable to map context %s, rc = %d.\\n\",\n\t\t\t c->str, -rc);\n\t\t\tgoto out;\n\t\t}\n\t}",
"\trc = context_cpy(&oldc, c);\n\tif (rc)\n\t\tgoto out;",
"\t/* Convert the user. */\n\trc = -EINVAL;\n\tusrdatum = hashtab_search(args->newp->p_users.table,\n\t\t\t\t sym_name(args->oldp, SYM_USERS, c->user - 1));\n\tif (!usrdatum)\n\t\tgoto bad;\n\tc->user = usrdatum->value;",
"\t/* Convert the role. */\n\trc = -EINVAL;\n\trole = hashtab_search(args->newp->p_roles.table,\n\t\t\t sym_name(args->oldp, SYM_ROLES, c->role - 1));\n\tif (!role)\n\t\tgoto bad;\n\tc->role = role->value;",
"\t/* Convert the type. */\n\trc = -EINVAL;\n\ttypdatum = hashtab_search(args->newp->p_types.table,\n\t\t\t\t sym_name(args->oldp, SYM_TYPES, c->type - 1));\n\tif (!typdatum)\n\t\tgoto bad;\n\tc->type = typdatum->value;",
"\t/* Convert the MLS fields if dealing with MLS policies */\n\tif (args->oldp->mls_enabled && args->newp->mls_enabled) {\n\t\trc = mls_convert_context(args->oldp, args->newp, c);\n\t\tif (rc)\n\t\t\tgoto bad;\n\t} else if (args->oldp->mls_enabled && !args->newp->mls_enabled) {\n\t\t/*\n\t\t * Switching between MLS and non-MLS policy:\n\t\t * free any storage used by the MLS fields in the\n\t\t * context for all existing entries in the sidtab.\n\t\t */\n\t\tmls_context_destroy(c);\n\t} else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {\n\t\t/*\n\t\t * Switching between non-MLS and MLS policy:\n\t\t * ensure that the MLS fields of the context for all\n\t\t * existing entries in the sidtab are filled in with a\n\t\t * suitable default value, likely taken from one of the\n\t\t * initial SIDs.\n\t\t */\n\t\toc = args->newp->ocontexts[OCON_ISID];\n\t\twhile (oc && oc->sid[0] != SECINITSID_UNLABELED)\n\t\t\toc = oc->next;\n\t\trc = -EINVAL;\n\t\tif (!oc) {\n\t\t\tprintk(KERN_ERR \"SELinux: unable to look up\"\n\t\t\t\t\" the initial SIDs list\\n\");\n\t\t\tgoto bad;\n\t\t}\n\t\trange = &oc->context[0].range;\n\t\trc = mls_range_set(c, range);\n\t\tif (rc)\n\t\t\tgoto bad;\n\t}",
"\t/* Check the validity of the new context. */\n\tif (!policydb_context_isvalid(args->newp, c)) {\n\t\trc = convert_context_handle_invalid_context(&oldc);\n\t\tif (rc)\n\t\t\tgoto bad;\n\t}",
"\tcontext_destroy(&oldc);",
"\trc = 0;\nout:\n\treturn rc;\nbad:\n\t/* Map old representation to string and save it. */\n\trc = context_struct_to_string(&oldc, &s, &len);\n\tif (rc)\n\t\treturn rc;\n\tcontext_destroy(&oldc);\n\tcontext_destroy(c);\n\tc->str = s;\n\tc->len = len;\n\tprintk(KERN_INFO \"SELinux: Context %s became invalid (unmapped).\\n\",\n\t c->str);\n\trc = 0;\n\tgoto out;\n}",
"static void security_load_policycaps(void)\n{\n\tselinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps,\n\t\t\t\t\t\t POLICYDB_CAPABILITY_NETPEER);\n\tselinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps,\n\t\t\t\t\t\t POLICYDB_CAPABILITY_OPENPERM);\n\tselinux_policycap_alwaysnetwork = ebitmap_get_bit(&policydb.policycaps,\n\t\t\t\t\t\t POLICYDB_CAPABILITY_ALWAYSNETWORK);\n}",
"static int security_preserve_bools(struct policydb *p);",
"/**\n * security_load_policy - Load a security policy configuration.\n * @data: binary policy data\n * @len: length of data in bytes\n *\n * Load a new set of security policy configuration data,\n * validate it and convert the SID table as necessary.\n * This function will flush the access vector cache after\n * loading the new policy.\n */\nint security_load_policy(void *data, size_t len)\n{\n\tstruct policydb *oldpolicydb, *newpolicydb;\n\tstruct sidtab oldsidtab, newsidtab;\n\tstruct selinux_mapping *oldmap, *map = NULL;\n\tstruct convert_context_args args;\n\tu32 seqno;\n\tu16 map_size;\n\tint rc = 0;\n\tstruct policy_file file = { data, len }, *fp = &file;",
"\toldpolicydb = kzalloc(2 * sizeof(*oldpolicydb), GFP_KERNEL);\n\tif (!oldpolicydb) {\n\t\trc = -ENOMEM;\n\t\tgoto out;\n\t}\n\tnewpolicydb = oldpolicydb + 1;",
"\tif (!ss_initialized) {\n\t\tavtab_cache_init();\n\t\trc = policydb_read(&policydb, fp);\n\t\tif (rc) {\n\t\t\tavtab_cache_destroy();\n\t\t\tgoto out;\n\t\t}",
"\t\tpolicydb.len = len;\n\t\trc = selinux_set_mapping(&policydb, secclass_map,\n\t\t\t\t\t ¤t_mapping,\n\t\t\t\t\t ¤t_mapping_size);\n\t\tif (rc) {\n\t\t\tpolicydb_destroy(&policydb);\n\t\t\tavtab_cache_destroy();\n\t\t\tgoto out;\n\t\t}",
"\t\trc = policydb_load_isids(&policydb, &sidtab);\n\t\tif (rc) {\n\t\t\tpolicydb_destroy(&policydb);\n\t\t\tavtab_cache_destroy();\n\t\t\tgoto out;\n\t\t}",
"\t\tsecurity_load_policycaps();\n\t\tss_initialized = 1;\n\t\tseqno = ++latest_granting;\n\t\tselinux_complete_init();\n\t\tavc_ss_reset(seqno);\n\t\tselnl_notify_policyload(seqno);\n\t\tselinux_status_update_policyload(seqno);\n\t\tselinux_netlbl_cache_invalidate();\n\t\tselinux_xfrm_notify_policyload();\n\t\tgoto out;\n\t}",
"#if 0\n\tsidtab_hash_eval(&sidtab, \"sids\");\n#endif",
"\trc = policydb_read(newpolicydb, fp);\n\tif (rc)\n\t\tgoto out;",
"\tnewpolicydb->len = len;\n\t/* If switching between different policy types, log MLS status */\n\tif (policydb.mls_enabled && !newpolicydb->mls_enabled)\n\t\tprintk(KERN_INFO \"SELinux: Disabling MLS support...\\n\");\n\telse if (!policydb.mls_enabled && newpolicydb->mls_enabled)\n\t\tprintk(KERN_INFO \"SELinux: Enabling MLS support...\\n\");",
"\trc = policydb_load_isids(newpolicydb, &newsidtab);\n\tif (rc) {\n\t\tprintk(KERN_ERR \"SELinux: unable to load the initial SIDs\\n\");\n\t\tpolicydb_destroy(newpolicydb);\n\t\tgoto out;\n\t}",
"\trc = selinux_set_mapping(newpolicydb, secclass_map, &map, &map_size);\n\tif (rc)\n\t\tgoto err;",
"\trc = security_preserve_bools(newpolicydb);\n\tif (rc) {\n\t\tprintk(KERN_ERR \"SELinux: unable to preserve booleans\\n\");\n\t\tgoto err;\n\t}",
"\t/* Clone the SID table. */\n\tsidtab_shutdown(&sidtab);",
"\trc = sidtab_map(&sidtab, clone_sid, &newsidtab);\n\tif (rc)\n\t\tgoto err;",
"\t/*\n\t * Convert the internal representations of contexts\n\t * in the new SID table.\n\t */\n\targs.oldp = &policydb;\n\targs.newp = newpolicydb;\n\trc = sidtab_map(&newsidtab, convert_context, &args);\n\tif (rc) {\n\t\tprintk(KERN_ERR \"SELinux: unable to convert the internal\"\n\t\t\t\" representation of contexts in the new SID\"\n\t\t\t\" table\\n\");\n\t\tgoto err;\n\t}",
"\t/* Save the old policydb and SID table to free later. */\n\tmemcpy(oldpolicydb, &policydb, sizeof(policydb));\n\tsidtab_set(&oldsidtab, &sidtab);",
"\t/* Install the new policydb and SID table. */\n\twrite_lock_irq(&policy_rwlock);\n\tmemcpy(&policydb, newpolicydb, sizeof(policydb));\n\tsidtab_set(&sidtab, &newsidtab);\n\tsecurity_load_policycaps();\n\toldmap = current_mapping;\n\tcurrent_mapping = map;\n\tcurrent_mapping_size = map_size;\n\tseqno = ++latest_granting;\n\twrite_unlock_irq(&policy_rwlock);",
"\t/* Free the old policydb and SID table. */\n\tpolicydb_destroy(oldpolicydb);\n\tsidtab_destroy(&oldsidtab);\n\tkfree(oldmap);",
"\tavc_ss_reset(seqno);\n\tselnl_notify_policyload(seqno);\n\tselinux_status_update_policyload(seqno);\n\tselinux_netlbl_cache_invalidate();\n\tselinux_xfrm_notify_policyload();",
"\trc = 0;\n\tgoto out;",
"err:\n\tkfree(map);\n\tsidtab_destroy(&newsidtab);\n\tpolicydb_destroy(newpolicydb);",
"out:\n\tkfree(oldpolicydb);\n\treturn rc;\n}",
"size_t security_policydb_len(void)\n{\n\tsize_t len;",
"\tread_lock(&policy_rwlock);\n\tlen = policydb.len;\n\tread_unlock(&policy_rwlock);",
"\treturn len;\n}",
"/**\n * security_port_sid - Obtain the SID for a port.\n * @protocol: protocol number\n * @port: port number\n * @out_sid: security identifier\n */\nint security_port_sid(u8 protocol, u16 port, u32 *out_sid)\n{\n\tstruct ocontext *c;\n\tint rc = 0;",
"\tread_lock(&policy_rwlock);",
"\tc = policydb.ocontexts[OCON_PORT];\n\twhile (c) {\n\t\tif (c->u.port.protocol == protocol &&\n\t\t c->u.port.low_port <= port &&\n\t\t c->u.port.high_port >= port)\n\t\t\tbreak;\n\t\tc = c->next;\n\t}",
"\tif (c) {\n\t\tif (!c->sid[0]) {\n\t\t\trc = sidtab_context_to_sid(&sidtab,\n\t\t\t\t\t\t &c->context[0],\n\t\t\t\t\t\t &c->sid[0]);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t}\n\t\t*out_sid = c->sid[0];\n\t} else {\n\t\t*out_sid = SECINITSID_PORT;\n\t}",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"/**\n * security_netif_sid - Obtain the SID for a network interface.\n * @name: interface name\n * @if_sid: interface SID\n */\nint security_netif_sid(char *name, u32 *if_sid)\n{\n\tint rc = 0;\n\tstruct ocontext *c;",
"\tread_lock(&policy_rwlock);",
"\tc = policydb.ocontexts[OCON_NETIF];\n\twhile (c) {\n\t\tif (strcmp(name, c->u.name) == 0)\n\t\t\tbreak;\n\t\tc = c->next;\n\t}",
"\tif (c) {\n\t\tif (!c->sid[0] || !c->sid[1]) {\n\t\t\trc = sidtab_context_to_sid(&sidtab,\n\t\t\t\t\t\t &c->context[0],\n\t\t\t\t\t\t &c->sid[0]);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t\trc = sidtab_context_to_sid(&sidtab,\n\t\t\t\t\t\t &c->context[1],\n\t\t\t\t\t\t &c->sid[1]);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t}\n\t\t*if_sid = c->sid[0];\n\t} else\n\t\t*if_sid = SECINITSID_NETIF;",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)\n{\n\tint i, fail = 0;",
"\tfor (i = 0; i < 4; i++)\n\t\tif (addr[i] != (input[i] & mask[i])) {\n\t\t\tfail = 1;\n\t\t\tbreak;\n\t\t}",
"\treturn !fail;\n}",
"/**\n * security_node_sid - Obtain the SID for a node (host).\n * @domain: communication domain aka address family\n * @addrp: address\n * @addrlen: address length in bytes\n * @out_sid: security identifier\n */\nint security_node_sid(u16 domain,\n\t\t void *addrp,\n\t\t u32 addrlen,\n\t\t u32 *out_sid)\n{\n\tint rc;\n\tstruct ocontext *c;",
"\tread_lock(&policy_rwlock);",
"\tswitch (domain) {\n\tcase AF_INET: {\n\t\tu32 addr;",
"\t\trc = -EINVAL;\n\t\tif (addrlen != sizeof(u32))\n\t\t\tgoto out;",
"\t\taddr = *((u32 *)addrp);",
"\t\tc = policydb.ocontexts[OCON_NODE];\n\t\twhile (c) {\n\t\t\tif (c->u.node.addr == (addr & c->u.node.mask))\n\t\t\t\tbreak;\n\t\t\tc = c->next;\n\t\t}\n\t\tbreak;\n\t}",
"\tcase AF_INET6:\n\t\trc = -EINVAL;\n\t\tif (addrlen != sizeof(u64) * 2)\n\t\t\tgoto out;\n\t\tc = policydb.ocontexts[OCON_NODE6];\n\t\twhile (c) {\n\t\t\tif (match_ipv6_addrmask(addrp, c->u.node6.addr,\n\t\t\t\t\t\tc->u.node6.mask))\n\t\t\t\tbreak;\n\t\t\tc = c->next;\n\t\t}\n\t\tbreak;",
"\tdefault:\n\t\trc = 0;\n\t\t*out_sid = SECINITSID_NODE;\n\t\tgoto out;\n\t}",
"\tif (c) {\n\t\tif (!c->sid[0]) {\n\t\t\trc = sidtab_context_to_sid(&sidtab,\n\t\t\t\t\t\t &c->context[0],\n\t\t\t\t\t\t &c->sid[0]);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t}\n\t\t*out_sid = c->sid[0];\n\t} else {\n\t\t*out_sid = SECINITSID_NODE;\n\t}",
"\trc = 0;\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"#define SIDS_NEL 25",
"/**\n * security_get_user_sids - Obtain reachable SIDs for a user.\n * @fromsid: starting SID\n * @username: username\n * @sids: array of reachable SIDs for user\n * @nel: number of elements in @sids\n *\n * Generate the set of SIDs for legal security contexts\n * for a given user that can be reached by @fromsid.\n * Set *@sids to point to a dynamically allocated\n * array containing the set of SIDs. Set *@nel to the\n * number of elements in the array.\n */",
"int security_get_user_sids(u32 fromsid,\n\t\t\t char *username,\n\t\t\t u32 **sids,\n\t\t\t u32 *nel)\n{\n\tstruct context *fromcon, usercon;\n\tu32 *mysids = NULL, *mysids2, sid;\n\tu32 mynel = 0, maxnel = SIDS_NEL;\n\tstruct user_datum *user;\n\tstruct role_datum *role;\n\tstruct ebitmap_node *rnode, *tnode;\n\tint rc = 0, i, j;",
"\t*sids = NULL;\n\t*nel = 0;",
"\tif (!ss_initialized)\n\t\tgoto out;",
"\tread_lock(&policy_rwlock);",
"\tcontext_init(&usercon);",
"\trc = -EINVAL;\n\tfromcon = sidtab_search(&sidtab, fromsid);\n\tif (!fromcon)\n\t\tgoto out_unlock;",
"\trc = -EINVAL;\n\tuser = hashtab_search(policydb.p_users.table, username);\n\tif (!user)\n\t\tgoto out_unlock;",
"\tusercon.user = user->value;",
"\trc = -ENOMEM;\n\tmysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);\n\tif (!mysids)\n\t\tgoto out_unlock;",
"\tebitmap_for_each_positive_bit(&user->roles, rnode, i) {\n\t\trole = policydb.role_val_to_struct[i];\n\t\tusercon.role = i + 1;\n\t\tebitmap_for_each_positive_bit(&role->types, tnode, j) {\n\t\t\tusercon.type = j + 1;",
"\t\t\tif (mls_setup_user_range(fromcon, user, &usercon))\n\t\t\t\tcontinue;",
"\t\t\trc = sidtab_context_to_sid(&sidtab, &usercon, &sid);\n\t\t\tif (rc)\n\t\t\t\tgoto out_unlock;\n\t\t\tif (mynel < maxnel) {\n\t\t\t\tmysids[mynel++] = sid;\n\t\t\t} else {\n\t\t\t\trc = -ENOMEM;\n\t\t\t\tmaxnel += SIDS_NEL;\n\t\t\t\tmysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);\n\t\t\t\tif (!mysids2)\n\t\t\t\t\tgoto out_unlock;\n\t\t\t\tmemcpy(mysids2, mysids, mynel * sizeof(*mysids2));\n\t\t\t\tkfree(mysids);\n\t\t\t\tmysids = mysids2;\n\t\t\t\tmysids[mynel++] = sid;\n\t\t\t}\n\t\t}\n\t}\n\trc = 0;\nout_unlock:\n\tread_unlock(&policy_rwlock);\n\tif (rc || !mynel) {\n\t\tkfree(mysids);\n\t\tgoto out;\n\t}",
"\trc = -ENOMEM;\n\tmysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);\n\tif (!mysids2) {\n\t\tkfree(mysids);\n\t\tgoto out;\n\t}\n\tfor (i = 0, j = 0; i < mynel; i++) {\n\t\tstruct av_decision dummy_avd;\n\t\trc = avc_has_perm_noaudit(fromsid, mysids[i],\n\t\t\t\t\t SECCLASS_PROCESS, /* kernel value */\n\t\t\t\t\t PROCESS__TRANSITION, AVC_STRICT,\n\t\t\t\t\t &dummy_avd);\n\t\tif (!rc)\n\t\t\tmysids2[j++] = mysids[i];\n\t\tcond_resched();\n\t}\n\trc = 0;\n\tkfree(mysids);\n\t*sids = mysids2;\n\t*nel = j;\nout:\n\treturn rc;\n}",
"/**\n * security_genfs_sid - Obtain a SID for a file in a filesystem\n * @fstype: filesystem type\n * @path: path from root of mount\n * @sclass: file security class\n * @sid: SID for path\n *\n * Obtain a SID to use for a file in a filesystem that\n * cannot support xattr or use a fixed labeling behavior like\n * transition SIDs or task SIDs.\n */\nint security_genfs_sid(const char *fstype,\n\t\t char *path,\n\t\t u16 orig_sclass,\n\t\t u32 *sid)\n{\n\tint len;\n\tu16 sclass;\n\tstruct genfs *genfs;\n\tstruct ocontext *c;\n\tint rc, cmp = 0;",
"\twhile (path[0] == '/' && path[1] == '/')\n\t\tpath++;",
"\tread_lock(&policy_rwlock);",
"\tsclass = unmap_class(orig_sclass);\n\t*sid = SECINITSID_UNLABELED;",
"\tfor (genfs = policydb.genfs; genfs; genfs = genfs->next) {\n\t\tcmp = strcmp(fstype, genfs->fstype);\n\t\tif (cmp <= 0)\n\t\t\tbreak;\n\t}",
"\trc = -ENOENT;\n\tif (!genfs || cmp)\n\t\tgoto out;",
"\tfor (c = genfs->head; c; c = c->next) {\n\t\tlen = strlen(c->u.name);\n\t\tif ((!c->v.sclass || sclass == c->v.sclass) &&\n\t\t (strncmp(c->u.name, path, len) == 0))\n\t\t\tbreak;\n\t}",
"\trc = -ENOENT;\n\tif (!c)\n\t\tgoto out;",
"\tif (!c->sid[0]) {\n\t\trc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]);\n\t\tif (rc)\n\t\t\tgoto out;\n\t}",
"\t*sid = c->sid[0];\n\trc = 0;\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"/**\n * security_fs_use - Determine how to handle labeling for a filesystem.\n * @sb: superblock in question\n */\nint security_fs_use(struct super_block *sb)\n{\n\tint rc = 0;\n\tstruct ocontext *c;\n\tstruct superblock_security_struct *sbsec = sb->s_security;\n\tconst char *fstype = sb->s_type->name;",
"\tread_lock(&policy_rwlock);",
"\tc = policydb.ocontexts[OCON_FSUSE];\n\twhile (c) {\n\t\tif (strcmp(fstype, c->u.name) == 0)\n\t\t\tbreak;\n\t\tc = c->next;\n\t}",
"\tif (c) {\n\t\tsbsec->behavior = c->v.behavior;\n\t\tif (!c->sid[0]) {\n\t\t\trc = sidtab_context_to_sid(&sidtab, &c->context[0],\n\t\t\t\t\t\t &c->sid[0]);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t}\n\t\tsbsec->sid = c->sid[0];\n\t} else {\n\t\trc = security_genfs_sid(fstype, \"/\", SECCLASS_DIR, &sbsec->sid);\n\t\tif (rc) {\n\t\t\tsbsec->behavior = SECURITY_FS_USE_NONE;\n\t\t\trc = 0;\n\t\t} else {\n\t\t\tsbsec->behavior = SECURITY_FS_USE_GENFS;\n\t\t}\n\t}",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"int security_get_bools(int *len, char ***names, int **values)\n{\n\tint i, rc;",
"\tread_lock(&policy_rwlock);\n\t*names = NULL;\n\t*values = NULL;",
"\trc = 0;\n\t*len = policydb.p_bools.nprim;\n\tif (!*len)\n\t\tgoto out;",
"\trc = -ENOMEM;\n\t*names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);\n\tif (!*names)\n\t\tgoto err;",
"\trc = -ENOMEM;\n\t*values = kcalloc(*len, sizeof(int), GFP_ATOMIC);\n\tif (!*values)\n\t\tgoto err;",
"\tfor (i = 0; i < *len; i++) {\n\t\tsize_t name_len;",
"\t\t(*values)[i] = policydb.bool_val_to_struct[i]->state;\n\t\tname_len = strlen(sym_name(&policydb, SYM_BOOLS, i)) + 1;",
"\t\trc = -ENOMEM;\n\t\t(*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);\n\t\tif (!(*names)[i])\n\t\t\tgoto err;",
"\t\tstrncpy((*names)[i], sym_name(&policydb, SYM_BOOLS, i), name_len);\n\t\t(*names)[i][name_len - 1] = 0;\n\t}\n\trc = 0;\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\nerr:\n\tif (*names) {\n\t\tfor (i = 0; i < *len; i++)\n\t\t\tkfree((*names)[i]);\n\t}\n\tkfree(*values);\n\tgoto out;\n}",
"\nint security_set_bools(int len, int *values)\n{\n\tint i, rc;\n\tint lenp, seqno = 0;\n\tstruct cond_node *cur;",
"\twrite_lock_irq(&policy_rwlock);",
"\trc = -EFAULT;\n\tlenp = policydb.p_bools.nprim;\n\tif (len != lenp)\n\t\tgoto out;",
"\tfor (i = 0; i < len; i++) {\n\t\tif (!!values[i] != policydb.bool_val_to_struct[i]->state) {\n\t\t\taudit_log(current->audit_context, GFP_ATOMIC,\n\t\t\t\tAUDIT_MAC_CONFIG_CHANGE,\n\t\t\t\t\"bool=%s val=%d old_val=%d auid=%u ses=%u\",\n\t\t\t\tsym_name(&policydb, SYM_BOOLS, i),\n\t\t\t\t!!values[i],\n\t\t\t\tpolicydb.bool_val_to_struct[i]->state,\n\t\t\t\tfrom_kuid(&init_user_ns, audit_get_loginuid(current)),\n\t\t\t\taudit_get_sessionid(current));\n\t\t}\n\t\tif (values[i])\n\t\t\tpolicydb.bool_val_to_struct[i]->state = 1;\n\t\telse\n\t\t\tpolicydb.bool_val_to_struct[i]->state = 0;\n\t}",
"\tfor (cur = policydb.cond_list; cur; cur = cur->next) {\n\t\trc = evaluate_cond_node(&policydb, cur);\n\t\tif (rc)\n\t\t\tgoto out;\n\t}",
"\tseqno = ++latest_granting;\n\trc = 0;\nout:\n\twrite_unlock_irq(&policy_rwlock);\n\tif (!rc) {\n\t\tavc_ss_reset(seqno);\n\t\tselnl_notify_policyload(seqno);\n\t\tselinux_status_update_policyload(seqno);\n\t\tselinux_xfrm_notify_policyload();\n\t}\n\treturn rc;\n}",
"int security_get_bool_value(int bool)\n{\n\tint rc;\n\tint len;",
"\tread_lock(&policy_rwlock);",
"\trc = -EFAULT;\n\tlen = policydb.p_bools.nprim;\n\tif (bool >= len)\n\t\tgoto out;",
"\trc = policydb.bool_val_to_struct[bool]->state;\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"static int security_preserve_bools(struct policydb *p)\n{\n\tint rc, nbools = 0, *bvalues = NULL, i;\n\tchar **bnames = NULL;\n\tstruct cond_bool_datum *booldatum;\n\tstruct cond_node *cur;",
"\trc = security_get_bools(&nbools, &bnames, &bvalues);\n\tif (rc)\n\t\tgoto out;\n\tfor (i = 0; i < nbools; i++) {\n\t\tbooldatum = hashtab_search(p->p_bools.table, bnames[i]);\n\t\tif (booldatum)\n\t\t\tbooldatum->state = bvalues[i];\n\t}\n\tfor (cur = p->cond_list; cur; cur = cur->next) {\n\t\trc = evaluate_cond_node(p, cur);\n\t\tif (rc)\n\t\t\tgoto out;\n\t}",
"out:\n\tif (bnames) {\n\t\tfor (i = 0; i < nbools; i++)\n\t\t\tkfree(bnames[i]);\n\t}\n\tkfree(bnames);\n\tkfree(bvalues);\n\treturn rc;\n}",
"/*\n * security_sid_mls_copy() - computes a new sid based on the given\n * sid and the mls portion of mls_sid.\n */\nint security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)\n{\n\tstruct context *context1;\n\tstruct context *context2;\n\tstruct context newcon;\n\tchar *s;\n\tu32 len;\n\tint rc;",
"\trc = 0;\n\tif (!ss_initialized || !policydb.mls_enabled) {\n\t\t*new_sid = sid;\n\t\tgoto out;\n\t}",
"\tcontext_init(&newcon);",
"\tread_lock(&policy_rwlock);",
"\trc = -EINVAL;\n\tcontext1 = sidtab_search(&sidtab, sid);\n\tif (!context1) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, sid);\n\t\tgoto out_unlock;\n\t}",
"\trc = -EINVAL;\n\tcontext2 = sidtab_search(&sidtab, mls_sid);\n\tif (!context2) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t\t__func__, mls_sid);\n\t\tgoto out_unlock;\n\t}",
"\tnewcon.user = context1->user;\n\tnewcon.role = context1->role;\n\tnewcon.type = context1->type;\n\trc = mls_context_cpy(&newcon, context2);\n\tif (rc)\n\t\tgoto out_unlock;",
"\t/* Check the validity of the new context. */\n\tif (!policydb_context_isvalid(&policydb, &newcon)) {\n\t\trc = convert_context_handle_invalid_context(&newcon);\n\t\tif (rc) {\n\t\t\tif (!context_struct_to_string(&newcon, &s, &len)) {\n\t\t\t\taudit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t\t\t\t \"security_sid_mls_copy: invalid context %s\", s);\n\t\t\t\tkfree(s);\n\t\t\t}\n\t\t\tgoto out_unlock;\n\t\t}\n\t}",
"\trc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);\nout_unlock:\n\tread_unlock(&policy_rwlock);\n\tcontext_destroy(&newcon);\nout:\n\treturn rc;\n}",
"/**\n * security_net_peersid_resolve - Compare and resolve two network peer SIDs\n * @nlbl_sid: NetLabel SID\n * @nlbl_type: NetLabel labeling protocol type\n * @xfrm_sid: XFRM SID\n *\n * Description:\n * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be\n * resolved into a single SID it is returned via @peer_sid and the function\n * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function\n * returns a negative value. A table summarizing the behavior is below:\n *\n * | function return | @sid\n * ------------------------------+-----------------+-----------------\n * no peer labels | 0 | SECSID_NULL\n * single peer label | 0 | <peer_label>\n * multiple, consistent labels | 0 | <peer_label>\n * multiple, inconsistent labels | -<errno> | SECSID_NULL\n *\n */\nint security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,\n\t\t\t\t u32 xfrm_sid,\n\t\t\t\t u32 *peer_sid)\n{\n\tint rc;\n\tstruct context *nlbl_ctx;\n\tstruct context *xfrm_ctx;",
"\t*peer_sid = SECSID_NULL;",
"\t/* handle the common (which also happens to be the set of easy) cases\n\t * right away, these two if statements catch everything involving a\n\t * single or absent peer SID/label */\n\tif (xfrm_sid == SECSID_NULL) {\n\t\t*peer_sid = nlbl_sid;\n\t\treturn 0;\n\t}\n\t/* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a \"fallback\" label\n\t * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label\n\t * is present */\n\tif (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {\n\t\t*peer_sid = xfrm_sid;\n\t\treturn 0;\n\t}",
"\t/* we don't need to check ss_initialized here since the only way both\n\t * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the\n\t * security server was initialized and ss_initialized was true */\n\tif (!policydb.mls_enabled)\n\t\treturn 0;",
"\tread_lock(&policy_rwlock);",
"\trc = -EINVAL;\n\tnlbl_ctx = sidtab_search(&sidtab, nlbl_sid);\n\tif (!nlbl_ctx) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, nlbl_sid);\n\t\tgoto out;\n\t}\n\trc = -EINVAL;\n\txfrm_ctx = sidtab_search(&sidtab, xfrm_sid);\n\tif (!xfrm_ctx) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized SID %d\\n\",\n\t\t __func__, xfrm_sid);\n\t\tgoto out;\n\t}\n\trc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);\n\tif (rc)\n\t\tgoto out;",
"\t/* at present NetLabel SIDs/labels really only carry MLS\n\t * information so if the MLS portion of the NetLabel SID\n\t * matches the MLS portion of the labeled XFRM SID/label\n\t * then pass along the XFRM SID as it is the most\n\t * expressive */\n\t*peer_sid = xfrm_sid;\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"static int get_classes_callback(void *k, void *d, void *args)\n{\n\tstruct class_datum *datum = d;\n\tchar *name = k, **classes = args;\n\tint value = datum->value - 1;",
"\tclasses[value] = kstrdup(name, GFP_ATOMIC);\n\tif (!classes[value])\n\t\treturn -ENOMEM;",
"\treturn 0;\n}",
"int security_get_classes(char ***classes, int *nclasses)\n{\n\tint rc;",
"\tread_lock(&policy_rwlock);",
"\trc = -ENOMEM;\n\t*nclasses = policydb.p_classes.nprim;\n\t*classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);\n\tif (!*classes)\n\t\tgoto out;",
"\trc = hashtab_map(policydb.p_classes.table, get_classes_callback,\n\t\t\t*classes);\n\tif (rc) {\n\t\tint i;\n\t\tfor (i = 0; i < *nclasses; i++)\n\t\t\tkfree((*classes)[i]);\n\t\tkfree(*classes);\n\t}",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"static int get_permissions_callback(void *k, void *d, void *args)\n{\n\tstruct perm_datum *datum = d;\n\tchar *name = k, **perms = args;\n\tint value = datum->value - 1;",
"\tperms[value] = kstrdup(name, GFP_ATOMIC);\n\tif (!perms[value])\n\t\treturn -ENOMEM;",
"\treturn 0;\n}",
"int security_get_permissions(char *class, char ***perms, int *nperms)\n{\n\tint rc, i;\n\tstruct class_datum *match;",
"\tread_lock(&policy_rwlock);",
"\trc = -EINVAL;\n\tmatch = hashtab_search(policydb.p_classes.table, class);\n\tif (!match) {\n\t\tprintk(KERN_ERR \"SELinux: %s: unrecognized class %s\\n\",\n\t\t\t__func__, class);\n\t\tgoto out;\n\t}",
"\trc = -ENOMEM;\n\t*nperms = match->permissions.nprim;\n\t*perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);\n\tif (!*perms)\n\t\tgoto out;",
"\tif (match->comdatum) {\n\t\trc = hashtab_map(match->comdatum->permissions.table,\n\t\t\t\tget_permissions_callback, *perms);\n\t\tif (rc)\n\t\t\tgoto err;\n\t}",
"\trc = hashtab_map(match->permissions.table, get_permissions_callback,\n\t\t\t*perms);\n\tif (rc)\n\t\tgoto err;",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn rc;",
"err:\n\tread_unlock(&policy_rwlock);\n\tfor (i = 0; i < *nperms; i++)\n\t\tkfree((*perms)[i]);\n\tkfree(*perms);\n\treturn rc;\n}",
"int security_get_reject_unknown(void)\n{\n\treturn policydb.reject_unknown;\n}",
"int security_get_allow_unknown(void)\n{\n\treturn policydb.allow_unknown;\n}",
"/**\n * security_policycap_supported - Check for a specific policy capability\n * @req_cap: capability\n *\n * Description:\n * This function queries the currently loaded policy to see if it supports the\n * capability specified by @req_cap. Returns true (1) if the capability is\n * supported, false (0) if it isn't supported.\n *\n */\nint security_policycap_supported(unsigned int req_cap)\n{\n\tint rc;",
"\tread_lock(&policy_rwlock);\n\trc = ebitmap_get_bit(&policydb.policycaps, req_cap);\n\tread_unlock(&policy_rwlock);",
"\treturn rc;\n}",
"struct selinux_audit_rule {\n\tu32 au_seqno;\n\tstruct context au_ctxt;\n};",
"void selinux_audit_rule_free(void *vrule)\n{\n\tstruct selinux_audit_rule *rule = vrule;",
"\tif (rule) {\n\t\tcontext_destroy(&rule->au_ctxt);\n\t\tkfree(rule);\n\t}\n}",
"int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)\n{\n\tstruct selinux_audit_rule *tmprule;\n\tstruct role_datum *roledatum;\n\tstruct type_datum *typedatum;\n\tstruct user_datum *userdatum;\n\tstruct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;\n\tint rc = 0;",
"\t*rule = NULL;",
"\tif (!ss_initialized)\n\t\treturn -EOPNOTSUPP;",
"\tswitch (field) {\n\tcase AUDIT_SUBJ_USER:\n\tcase AUDIT_SUBJ_ROLE:\n\tcase AUDIT_SUBJ_TYPE:\n\tcase AUDIT_OBJ_USER:\n\tcase AUDIT_OBJ_ROLE:\n\tcase AUDIT_OBJ_TYPE:\n\t\t/* only 'equals' and 'not equals' fit user, role, and type */\n\t\tif (op != Audit_equal && op != Audit_not_equal)\n\t\t\treturn -EINVAL;\n\t\tbreak;\n\tcase AUDIT_SUBJ_SEN:\n\tcase AUDIT_SUBJ_CLR:\n\tcase AUDIT_OBJ_LEV_LOW:\n\tcase AUDIT_OBJ_LEV_HIGH:\n\t\t/* we do not allow a range, indicated by the presence of '-' */\n\t\tif (strchr(rulestr, '-'))\n\t\t\treturn -EINVAL;\n\t\tbreak;\n\tdefault:\n\t\t/* only the above fields are valid */\n\t\treturn -EINVAL;\n\t}",
"\ttmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);\n\tif (!tmprule)\n\t\treturn -ENOMEM;",
"\tcontext_init(&tmprule->au_ctxt);",
"\tread_lock(&policy_rwlock);",
"\ttmprule->au_seqno = latest_granting;",
"\tswitch (field) {\n\tcase AUDIT_SUBJ_USER:\n\tcase AUDIT_OBJ_USER:\n\t\trc = -EINVAL;\n\t\tuserdatum = hashtab_search(policydb.p_users.table, rulestr);\n\t\tif (!userdatum)\n\t\t\tgoto out;\n\t\ttmprule->au_ctxt.user = userdatum->value;\n\t\tbreak;\n\tcase AUDIT_SUBJ_ROLE:\n\tcase AUDIT_OBJ_ROLE:\n\t\trc = -EINVAL;\n\t\troledatum = hashtab_search(policydb.p_roles.table, rulestr);\n\t\tif (!roledatum)\n\t\t\tgoto out;\n\t\ttmprule->au_ctxt.role = roledatum->value;\n\t\tbreak;\n\tcase AUDIT_SUBJ_TYPE:\n\tcase AUDIT_OBJ_TYPE:\n\t\trc = -EINVAL;\n\t\ttypedatum = hashtab_search(policydb.p_types.table, rulestr);\n\t\tif (!typedatum)\n\t\t\tgoto out;\n\t\ttmprule->au_ctxt.type = typedatum->value;\n\t\tbreak;\n\tcase AUDIT_SUBJ_SEN:\n\tcase AUDIT_SUBJ_CLR:\n\tcase AUDIT_OBJ_LEV_LOW:\n\tcase AUDIT_OBJ_LEV_HIGH:\n\t\trc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);\n\t\tif (rc)\n\t\t\tgoto out;\n\t\tbreak;\n\t}\n\trc = 0;\nout:\n\tread_unlock(&policy_rwlock);",
"\tif (rc) {\n\t\tselinux_audit_rule_free(tmprule);\n\t\ttmprule = NULL;\n\t}",
"\t*rule = tmprule;",
"\treturn rc;\n}",
"/* Check to see if the rule contains any selinux fields */\nint selinux_audit_rule_known(struct audit_krule *rule)\n{\n\tint i;",
"\tfor (i = 0; i < rule->field_count; i++) {\n\t\tstruct audit_field *f = &rule->fields[i];\n\t\tswitch (f->type) {\n\t\tcase AUDIT_SUBJ_USER:\n\t\tcase AUDIT_SUBJ_ROLE:\n\t\tcase AUDIT_SUBJ_TYPE:\n\t\tcase AUDIT_SUBJ_SEN:\n\t\tcase AUDIT_SUBJ_CLR:\n\t\tcase AUDIT_OBJ_USER:\n\t\tcase AUDIT_OBJ_ROLE:\n\t\tcase AUDIT_OBJ_TYPE:\n\t\tcase AUDIT_OBJ_LEV_LOW:\n\t\tcase AUDIT_OBJ_LEV_HIGH:\n\t\t\treturn 1;\n\t\t}\n\t}",
"\treturn 0;\n}",
"int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,\n\t\t\t struct audit_context *actx)\n{\n\tstruct context *ctxt;\n\tstruct mls_level *level;\n\tstruct selinux_audit_rule *rule = vrule;\n\tint match = 0;",
"\tif (!rule) {\n\t\taudit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t\t \"selinux_audit_rule_match: missing rule\\n\");\n\t\treturn -ENOENT;\n\t}",
"\tread_lock(&policy_rwlock);",
"\tif (rule->au_seqno < latest_granting) {\n\t\taudit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t\t \"selinux_audit_rule_match: stale rule\\n\");\n\t\tmatch = -ESTALE;\n\t\tgoto out;\n\t}",
"\tctxt = sidtab_search(&sidtab, sid);\n\tif (!ctxt) {\n\t\taudit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,\n\t\t\t \"selinux_audit_rule_match: unrecognized SID %d\\n\",\n\t\t\t sid);\n\t\tmatch = -ENOENT;\n\t\tgoto out;\n\t}",
"\t/* a field/op pair that is not caught here will simply fall through\n\t without a match */\n\tswitch (field) {\n\tcase AUDIT_SUBJ_USER:\n\tcase AUDIT_OBJ_USER:\n\t\tswitch (op) {\n\t\tcase Audit_equal:\n\t\t\tmatch = (ctxt->user == rule->au_ctxt.user);\n\t\t\tbreak;\n\t\tcase Audit_not_equal:\n\t\t\tmatch = (ctxt->user != rule->au_ctxt.user);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase AUDIT_SUBJ_ROLE:\n\tcase AUDIT_OBJ_ROLE:\n\t\tswitch (op) {\n\t\tcase Audit_equal:\n\t\t\tmatch = (ctxt->role == rule->au_ctxt.role);\n\t\t\tbreak;\n\t\tcase Audit_not_equal:\n\t\t\tmatch = (ctxt->role != rule->au_ctxt.role);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase AUDIT_SUBJ_TYPE:\n\tcase AUDIT_OBJ_TYPE:\n\t\tswitch (op) {\n\t\tcase Audit_equal:\n\t\t\tmatch = (ctxt->type == rule->au_ctxt.type);\n\t\t\tbreak;\n\t\tcase Audit_not_equal:\n\t\t\tmatch = (ctxt->type != rule->au_ctxt.type);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase AUDIT_SUBJ_SEN:\n\tcase AUDIT_SUBJ_CLR:\n\tcase AUDIT_OBJ_LEV_LOW:\n\tcase AUDIT_OBJ_LEV_HIGH:\n\t\tlevel = ((field == AUDIT_SUBJ_SEN ||\n\t\t\t field == AUDIT_OBJ_LEV_LOW) ?\n\t\t\t &ctxt->range.level[0] : &ctxt->range.level[1]);\n\t\tswitch (op) {\n\t\tcase Audit_equal:\n\t\t\tmatch = mls_level_eq(&rule->au_ctxt.range.level[0],\n\t\t\t\t\t level);\n\t\t\tbreak;\n\t\tcase Audit_not_equal:\n\t\t\tmatch = !mls_level_eq(&rule->au_ctxt.range.level[0],\n\t\t\t\t\t level);\n\t\t\tbreak;\n\t\tcase Audit_lt:\n\t\t\tmatch = (mls_level_dom(&rule->au_ctxt.range.level[0],\n\t\t\t\t\t level) &&\n\t\t\t\t !mls_level_eq(&rule->au_ctxt.range.level[0],\n\t\t\t\t\t level));\n\t\t\tbreak;\n\t\tcase Audit_le:\n\t\t\tmatch = mls_level_dom(&rule->au_ctxt.range.level[0],\n\t\t\t\t\t level);\n\t\t\tbreak;\n\t\tcase Audit_gt:\n\t\t\tmatch = (mls_level_dom(level,\n\t\t\t\t\t &rule->au_ctxt.range.level[0]) &&\n\t\t\t\t !mls_level_eq(level,\n\t\t\t\t\t &rule->au_ctxt.range.level[0]));\n\t\t\tbreak;\n\t\tcase Audit_ge:\n\t\t\tmatch = mls_level_dom(level,\n\t\t\t\t\t &rule->au_ctxt.range.level[0]);\n\t\t\tbreak;\n\t\t}\n\t}",
"out:\n\tread_unlock(&policy_rwlock);\n\treturn match;\n}",
"static int (*aurule_callback)(void) = audit_update_lsm_rules;",
"static int aurule_avc_callback(u32 event)\n{\n\tint err = 0;",
"\tif (event == AVC_CALLBACK_RESET && aurule_callback)\n\t\terr = aurule_callback();\n\treturn err;\n}",
"static int __init aurule_init(void)\n{\n\tint err;",
"\terr = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);\n\tif (err)\n\t\tpanic(\"avc_add_callback() failed, error %d\\n\", err);",
"\treturn err;\n}\n__initcall(aurule_init);",
"#ifdef CONFIG_NETLABEL\n/**\n * security_netlbl_cache_add - Add an entry to the NetLabel cache\n * @secattr: the NetLabel packet security attributes\n * @sid: the SELinux SID\n *\n * Description:\n * Attempt to cache the context in @ctx, which was derived from the packet in\n * @skb, in the NetLabel subsystem cache. This function assumes @secattr has\n * already been initialized.\n *\n */\nstatic void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,\n\t\t\t\t u32 sid)\n{\n\tu32 *sid_cache;",
"\tsid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);\n\tif (sid_cache == NULL)\n\t\treturn;\n\tsecattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);\n\tif (secattr->cache == NULL) {\n\t\tkfree(sid_cache);\n\t\treturn;\n\t}",
"\t*sid_cache = sid;\n\tsecattr->cache->free = kfree;\n\tsecattr->cache->data = sid_cache;\n\tsecattr->flags |= NETLBL_SECATTR_CACHE;\n}",
"/**\n * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID\n * @secattr: the NetLabel packet security attributes\n * @sid: the SELinux SID\n *\n * Description:\n * Convert the given NetLabel security attributes in @secattr into a\n * SELinux SID. If the @secattr field does not contain a full SELinux\n * SID/context then use SECINITSID_NETMSG as the foundation. If possible the\n * 'cache' field of @secattr is set and the CACHE flag is set; this is to\n * allow the @secattr to be used by NetLabel to cache the secattr to SID\n * conversion for future lookups. Returns zero on success, negative values on\n * failure.\n *\n */\nint security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,\n\t\t\t\t u32 *sid)\n{\n\tint rc;\n\tstruct context *ctx;\n\tstruct context ctx_new;",
"\tif (!ss_initialized) {\n\t\t*sid = SECSID_NULL;\n\t\treturn 0;\n\t}",
"\tread_lock(&policy_rwlock);",
"\tif (secattr->flags & NETLBL_SECATTR_CACHE)\n\t\t*sid = *(u32 *)secattr->cache->data;\n\telse if (secattr->flags & NETLBL_SECATTR_SECID)\n\t\t*sid = secattr->attr.secid;\n\telse if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {\n\t\trc = -EIDRM;\n\t\tctx = sidtab_search(&sidtab, SECINITSID_NETMSG);\n\t\tif (ctx == NULL)\n\t\t\tgoto out;",
"\t\tcontext_init(&ctx_new);\n\t\tctx_new.user = ctx->user;\n\t\tctx_new.role = ctx->role;\n\t\tctx_new.type = ctx->type;\n\t\tmls_import_netlbl_lvl(&ctx_new, secattr);\n\t\tif (secattr->flags & NETLBL_SECATTR_MLS_CAT) {\n\t\t\trc = ebitmap_netlbl_import(&ctx_new.range.level[0].cat,\n\t\t\t\t\t\t secattr->attr.mls.cat);\n\t\t\tif (rc)\n\t\t\t\tgoto out;\n\t\t\tmemcpy(&ctx_new.range.level[1].cat,\n\t\t\t &ctx_new.range.level[0].cat,\n\t\t\t sizeof(ctx_new.range.level[0].cat));\n\t\t}\n\t\trc = -EIDRM;\n\t\tif (!mls_context_isvalid(&policydb, &ctx_new))\n\t\t\tgoto out_free;",
"\t\trc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);\n\t\tif (rc)\n\t\t\tgoto out_free;",
"\t\tsecurity_netlbl_cache_add(secattr, *sid);",
"\t\tebitmap_destroy(&ctx_new.range.level[0].cat);\n\t} else\n\t\t*sid = SECSID_NULL;",
"\tread_unlock(&policy_rwlock);\n\treturn 0;\nout_free:\n\tebitmap_destroy(&ctx_new.range.level[0].cat);\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}",
"/**\n * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr\n * @sid: the SELinux SID\n * @secattr: the NetLabel packet security attributes\n *\n * Description:\n * Convert the given SELinux SID in @sid into a NetLabel security attribute.\n * Returns zero on success, negative values on failure.\n *\n */\nint security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)\n{\n\tint rc;\n\tstruct context *ctx;",
"\tif (!ss_initialized)\n\t\treturn 0;",
"\tread_lock(&policy_rwlock);",
"\trc = -ENOENT;\n\tctx = sidtab_search(&sidtab, sid);\n\tif (ctx == NULL)\n\t\tgoto out;",
"\trc = -ENOMEM;\n\tsecattr->domain = kstrdup(sym_name(&policydb, SYM_TYPES, ctx->type - 1),\n\t\t\t\t GFP_ATOMIC);\n\tif (secattr->domain == NULL)\n\t\tgoto out;",
"\tsecattr->attr.secid = sid;\n\tsecattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;\n\tmls_export_netlbl_lvl(ctx, secattr);\n\trc = mls_export_netlbl_cat(ctx, secattr);\nout:\n\tread_unlock(&policy_rwlock);\n\treturn rc;\n}\n#endif /* CONFIG_NETLABEL */",
"/**\n * security_read_policy - read the policy.\n * @data: binary policy data\n * @len: length of data in bytes\n *\n */\nint security_read_policy(void **data, size_t *len)\n{\n\tint rc;\n\tstruct policy_file fp;",
"\tif (!ss_initialized)\n\t\treturn -EINVAL;",
"\t*len = security_policydb_len();",
"\t*data = vmalloc_user(*len);\n\tif (!*data)\n\t\treturn -ENOMEM;",
"\tfp.data = *data;\n\tfp.len = *len;",
"\tread_lock(&policy_rwlock);\n\trc = policydb_write(&policydb, &fp);\n\tread_unlock(&policy_rwlock);",
"\tif (rc)\n\t\treturn rc;",
"\t*len = (unsigned long)fp.data - (unsigned long)*data;\n\treturn 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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [1234], "buggy_code_start_loc": [1234], "filenames": ["security/selinux/ss/services.c"], "fixing_code_end_loc": [1239], "fixing_code_start_loc": [1235], "message": "The security_context_to_sid_core function in security/selinux/ss/services.c in the Linux kernel before 3.13.4 allows local users to cause a denial of service (system crash) by leveraging the CAP_MAC_ADMIN capability to set a zero-length security context.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "C5D0B9E7-C5EF-4C15-BD87-FA13FD781E06", "versionEndExcluding": "3.13.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:suse:linux_enterprise_server:10:sp4:*:*:ltss:*:*:*", "matchCriteriaId": "35BBD83D-BDC7-4678-BE94-639F59281139", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:10.04:*:*:*:-:*:*:*", "matchCriteriaId": "01EDA41C-6B2E-49AF-B503-EB3882265C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:esm:*:*:*", "matchCriteriaId": "8D305F7A-D159-4716-AB26-5E38BB5CD991", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.10:*:*:*:*:*:*:*", "matchCriteriaId": "E2076871-2E80-4605-A470-A41C1A8EC7EE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:13.10:*:*:*:*:*:*:*", "matchCriteriaId": "7F61F047-129C-41A6-8A27-FFCBB8563E91", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The security_context_to_sid_core function in security/selinux/ss/services.c in the Linux kernel before 3.13.4 allows local users to cause a denial of service (system crash) by leveraging the CAP_MAC_ADMIN capability to set a zero-length security context."}, {"lang": "es", "value": "La funci\u00f3n security_context_to_sid_core en security/selinux/ss/services.c en el kernel de Linux anterior a 3.13.4 permite a usuarios locales causar una denegaci\u00f3n de servicio (ca\u00edda del sistema) mediante el aprovechamiento de la funcionalidad CAP_MAC_ADMIN para configurar un contexto de seguridad de longitud cero."}], "evaluatorComment": null, "id": "CVE-2014-1874", "lastModified": "2023-02-13T00:38:31.907", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.9, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-02-28T06:18:54.587", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git%3Ba=commit%3Bh=2172fa709ab32ca60e86179dc67d0857be8e2c98"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://linux.oracle.com/errata/ELSA-2014-0771.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://linux.oracle.com/errata/ELSA-2014-3043.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-04/msg00020.html"}, {"source": "secalert@redhat.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "http://www.kernel.org/pub/linux/kernel/v3.x/ChangeLog-3.13.4"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/02/07/2"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/65459"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2128-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2129-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2133-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2134-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2135-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2136-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2137-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2138-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2139-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2140-1"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2141-1"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1062356"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/2172fa709ab32ca60e86179dc67d0857be8e2c98"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-20"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/2172fa709ab32ca60e86179dc67d0857be8e2c98"}, "type": "CWE-20"}
| 262
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"( function( $ ) {\n\t'use strict';",
"\tconst UserProfile = function( args ) {\n\t\tthis.view = new UserProfile.View( {\n\t\t\tmodel: new UserProfile.Model( args ),\n\t\t} );\n\t};",
"\tUserProfile.View = Backbone.View.extend( {\n\t\tevents: {\n\t\t\t'click #lp-remove-upload-photo': '_removePhoto',\n\t\t\t'click #lp-upload-photo': '_upload',\n\t\t\t'click .lp-cancel-upload': '_cancel',\n\t\t\t'click .lp-save-upload': '_save',\n\t\t},\n\t\tel: '#lp-user-edit-avatar',\n\t\tuploader: null,\n\t\tinitialize() {\n\t\t\t_.bindAll( this, 'filesAdded', 'uploadProgress', 'uploadError', 'fileUploaded', 'crop' );\n\t\t\tthis._getUploader();\n\t\t},\n\t\t_save( e ) {\n\t\t\te.preventDefault();\n\t\t\tconst self = this;\n\t\t\t$.ajax( {",
"\t\t\t\turl: '?lp-ajax=save-uploaded-user-avatar',",
"\t\t\t\tdata: this.$( '.lp-avatar-crop-image' ).serializeJSON(),\n\t\t\t\ttype: 'post',\n\t\t\t\tsuccess( response ) {\n\t\t\t\t\tresponse = LP.parseJSON( response );\n\t\t\t\t\tif ( ! response.success ) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}",
"\t\t\t\t\tself.$( '.lp-avatar-crop-image' ).remove();",
"\t\t\t\t\t$( '.lp-user-profile-avatar' ).html( response.avatar );",
"\t\t\t\t\tself.$().attr( 'data-custom', 'yes' );\n\t\t\t\t\tself.$( '.profile-picture' ).toggleClass( 'profile-avatar-current' ).filter( '.profile-avatar-current' ).html( response.avatar );\n\t\t\t\t},\n\t\t\t} );\n\t\t},\n\t\t$( selector ) {\n\t\t\treturn selector ? $( this.$el ).find( selector ) : $( this.$el );\n\t\t},\n\t\t_removePhoto( e ) {\n\t\t\te.preventDefault();",
"\t\t\t// eslint-disable-next-line no-alert\n\t\t\tif ( ! confirm( 'Are you sure?' ) ) {\n\t\t\t\treturn;\n\t\t\t}\n",
"\t\t\tthis.$().removeAttr( 'data-custom' );\n\t\t\tthis.$( '.profile-picture' ).toggleClass( 'profile-avatar-current' );\n\t\t\tthis.$( '#submit' ).prop( 'disabled', false );",
"\t\t\t$( '.lp-user-profile-avatar' ).html( this.$( '.profile-avatar-current' ).find( 'img' ).clone() );",
"\t\t},\n\t\t_upload( e ) {\n\t\t\te.preventDefault();\n\t\t},\n\t\t_cancel( e ) {\n\t\t\te.preventDefault();\n\t\t\tthis.$crop && this.$crop.remove();\n\t\t\tthis.$( '.lp-avatar-preview' ).removeClass( 'croping' );\n\t\t},\n\t\tfilesAdded( up, files ) {\n\t\t\tconst that = this;\n\t\t\tup.files.splice( 0, up.files.length - 1 );\n\t\t\tthat.$( '.lp-avatar-preview' ).addClass( 'uploading' );\n\t\t\tthat.$( '.lp-avatar-upload-progress-value' ).width( 0 );\n\t\t\tthat.uploader.start();\n\t\t},\n\t\tuploadProgress( up, file ) {\n\t\t\tthis.$( '.lp-avatar-upload-progress-value' ).css( 'width', file.percent + '%' );\n\t\t},\n\t\tuploadError( up, err ) {\n\t\t\tthis.$( '.lp-avatar-preview' ).addClass( 'upload-error' ).removeClass( 'uploading' );\n\t\t\tthis.$( '.lp-avatar-upload-error' ).html( err );\n\t\t},\n\t\tfileUploaded( up, file, info ) {\n\t\t\tthis.$( '.lp-avatar-preview' ).removeClass( 'upload-error' ).removeClass( 'uploading' );\n\t\t\tconst that = this,\n\t\t\t\tresponse = LP.parseJSON( info.response );\n\t\t\tif ( response.url ) {\n\t\t\t\tthis.avatar = response.url;\n\t\t\t\t$( '<img/>' )\n\t\t\t\t\t.attr( 'src', response.url )\n\t\t\t\t\t.on( 'load', function() {\n\t\t\t\t\t\tthat.model.set( $.extend( response, {\n\t\t\t\t\t\t\twidth: this.width,\n\t\t\t\t\t\t\theight: this.height,\n\t\t\t\t\t\t} ) );\n\t\t\t\t\t\tthat.crop();\n\t\t\t\t\t} );\n\t\t\t}\n\t\t},\n\t\tcrop() {\n\t\t\tthis.model.set( 'r', Math.random() );\n\t\t\tnew UserProfile.Crop( this );\n\t\t\tthis.$( '#submit' ).prop( 'disabled', false );\n\t\t},\n\t\t_getUploader() {\n\t\t\tif ( this.uploader ) {\n\t\t\t\treturn this.uploader;\n\t\t\t}\n\t\t\tthis.uploader = new plupload.Uploader( {\n\t\t\t\truntimes: 'html5,flash,silverlight,html4',\n\t\t\t\tbrowse_button: 'lp-upload-photo',\n\t\t\t\tcontainer: $( '#lp-user-edit-avatar' ).get( 0 ),\n\t\t\t\turl: ( typeof lpGlobalSettings !== 'undefined' ? lpGlobalSettings.ajax : '' ).addQueryVar( 'action', 'learnpress_upload-user-avatar' ),\n\t\t\t\tfilters: {\n\t\t\t\t\tmax_file_size: '10mb',\n\t\t\t\t\tmime_types: [\n\t\t\t\t\t\t{ title: 'Image', extensions: 'png,jpg,bmp,gif' },\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tfile_data_name: 'lp-upload-avatar',\n\t\t\t\tinit: {\n\t\t\t\t\tPostInit() {\n\t\t\t\t\t},\n\t\t\t\t\tFilesAdded: this.filesAdded,\n\t\t\t\t\tUploadProgress: this.uploadProgress,\n\t\t\t\t\tFileUploaded: this.fileUploaded,\n\t\t\t\t\tError: this.uploadError,\n\t\t\t\t},\n\t\t\t} );\n\t\t\tthis.uploader.init();\n\t\t\treturn this.uploader;\n\t\t},\n\t} );\n\tUserProfile.Model = Backbone.Model.extend( {} );\n\tUserProfile.Crop = function( $view ) {\n\t\tconst self = this,\n\t\t\tdata = $view.model.toJSON(),\n\t\t\t$crop = $( LP.template( 'tmpl-crop-user-avatar' )( data ) );\n\t\t$crop.appendTo( $view.$( '#profile-avatar-uploader' ) );",
"\t\t$view.$crop = $crop;\n\t\tlet $img = $crop.find( 'img' ),\n\t\t\twx = 0,\n\t\t\thx = 0,\n\t\t\tlx = 0,\n\t\t\ttx = 0,\n\t\t\tnw = 0,\n\t\t\tnh = 0,\n\t\t\tmaxWidth = 870;\n\t\tthis.initCrop = function() {\n\t\t\tconst r1 = data.viewWidth / data.viewHeight,\n\t\t\t\tr2 = data.width / data.height;",
"\t\t\tif ( r1 >= r2 ) {\n\t\t\t\twx = data.viewWidth;\n\t\t\t\thx = data.height * data.viewWidth / data.width;\n\t\t\t\tlx = 0;\n\t\t\t\ttx = -( hx - data.viewHeight ) / 2;\n\t\t\t} else {\n\t\t\t\thx = data.viewHeight;\n\t\t\t\twx = data.width * data.viewHeight / data.height;\n\t\t\t\ttx = 0;\n\t\t\t\tlx = -( wx - data.viewWidth ) / 2;\n\t\t\t}\n\t\t\tnw = wx;\n\t\t\tnh = hx;\n\t\t\t$img.draggable( {\n\t\t\t\tdrag( e, ui ) {\n\t\t\t\t\tif ( ui.position.left > 0 ) {\n\t\t\t\t\t\tui.position.left = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif ( ui.position.top > 0 ) {\n\t\t\t\t\t\tui.position.top = 0;\n\t\t\t\t\t}\n\t\t\t\t\tconst xx = data.viewWidth - nw,\n\t\t\t\t\t\tyy = data.viewHeight - nh;\n\t\t\t\t\tif ( xx > ui.position.left ) {\n\t\t\t\t\t\tui.position.left = xx;\n\t\t\t\t\t}\n\t\t\t\t\tif ( yy > ui.position.top ) {\n\t\t\t\t\t\tui.position.top = yy;\n\t\t\t\t\t}\n\t\t\t\t\t$( document.body ).addClass( 'profile-dragging' );\n\t\t\t\t},\n\t\t\t\tstop( e, ui ) {\n\t\t\t\t\tlx = parseInt( $img.css( 'left' ) );\n\t\t\t\t\ttx = parseInt( $img.css( 'top' ) );\n\t\t\t\t\tdd = ( Math.abs( lx ) + data.viewWidth / 2 ) / nw;\n\t\t\t\t\tbb = ( Math.abs( tx ) + data.viewHeight / 2 ) / nh;\n\t\t\t\t\tself.update( {\n\t\t\t\t\t\twidth: nw,\n\t\t\t\t\t\theight: nh,\n\t\t\t\t\t\ttop: tx,\n\t\t\t\t\t\tleft: lx,\n\t\t\t\t\t} );\n\t\t\t\t\t$( document.body ).removeClass( 'profile-dragging' );\n\t\t\t\t},\n\t\t\t} );\n\t\t\tvar dd = ( Math.abs( lx ) + data.viewWidth / 2 ) / wx,\n\t\t\t\tbb = ( Math.abs( tx ) + data.viewHeight / 2 ) / hx;\n\t\t\t$crop.find( '.lp-zoom > div' ).slider( {\n\t\t\t\tcreate() {\n\t\t\t\t\tself.update( {\n\t\t\t\t\t\twidth: wx,\n\t\t\t\t\t\theight: hx,\n\t\t\t\t\t\ttop: tx,\n\t\t\t\t\t\tleft: lx,\n\t\t\t\t\t} );\n\t\t\t\t},\n\t\t\t\tslide( e, ui ) {\n\t\t\t\t\tnw = wx + ( ui.value / 100 ) * data.width * 2;\n\t\t\t\t\tnh = hx + ( ui.value / 100 ) * data.height * 2;\n\t\t\t\t\tlet nl = data.viewWidth / 2 - ( nw * dd ),\n\t\t\t\t\t\tnt = data.viewHeight / 2 - nh * bb;",
"\t\t\t\t\tif ( nl > 0 ) {\n\t\t\t\t\t\tnl = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif ( nt > 0 ) {\n\t\t\t\t\t\tnt = 0;\n\t\t\t\t\t}\n\t\t\t\t\tconst xx = parseInt( data.viewWidth - nw ),\n\t\t\t\t\t\tyy = parseInt( data.viewHeight - nh );",
"\t\t\t\t\tif ( xx > nl ) {\n\t\t\t\t\t\tnl = lx = xx;\n\t\t\t\t\t}\n\t\t\t\t\tif ( yy > nt ) {\n\t\t\t\t\t\tnt = tx = yy;\n\t\t\t\t\t}\n\t\t\t\t\tself.update( {\n\t\t\t\t\t\twidth: nw,\n\t\t\t\t\t\theight: nh,\n\t\t\t\t\t\ttop: nt,\n\t\t\t\t\t\tleft: nl,\n\t\t\t\t\t} );\n\t\t\t\t\t$( document.body ).addClass( 'profile-resizing' );",
"\t\t\t\t\tconsole.log( ui.value, data );\n\t\t\t\t},\n\t\t\t\tstop() {\n\t\t\t\t\t$( document.body ).removeClass( 'profile-resizing' );\n\t\t\t\t},\n\t\t\t} );\n\t\t};\n\t\tthis.update = function( args ) {\n\t\t\t$img.css( {\n\t\t\t\twidth: args.width,\n\t\t\t\theight: args.height,\n\t\t\t\ttop: args.top,\n\t\t\t\tleft: args.left,\n\t\t\t} );\n\t\t\tconst r = args.width / data.width,\n\t\t\t\tleft = parseInt( Math.abs( args.left / r ) ),\n\t\t\t\ttop = parseInt( Math.abs( args.top / r ) ),\n\t\t\t\tright = left + parseInt( data.viewWidth / r ),\n\t\t\t\tbottom = top + parseInt( data.viewHeight / r );\n\t\t\tconst cropData = $.extend( args, {\n\t\t\t\twidth: data.viewWidth,\n\t\t\t\theight: data.viewHeight,\n\t\t\t\tr,\n\t\t\t\tpoints: [ left, top, right, bottom ].join( ',' ),\n\t\t\t} );\n\t\t\t$crop.find( 'input[name^=\"lp-user-avatar-crop\"]' ).each( function() {\n\t\t\t\tconst $input = $( this ),\n\t\t\t\t\tname = $input.data( 'name' );",
"\t\t\t\tif ( name != 'name' && cropData[ name ] !== undefined ) {\n\t\t\t\t\t$input.val( cropData[ name ] );\n\t\t\t\t}\n\t\t\t} );\n\t\t};\n\t\tthis.initCrop();\n\t};",
"\t$( document ).on( 'submit', '#learn-press-form-login', function( e ) {\n\t\tconst $form = $( this ),\n\t\t\tdata = $form.serialize();\n\t\t$form.find( '.learn-press-error, .learn-press-notice, .learn-press-message' ).fadeOut();\n\t\t$form.find( 'input' ).attr( 'disabled', true );",
"\t\tLP.doAjax( {\n\t\t\tdata: {\n\t\t\t\t'lp-ajax': 'login',\n\t\t\t\tdata,\n\t\t\t},\n\t\t\tsuccess( response, raw ) {\n\t\t\t\tLP.showMessages( response.message, $form, 'LOGIN_ERROR' );\n\t\t\t\tif ( response.result == 'error' ) {\n\t\t\t\t\t$form.find( 'input' ).attr( 'disabled', false );\n\t\t\t\t\t$( '#learn-press-form-login input[type=\"text\"]' ).trigger( 'focus' );\n\t\t\t\t}\n\t\t\t\tif ( response.redirect ) {\n\t\t\t\t\tLP.reload( response.redirect );\n\t\t\t\t}\n\t\t\t},\n\t\t\terror() {\n\t\t\t\tLP.showMessages( '', $form, 'LOGIN_ERROR' );\n\t\t\t\t$form.find( 'input' ).attr( 'disabled', false );\n\t\t\t\t$( '#learn-press-form-login input[type=\"text\"]' ).trigger( 'focus' );\n\t\t\t},\n\t\t} );",
"\t\treturn false;\n\t} );",
"\t$( document ).on( 'click', '.table-orders .cancel-order', function( e ) {\n\t\te.preventDefault();\n\t\tconst _this = $( this ),\n\t\t\t_href = _this.attr( 'href' );",
"\t\tLP.alert( learn_press_js_localize.confirm_cancel_order, function( confirm ) {\n\t\t\tif ( confirm ) {\n\t\t\t\twindow.location.href = _href;\n\t\t\t}\n\t\t} );",
"\t\treturn false;\n\t} );",
"\t$( document ).ready( function() {\n\t\tlet $form = $( '#lp-user-profile-form form' ),\n\t\t\toldData = $form.serialize(),\n\t\t\ttimer = null,\n\t\t\t$passwordForm = $form.find( '#lp-profile-edit-password-form' );",
"\t\tfunction _checkData() {\n\t\t\treturn $form.serialize() != oldData;\n\t\t}",
"\t\tfunction _timerCallback() {\n\t\t\t$form.find( '#submit' ).prop( 'disabled', ! _checkData() );\n\t\t}",
"\t\tif ( $passwordForm.length == 0 ) {\n\t\t\t$form.on( 'keyup change', 'input, textarea, select', function() {\n\t\t\t\ttimer && clearTimeout( timer );\n\t\t\t\ttimer = setTimeout( _timerCallback, 300 );\n\t\t\t} );\n\t\t} else {\n\t\t\t$passwordForm.on( 'change keyup', 'input', function( e ) {\n\t\t\t\tconst $target = $( e.target ),\n\t\t\t\t\ttargetName = $target.attr( 'name' ),\n\t\t\t\t\t$oldPass = $form.find( '#pass0' ),\n\t\t\t\t\t$newPass = $form.find( '#pass1' ),\n\t\t\t\t\t$confirmPass = $form.find( '#pass2' ),\n\t\t\t\t\tmatch = ! ( ( $newPass.val() || $confirmPass.val() ) && $newPass.val() != $confirmPass.val() );\n\t\t\t\t$form.find( '#lp-password-not-match' ).toggleClass( 'hide-if-js', match );\n\t\t\t\t$form.find( '#submit' ).prop( 'disabled', ! match || ! $oldPass.val() || ! $newPass.val() || ! $confirmPass.val() );\n\t\t\t} );\n\t\t}",
"\t\tconst args = {};\n\t\tif ( typeof lpProfileUserSettings !== 'undefined' ) {\n\t\t\targs.viewWidth = parseInt( lpProfileUserSettings.avatar_size.width );\n\t\t\targs.viewHeight = parseInt( lpProfileUserSettings.avatar_size.height );\n\t\t}",
"\t\tnew UserProfile( args );",
"\t\tProfile.recoverOrder();\n\t} ).on( 'click', '.btn-load-more-courses', function( event ) {\n\t\tconst $button = $( this );\n\t\tlet paged = $button.data( 'paged' ) || 1;\n\t\tconst pages = $button.data( 'pages' ) || 1;\n\t\tconst container = $button.data( 'container' );\n\t\tconst $container = $( '#' + container );\n\t\tlet url = $button.data( 'url' );",
"\t\tpaged++;\n\t\t$button.data( 'paged', paged ).prop( 'disabled', true ).removeClass( 'btn-ajax-off' ).addClass( 'btn-ajax-on' );",
"\t\tif ( ! url ) {\n\t\t\tconst seg = window.location.href.split( '?' );",
"\t\t\tif ( seg[ 0 ].match( /\\/([0-9]+)\\// ) ) {\n\t\t\t\turl = seg[ 0 ].replace( /\\/([0-9]+)\\//, paged );\n\t\t\t} else {\n\t\t\t\turl = seg[ 0 ] + paged;\n\t\t\t}",
"\t\t\tif ( seg[ 1 ] ) {\n\t\t\t\turl += '?' + seg[ 1 ];\n\t\t\t}\n\t\t} else {\n\t\t\turl = url.addQueryVar( 'current_page', paged );\n\t\t}",
"\t\t$.ajax( {\n\t\t\turl,\n\t\t\tdata: $button.data( 'args' ),\n\t\t\tsuccess( response ) {\n\t\t\t\t$container.append( $( response ).find( '#' + container ).children() );",
"\t\t\t\tif ( paged >= pages ) {\n\t\t\t\t\t$button.remove();\n\t\t\t\t} else {\n\t\t\t\t\t$button.prop( 'disabled', false ).removeClass( 'btn-ajax-on' ).addClass( 'btn-ajax-off' );\n\t\t\t\t}\n\t\t\t},\n\t\t} );\n\t} );",
"\tconst Profile = {\n\t\trecoverOrder( e ) {\n\t\t\tconst $wrap = $( '.order-recover' ),\n\t\t\t\t$buttonRecoverOrder = $wrap.find( '.button-recover-order' ),\n\t\t\t\t$input = $wrap.find( 'input[name=\"order-key\"]' );",
"\t\t\tconst recoverOrder = () => {\n\t\t\t\t$wrap.find( '.learn-press-message' ).remove();",
"\t\t\t\t$( '.profile-recover-order' ).find( '.learn-press-message' ).remove();",
"\t\t\t\t$.post( {\n\t\t\t\t\turl: '',\n\t\t\t\t\tdata: $wrap.serializeJSON(),\n\t\t\t\t\tbeforeSend() {\n\t\t\t\t\t\t$buttonRecoverOrder.addClass( 'loading' ).attr( 'disabled', 'disabled' );\n\t\t\t\t\t},\n\t\t\t\t\tsuccess( response ) {\n\t\t\t\t\t\tresponse = LP.parseJSON( response );",
"\t\t\t\t\t\tif ( response.message ) {\n\t\t\t\t\t\t\tconst $msg = $( '<div class=\"learn-press-message icon\"><i class=\"fa\"></i> ' + response.message + '</div>' );",
"\t\t\t\t\t\t\tif ( response.result == 'error' ) {\n\t\t\t\t\t\t\t\t$msg.addClass( 'error' );\n\t\t\t\t\t\t\t}",
"\t\t\t\t\t\t\t$wrap.before( $msg );\n\t\t\t\t\t\t}",
"\t\t\t\t\t\tif ( response.redirect ) {\n\t\t\t\t\t\t\twindow.location.href = response.redirect;\n\t\t\t\t\t\t}",
"\t\t\t\t\t\t$buttonRecoverOrder.removeClass( 'loading' ).removeAttr( 'disabled', '' );\n\t\t\t\t\t},\n\t\t\t\t\terror() {\n\t\t\t\t\t\t$buttonRecoverOrder.removeClass( 'loading' ).removeAttr( 'disabled', '' );\n\t\t\t\t\t},\n\t\t\t\t} );\n\t\t\t};",
"\t\t\t$buttonRecoverOrder.on( 'click', recoverOrder );\n\t\t},\n\t};\n}( jQuery ) );"
] |
[
1,
1,
1,
0,
1,
1,
1,
1,
1,
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,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [61, 1262, 233, 1156], "buggy_code_start_loc": [27, 1198, 14, 1081], "filenames": ["assets/src/js/frontend/profile.js", "inc/admin/class-lp-admin-ajax.php", "inc/class-lp-ajax.php", "inc/user/lp-user-functions.php"], "fixing_code_end_loc": [71, 1364, 200, 1152], "fixing_code_start_loc": [27, 1199, 14, 1082], "message": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thimpress:learnpress:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "F74AC61D-6728-4759-B5A4-F03B9519485C", "versionEndExcluding": "4.1.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site."}, {"lang": "es", "value": "Los usuarios del plugin LearnPress de WordPress versiones anteriores a 4.1.5, pueden subir una imagen como avatar de perfil tras el registro. Tras este proceso, el usuario recorta y guarda la imagen. A continuaci\u00f3n, se env\u00eda al servidor una petici\u00f3n \"POST\" que contiene el nombre de la imagen suministrado por el usuario para cambiar el nombre y recortar la imagen. Como resultado de esta petici\u00f3n, el nombre de la imagen suministrada por el usuario es cambiada con un valor MD5. Este proceso s\u00f3lo puede llevarse a cabo cuando el tipo de la imagen es JPG o PNG. Un atacante puede usar esta vulnerabilidad para cambiar el nombre de un archivo de imagen arbitrario. Al hacer esto, podr\u00edan destruir el dise\u00f1o del sitio web."}], "evaluatorComment": null, "id": "CVE-2022-0377", "lastModified": "2022-03-08T16:39:46.640", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-28T09:15:09.093", "references": [{"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://bozogullarindan.com/en/2022/01/wordpress-learnpress-plugin-4.1.4.1-arbitrary-image-renaming/"}, {"source": "contact@wpscan.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, {"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://wpscan.com/vulnerability/0d95ada6-53e3-4a80-a395-eacd7b090f26"}], "sourceIdentifier": "contact@wpscan.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-610"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-73"}], "source": "contact@wpscan.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, "type": "CWE-610"}
| 263
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"( function( $ ) {\n\t'use strict';",
"\tconst UserProfile = function( args ) {\n\t\tthis.view = new UserProfile.View( {\n\t\t\tmodel: new UserProfile.Model( args ),\n\t\t} );\n\t};",
"\tUserProfile.View = Backbone.View.extend( {\n\t\tevents: {\n\t\t\t'click #lp-remove-upload-photo': '_removePhoto',\n\t\t\t'click #lp-upload-photo': '_upload',\n\t\t\t'click .lp-cancel-upload': '_cancel',\n\t\t\t'click .lp-save-upload': '_save',\n\t\t},\n\t\tel: '#lp-user-edit-avatar',\n\t\tuploader: null,\n\t\tinitialize() {\n\t\t\t_.bindAll( this, 'filesAdded', 'uploadProgress', 'uploadError', 'fileUploaded', 'crop' );\n\t\t\tthis._getUploader();\n\t\t},\n\t\t_save( e ) {\n\t\t\te.preventDefault();\n\t\t\tconst self = this;\n\t\t\t$.ajax( {",
"\t\t\t\t//url: '?lp-ajax=save-uploaded-user-avatar',\n\t\t\t\turl: ( typeof lpGlobalSettings !== 'undefined' ? lpGlobalSettings.ajax : '' ).addQueryVar( 'action', 'learnpress_save-uploaded-user-avatar' ),",
"\t\t\t\tdata: this.$( '.lp-avatar-crop-image' ).serializeJSON(),\n\t\t\t\ttype: 'post',\n\t\t\t\tsuccess( response ) {\n\t\t\t\t\tresponse = LP.parseJSON( response );\n\t\t\t\t\tif ( ! response.success ) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}",
"\t\t\t\t\tself.$( '.lp-avatar-crop-image' ).remove();",
"\t\t\t\t\t$( '.lp-user-profile-avatar' ).html( response.avatar );",
"\t\t\t\t\tself.$().attr( 'data-custom', 'yes' );\n\t\t\t\t\tself.$( '.profile-picture' ).toggleClass( 'profile-avatar-current' ).filter( '.profile-avatar-current' ).html( response.avatar );\n\t\t\t\t},\n\t\t\t} );\n\t\t},\n\t\t$( selector ) {\n\t\t\treturn selector ? $( this.$el ).find( selector ) : $( this.$el );\n\t\t},\n\t\t_removePhoto( e ) {\n\t\t\te.preventDefault();",
"\t\t\t// eslint-disable-next-line no-alert\n\t\t\tif ( ! confirm( 'Are you sure?' ) ) {\n\t\t\t\treturn;\n\t\t\t}\n",
"\t\t\tconst el = this;",
"\t\t\t$.ajax( {\n\t\t\t\turl: ( typeof lpGlobalSettings !== 'undefined' ? lpGlobalSettings.ajax : '' ).addQueryVar( 'action', 'learnpress_remove-avatar' ),\n\t\t\t\tdata: {},\n\t\t\t\ttype: 'post',\n\t\t\t\tsuccess( response ) {\n\t\t\t\t\tel.$().removeAttr( 'data-custom' );\n\t\t\t\t\tel.$( '.profile-picture' ).toggleClass( 'profile-avatar-current' );\n\t\t\t\t\tel.$( '#submit' ).prop( 'disabled', false );",
"\t\t\t\t\t$( '.lp-user-profile-avatar' ).html( el.$( '.profile-avatar-current' ).find( 'img' ).clone() );\n\t\t\t\t},\n\t\t\t} );",
"\t\t},\n\t\t_upload( e ) {\n\t\t\te.preventDefault();\n\t\t},\n\t\t_cancel( e ) {\n\t\t\te.preventDefault();\n\t\t\tthis.$crop && this.$crop.remove();\n\t\t\tthis.$( '.lp-avatar-preview' ).removeClass( 'croping' );\n\t\t},\n\t\tfilesAdded( up, files ) {\n\t\t\tconst that = this;\n\t\t\tup.files.splice( 0, up.files.length - 1 );\n\t\t\tthat.$( '.lp-avatar-preview' ).addClass( 'uploading' );\n\t\t\tthat.$( '.lp-avatar-upload-progress-value' ).width( 0 );\n\t\t\tthat.uploader.start();\n\t\t},\n\t\tuploadProgress( up, file ) {\n\t\t\tthis.$( '.lp-avatar-upload-progress-value' ).css( 'width', file.percent + '%' );\n\t\t},\n\t\tuploadError( up, err ) {\n\t\t\tthis.$( '.lp-avatar-preview' ).addClass( 'upload-error' ).removeClass( 'uploading' );\n\t\t\tthis.$( '.lp-avatar-upload-error' ).html( err );\n\t\t},\n\t\tfileUploaded( up, file, info ) {\n\t\t\tthis.$( '.lp-avatar-preview' ).removeClass( 'upload-error' ).removeClass( 'uploading' );\n\t\t\tconst that = this,\n\t\t\t\tresponse = LP.parseJSON( info.response );\n\t\t\tif ( response.url ) {\n\t\t\t\tthis.avatar = response.url;\n\t\t\t\t$( '<img/>' )\n\t\t\t\t\t.attr( 'src', response.url )\n\t\t\t\t\t.on( 'load', function() {\n\t\t\t\t\t\tthat.model.set( $.extend( response, {\n\t\t\t\t\t\t\twidth: this.width,\n\t\t\t\t\t\t\theight: this.height,\n\t\t\t\t\t\t} ) );\n\t\t\t\t\t\tthat.crop();\n\t\t\t\t\t} );\n\t\t\t}\n\t\t},\n\t\tcrop() {\n\t\t\tthis.model.set( 'r', Math.random() );\n\t\t\tnew UserProfile.Crop( this );\n\t\t\tthis.$( '#submit' ).prop( 'disabled', false );\n\t\t},\n\t\t_getUploader() {\n\t\t\tif ( this.uploader ) {\n\t\t\t\treturn this.uploader;\n\t\t\t}\n\t\t\tthis.uploader = new plupload.Uploader( {\n\t\t\t\truntimes: 'html5,flash,silverlight,html4',\n\t\t\t\tbrowse_button: 'lp-upload-photo',\n\t\t\t\tcontainer: $( '#lp-user-edit-avatar' ).get( 0 ),\n\t\t\t\turl: ( typeof lpGlobalSettings !== 'undefined' ? lpGlobalSettings.ajax : '' ).addQueryVar( 'action', 'learnpress_upload-user-avatar' ),\n\t\t\t\tfilters: {\n\t\t\t\t\tmax_file_size: '10mb',\n\t\t\t\t\tmime_types: [\n\t\t\t\t\t\t{ title: 'Image', extensions: 'png,jpg,bmp,gif' },\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tfile_data_name: 'lp-upload-avatar',\n\t\t\t\tinit: {\n\t\t\t\t\tPostInit() {\n\t\t\t\t\t},\n\t\t\t\t\tFilesAdded: this.filesAdded,\n\t\t\t\t\tUploadProgress: this.uploadProgress,\n\t\t\t\t\tFileUploaded: this.fileUploaded,\n\t\t\t\t\tError: this.uploadError,\n\t\t\t\t},\n\t\t\t} );\n\t\t\tthis.uploader.init();\n\t\t\treturn this.uploader;\n\t\t},\n\t} );\n\tUserProfile.Model = Backbone.Model.extend( {} );\n\tUserProfile.Crop = function( $view ) {\n\t\tconst self = this,\n\t\t\tdata = $view.model.toJSON(),\n\t\t\t$crop = $( LP.template( 'tmpl-crop-user-avatar' )( data ) );\n\t\t$crop.appendTo( $view.$( '#profile-avatar-uploader' ) );",
"\t\t$view.$crop = $crop;\n\t\tlet $img = $crop.find( 'img' ),\n\t\t\twx = 0,\n\t\t\thx = 0,\n\t\t\tlx = 0,\n\t\t\ttx = 0,\n\t\t\tnw = 0,\n\t\t\tnh = 0,\n\t\t\tmaxWidth = 870;\n\t\tthis.initCrop = function() {\n\t\t\tconst r1 = data.viewWidth / data.viewHeight,\n\t\t\t\tr2 = data.width / data.height;",
"\t\t\tif ( r1 >= r2 ) {\n\t\t\t\twx = data.viewWidth;\n\t\t\t\thx = data.height * data.viewWidth / data.width;\n\t\t\t\tlx = 0;\n\t\t\t\ttx = -( hx - data.viewHeight ) / 2;\n\t\t\t} else {\n\t\t\t\thx = data.viewHeight;\n\t\t\t\twx = data.width * data.viewHeight / data.height;\n\t\t\t\ttx = 0;\n\t\t\t\tlx = -( wx - data.viewWidth ) / 2;\n\t\t\t}\n\t\t\tnw = wx;\n\t\t\tnh = hx;\n\t\t\t$img.draggable( {\n\t\t\t\tdrag( e, ui ) {\n\t\t\t\t\tif ( ui.position.left > 0 ) {\n\t\t\t\t\t\tui.position.left = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif ( ui.position.top > 0 ) {\n\t\t\t\t\t\tui.position.top = 0;\n\t\t\t\t\t}\n\t\t\t\t\tconst xx = data.viewWidth - nw,\n\t\t\t\t\t\tyy = data.viewHeight - nh;\n\t\t\t\t\tif ( xx > ui.position.left ) {\n\t\t\t\t\t\tui.position.left = xx;\n\t\t\t\t\t}\n\t\t\t\t\tif ( yy > ui.position.top ) {\n\t\t\t\t\t\tui.position.top = yy;\n\t\t\t\t\t}\n\t\t\t\t\t$( document.body ).addClass( 'profile-dragging' );\n\t\t\t\t},\n\t\t\t\tstop( e, ui ) {\n\t\t\t\t\tlx = parseInt( $img.css( 'left' ) );\n\t\t\t\t\ttx = parseInt( $img.css( 'top' ) );\n\t\t\t\t\tdd = ( Math.abs( lx ) + data.viewWidth / 2 ) / nw;\n\t\t\t\t\tbb = ( Math.abs( tx ) + data.viewHeight / 2 ) / nh;\n\t\t\t\t\tself.update( {\n\t\t\t\t\t\twidth: nw,\n\t\t\t\t\t\theight: nh,\n\t\t\t\t\t\ttop: tx,\n\t\t\t\t\t\tleft: lx,\n\t\t\t\t\t} );\n\t\t\t\t\t$( document.body ).removeClass( 'profile-dragging' );\n\t\t\t\t},\n\t\t\t} );\n\t\t\tvar dd = ( Math.abs( lx ) + data.viewWidth / 2 ) / wx,\n\t\t\t\tbb = ( Math.abs( tx ) + data.viewHeight / 2 ) / hx;\n\t\t\t$crop.find( '.lp-zoom > div' ).slider( {\n\t\t\t\tcreate() {\n\t\t\t\t\tself.update( {\n\t\t\t\t\t\twidth: wx,\n\t\t\t\t\t\theight: hx,\n\t\t\t\t\t\ttop: tx,\n\t\t\t\t\t\tleft: lx,\n\t\t\t\t\t} );\n\t\t\t\t},\n\t\t\t\tslide( e, ui ) {\n\t\t\t\t\tnw = wx + ( ui.value / 100 ) * data.width * 2;\n\t\t\t\t\tnh = hx + ( ui.value / 100 ) * data.height * 2;\n\t\t\t\t\tlet nl = data.viewWidth / 2 - ( nw * dd ),\n\t\t\t\t\t\tnt = data.viewHeight / 2 - nh * bb;",
"\t\t\t\t\tif ( nl > 0 ) {\n\t\t\t\t\t\tnl = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif ( nt > 0 ) {\n\t\t\t\t\t\tnt = 0;\n\t\t\t\t\t}\n\t\t\t\t\tconst xx = parseInt( data.viewWidth - nw ),\n\t\t\t\t\t\tyy = parseInt( data.viewHeight - nh );",
"\t\t\t\t\tif ( xx > nl ) {\n\t\t\t\t\t\tnl = lx = xx;\n\t\t\t\t\t}\n\t\t\t\t\tif ( yy > nt ) {\n\t\t\t\t\t\tnt = tx = yy;\n\t\t\t\t\t}\n\t\t\t\t\tself.update( {\n\t\t\t\t\t\twidth: nw,\n\t\t\t\t\t\theight: nh,\n\t\t\t\t\t\ttop: nt,\n\t\t\t\t\t\tleft: nl,\n\t\t\t\t\t} );\n\t\t\t\t\t$( document.body ).addClass( 'profile-resizing' );",
"\t\t\t\t\tconsole.log( ui.value, data );\n\t\t\t\t},\n\t\t\t\tstop() {\n\t\t\t\t\t$( document.body ).removeClass( 'profile-resizing' );\n\t\t\t\t},\n\t\t\t} );\n\t\t};\n\t\tthis.update = function( args ) {\n\t\t\t$img.css( {\n\t\t\t\twidth: args.width,\n\t\t\t\theight: args.height,\n\t\t\t\ttop: args.top,\n\t\t\t\tleft: args.left,\n\t\t\t} );\n\t\t\tconst r = args.width / data.width,\n\t\t\t\tleft = parseInt( Math.abs( args.left / r ) ),\n\t\t\t\ttop = parseInt( Math.abs( args.top / r ) ),\n\t\t\t\tright = left + parseInt( data.viewWidth / r ),\n\t\t\t\tbottom = top + parseInt( data.viewHeight / r );\n\t\t\tconst cropData = $.extend( args, {\n\t\t\t\twidth: data.viewWidth,\n\t\t\t\theight: data.viewHeight,\n\t\t\t\tr,\n\t\t\t\tpoints: [ left, top, right, bottom ].join( ',' ),\n\t\t\t} );\n\t\t\t$crop.find( 'input[name^=\"lp-user-avatar-crop\"]' ).each( function() {\n\t\t\t\tconst $input = $( this ),\n\t\t\t\t\tname = $input.data( 'name' );",
"\t\t\t\tif ( name != 'name' && cropData[ name ] !== undefined ) {\n\t\t\t\t\t$input.val( cropData[ name ] );\n\t\t\t\t}\n\t\t\t} );\n\t\t};\n\t\tthis.initCrop();\n\t};",
"\t$( document ).on( 'submit', '#learn-press-form-login', function( e ) {\n\t\tconst $form = $( this ),\n\t\t\tdata = $form.serialize();\n\t\t$form.find( '.learn-press-error, .learn-press-notice, .learn-press-message' ).fadeOut();\n\t\t$form.find( 'input' ).attr( 'disabled', true );",
"\t\tLP.doAjax( {\n\t\t\tdata: {\n\t\t\t\t'lp-ajax': 'login',\n\t\t\t\tdata,\n\t\t\t},\n\t\t\tsuccess( response, raw ) {\n\t\t\t\tLP.showMessages( response.message, $form, 'LOGIN_ERROR' );\n\t\t\t\tif ( response.result == 'error' ) {\n\t\t\t\t\t$form.find( 'input' ).attr( 'disabled', false );\n\t\t\t\t\t$( '#learn-press-form-login input[type=\"text\"]' ).trigger( 'focus' );\n\t\t\t\t}\n\t\t\t\tif ( response.redirect ) {\n\t\t\t\t\tLP.reload( response.redirect );\n\t\t\t\t}\n\t\t\t},\n\t\t\terror() {\n\t\t\t\tLP.showMessages( '', $form, 'LOGIN_ERROR' );\n\t\t\t\t$form.find( 'input' ).attr( 'disabled', false );\n\t\t\t\t$( '#learn-press-form-login input[type=\"text\"]' ).trigger( 'focus' );\n\t\t\t},\n\t\t} );",
"\t\treturn false;\n\t} );",
"\t$( document ).on( 'click', '.table-orders .cancel-order', function( e ) {\n\t\te.preventDefault();\n\t\tconst _this = $( this ),\n\t\t\t_href = _this.attr( 'href' );",
"\t\tLP.alert( learn_press_js_localize.confirm_cancel_order, function( confirm ) {\n\t\t\tif ( confirm ) {\n\t\t\t\twindow.location.href = _href;\n\t\t\t}\n\t\t} );",
"\t\treturn false;\n\t} );",
"\t$( document ).ready( function() {\n\t\tlet $form = $( '#lp-user-profile-form form' ),\n\t\t\toldData = $form.serialize(),\n\t\t\ttimer = null,\n\t\t\t$passwordForm = $form.find( '#lp-profile-edit-password-form' );",
"\t\tfunction _checkData() {\n\t\t\treturn $form.serialize() != oldData;\n\t\t}",
"\t\tfunction _timerCallback() {\n\t\t\t$form.find( '#submit' ).prop( 'disabled', ! _checkData() );\n\t\t}",
"\t\tif ( $passwordForm.length == 0 ) {\n\t\t\t$form.on( 'keyup change', 'input, textarea, select', function() {\n\t\t\t\ttimer && clearTimeout( timer );\n\t\t\t\ttimer = setTimeout( _timerCallback, 300 );\n\t\t\t} );\n\t\t} else {\n\t\t\t$passwordForm.on( 'change keyup', 'input', function( e ) {\n\t\t\t\tconst $target = $( e.target ),\n\t\t\t\t\ttargetName = $target.attr( 'name' ),\n\t\t\t\t\t$oldPass = $form.find( '#pass0' ),\n\t\t\t\t\t$newPass = $form.find( '#pass1' ),\n\t\t\t\t\t$confirmPass = $form.find( '#pass2' ),\n\t\t\t\t\tmatch = ! ( ( $newPass.val() || $confirmPass.val() ) && $newPass.val() != $confirmPass.val() );\n\t\t\t\t$form.find( '#lp-password-not-match' ).toggleClass( 'hide-if-js', match );\n\t\t\t\t$form.find( '#submit' ).prop( 'disabled', ! match || ! $oldPass.val() || ! $newPass.val() || ! $confirmPass.val() );\n\t\t\t} );\n\t\t}",
"\t\tconst args = {};\n\t\tif ( typeof lpProfileUserSettings !== 'undefined' ) {\n\t\t\targs.viewWidth = parseInt( lpProfileUserSettings.avatar_size.width );\n\t\t\targs.viewHeight = parseInt( lpProfileUserSettings.avatar_size.height );\n\t\t}",
"\t\tnew UserProfile( args );",
"\t\tProfile.recoverOrder();\n\t} ).on( 'click', '.btn-load-more-courses', function( event ) {\n\t\tconst $button = $( this );\n\t\tlet paged = $button.data( 'paged' ) || 1;\n\t\tconst pages = $button.data( 'pages' ) || 1;\n\t\tconst container = $button.data( 'container' );\n\t\tconst $container = $( '#' + container );\n\t\tlet url = $button.data( 'url' );",
"\t\tpaged++;\n\t\t$button.data( 'paged', paged ).prop( 'disabled', true ).removeClass( 'btn-ajax-off' ).addClass( 'btn-ajax-on' );",
"\t\tif ( ! url ) {\n\t\t\tconst seg = window.location.href.split( '?' );",
"\t\t\tif ( seg[ 0 ].match( /\\/([0-9]+)\\// ) ) {\n\t\t\t\turl = seg[ 0 ].replace( /\\/([0-9]+)\\//, paged );\n\t\t\t} else {\n\t\t\t\turl = seg[ 0 ] + paged;\n\t\t\t}",
"\t\t\tif ( seg[ 1 ] ) {\n\t\t\t\turl += '?' + seg[ 1 ];\n\t\t\t}\n\t\t} else {\n\t\t\turl = url.addQueryVar( 'current_page', paged );\n\t\t}",
"\t\t$.ajax( {\n\t\t\turl,\n\t\t\tdata: $button.data( 'args' ),\n\t\t\tsuccess( response ) {\n\t\t\t\t$container.append( $( response ).find( '#' + container ).children() );",
"\t\t\t\tif ( paged >= pages ) {\n\t\t\t\t\t$button.remove();\n\t\t\t\t} else {\n\t\t\t\t\t$button.prop( 'disabled', false ).removeClass( 'btn-ajax-on' ).addClass( 'btn-ajax-off' );\n\t\t\t\t}\n\t\t\t},\n\t\t} );\n\t} );",
"\tconst Profile = {\n\t\trecoverOrder( e ) {\n\t\t\tconst $wrap = $( '.order-recover' ),\n\t\t\t\t$buttonRecoverOrder = $wrap.find( '.button-recover-order' ),\n\t\t\t\t$input = $wrap.find( 'input[name=\"order-key\"]' );",
"\t\t\tconst recoverOrder = () => {\n\t\t\t\t$wrap.find( '.learn-press-message' ).remove();",
"\t\t\t\t$( '.profile-recover-order' ).find( '.learn-press-message' ).remove();",
"\t\t\t\t$.post( {\n\t\t\t\t\turl: '',\n\t\t\t\t\tdata: $wrap.serializeJSON(),\n\t\t\t\t\tbeforeSend() {\n\t\t\t\t\t\t$buttonRecoverOrder.addClass( 'loading' ).attr( 'disabled', 'disabled' );\n\t\t\t\t\t},\n\t\t\t\t\tsuccess( response ) {\n\t\t\t\t\t\tresponse = LP.parseJSON( response );",
"\t\t\t\t\t\tif ( response.message ) {\n\t\t\t\t\t\t\tconst $msg = $( '<div class=\"learn-press-message icon\"><i class=\"fa\"></i> ' + response.message + '</div>' );",
"\t\t\t\t\t\t\tif ( response.result == 'error' ) {\n\t\t\t\t\t\t\t\t$msg.addClass( 'error' );\n\t\t\t\t\t\t\t}",
"\t\t\t\t\t\t\t$wrap.before( $msg );\n\t\t\t\t\t\t}",
"\t\t\t\t\t\tif ( response.redirect ) {\n\t\t\t\t\t\t\twindow.location.href = response.redirect;\n\t\t\t\t\t\t}",
"\t\t\t\t\t\t$buttonRecoverOrder.removeClass( 'loading' ).removeAttr( 'disabled', '' );\n\t\t\t\t\t},\n\t\t\t\t\terror() {\n\t\t\t\t\t\t$buttonRecoverOrder.removeClass( 'loading' ).removeAttr( 'disabled', '' );\n\t\t\t\t\t},\n\t\t\t\t} );\n\t\t\t};",
"\t\t\t$buttonRecoverOrder.on( 'click', recoverOrder );\n\t\t},\n\t};\n}( jQuery ) );"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [61, 1262, 233, 1156], "buggy_code_start_loc": [27, 1198, 14, 1081], "filenames": ["assets/src/js/frontend/profile.js", "inc/admin/class-lp-admin-ajax.php", "inc/class-lp-ajax.php", "inc/user/lp-user-functions.php"], "fixing_code_end_loc": [71, 1364, 200, 1152], "fixing_code_start_loc": [27, 1199, 14, 1082], "message": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thimpress:learnpress:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "F74AC61D-6728-4759-B5A4-F03B9519485C", "versionEndExcluding": "4.1.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site."}, {"lang": "es", "value": "Los usuarios del plugin LearnPress de WordPress versiones anteriores a 4.1.5, pueden subir una imagen como avatar de perfil tras el registro. Tras este proceso, el usuario recorta y guarda la imagen. A continuaci\u00f3n, se env\u00eda al servidor una petici\u00f3n \"POST\" que contiene el nombre de la imagen suministrado por el usuario para cambiar el nombre y recortar la imagen. Como resultado de esta petici\u00f3n, el nombre de la imagen suministrada por el usuario es cambiada con un valor MD5. Este proceso s\u00f3lo puede llevarse a cabo cuando el tipo de la imagen es JPG o PNG. Un atacante puede usar esta vulnerabilidad para cambiar el nombre de un archivo de imagen arbitrario. Al hacer esto, podr\u00edan destruir el dise\u00f1o del sitio web."}], "evaluatorComment": null, "id": "CVE-2022-0377", "lastModified": "2022-03-08T16:39:46.640", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-28T09:15:09.093", "references": [{"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://bozogullarindan.com/en/2022/01/wordpress-learnpress-plugin-4.1.4.1-arbitrary-image-renaming/"}, {"source": "contact@wpscan.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, {"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://wpscan.com/vulnerability/0d95ada6-53e3-4a80-a395-eacd7b090f26"}], "sourceIdentifier": "contact@wpscan.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-610"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-73"}], "source": "contact@wpscan.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, "type": "CWE-610"}
| 263
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"/**\n * Class LP_Admin_Ajax\n *\n * @author ThimPress\n * @package LearnPress/Classes\n * @version 3.0.0\n */",
"/**\n * Prevent loading this file directly\n */\ndefined( 'ABSPATH' ) || exit();",
"if ( ! class_exists( 'LP_Admin_Ajax' ) ) {",
"\t/**\n\t * Class LP_Admin_Ajax\n\t */\n\tclass LP_Admin_Ajax {",
"\t\t/**\n\t\t * Add action ajax\n\t\t */\n\t\tpublic static function init() {",
"\t\t\tif ( ! is_user_logged_in() ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\t$ajax_events = array(\n\t\t\t\t'create_page' => false, // Use create new page on Settings\n\t\t\t\t// 'plugin_action' => false,\n\t\t\t\t// 'modal_search_items' => false,\n\t\t\t\t//'dismiss_notice' => false,\n\t\t\t\t//'search_users' => false,\n\t\t\t\t'load_chart' => false,\n\t\t\t\t'search_course_category' => false,\n\t\t\t\t'custom_stats' => false,\n\t\t\t\t//'ignore_setting_up' => false,\n\t\t\t\t'get_page_permalink' => false,\n\t\t\t\t//'dummy_image' => false,\n\t\t\t\t// 'update_add_on_status' => false,\n\t\t\t\t// 'plugin_install' => false,\n\t\t\t\t//'bundle_activate_add_ons' => false,\n\t\t\t\t//'install_sample_data' => false,",
"\t\t\t\t// Remove Notice\n\t\t\t\t//'remove_notice_popup' => false,\n\t\t\t\t// Update order status\n\t\t\t\t// 'update_order_status' => false,\n\t\t\t\t'update_order_exports' => false,\n\t\t\t);",
"\t\t\tforeach ( $ajax_events as $ajax_event => $nopriv ) {\n\t\t\t\tadd_action( 'wp_ajax_learnpress_' . $ajax_event, array( __CLASS__, $ajax_event ) );",
"\t\t\t\t// enable for non-logged in users\n\t\t\t\tif ( $nopriv ) {\n\t\t\t\t\tadd_action( 'wp_ajax_nopriv_learnpress_' . $ajax_event, array( __CLASS__, $ajax_event ) );\n\t\t\t\t}\n\t\t\t}",
"\t\t\tdo_action( 'learn-press/ajax/admin-load', __CLASS__ );",
"\t\t\t$ajax_events = array(\n\t\t\t\t'search_items' => 'modal_search_items',\n\t\t\t\t'update-payment-order', // Update ordering of payments when user changing.\n\t\t\t\t'update-payment-status', // Enable type payment\n\t\t\t\t//'toggle_item_preview',",
"\t\t\t\t// admin editor\n\t\t\t\t'admin_course_editor',\n\t\t\t\t'admin_quiz_editor',\n\t\t\t\t'admin_question_editor',\n\t\t\t\t// duplicator\n\t\t\t\t'duplicator', // Duplicate course, lesson, quiz, question.",
"\t\t\t\t//'add_item_to_order',\n\t\t\t\t//'remove_order_item',",
"\t\t\t\t'modal_search_items', // Used to search courses on LP Order\n\t\t\t\t'modal_search_users', // Used to search users on LP Order\n\t\t\t\t'add_items_to_order', // Used to add courses on LP Order\n\t\t\t\t'remove_items_from_order', // Used to remove items from LP Order\n\t\t\t\t'update_email_status', // Use for enable email on LP Settings\n\t\t\t\t//'create-pages',\n\t\t\t\t'search-authors', // Used to search username on input some page (list courses, lp orders, quizzes, questions... on the Backend\n\t\t\t\t'skip-notice-install',\n\t\t\t\t//'join_newsletter',\n\t\t\t\t//'dashboard-order-status',\n\t\t\t\t//'dashboard-plugin-status',\n\t\t\t\t//'dismiss-notice',\n\t\t\t\t//'sync-user-orders',\n\t\t\t\t//'sync-course-final-quiz',\n\t\t\t\t//'sync-remove-older-data',\n\t\t\t\t//'sync-calculate-course-results',\n\t\t\t\t//'create-question-type',\n\t\t\t\t// 'sync-user-courses',\n\t\t\t);",
"\t\t\tforeach ( $ajax_events as $action => $callback ) {\n\t\t\t\tif ( is_numeric( $action ) ) {\n\t\t\t\t\t$action = $callback;\n\t\t\t\t}",
"\t\t\t\t$actions = LP_Request::parse_action( $action );\n\t\t\t\t$method = $actions['action'];",
"\t\t\t\tif ( ! is_callable( $callback ) ) {\n\t\t\t\t\t$method = preg_replace( '/-/', '_', $method );\n\t\t\t\t\t$callback = array( __CLASS__, $method );\n\t\t\t\t}",
"\t\t\t\tLP_Request::register_ajax( $action, $callback );\n\t\t\t}\n\t\t}",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function sync_calculate_course_results() {\n\t\t\tif ( ! isset( $_REQUEST['sync'] ) ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\t$sync = LP_Helper::sanitize_params_submitted( $_REQUEST['sync'] );",
"\t\t\tif ( empty( $sync ) ) {\n\t\t\t\tdie();\n\t\t\t}",
"\t\t\tglobal $wpdb;\n\t\t\t$api = LP_Repair_Database::instance();",
"\t\t\tif ( $sync === 'get-users' ) {\n\t\t\t\t$query = $wpdb->prepare(\n\t\t\t\t\t\"\n\t\t\t\t\tSELECT ID\n\t\t\t\t\tFROM {$wpdb->users}\n\t\t\t\t\tWHERE 1\n\t\t\t\t\",\n\t\t\t\t\t1\n\t\t\t\t);",
"\t\t\t\t$users = $wpdb->get_col( $query );",
"\t\t\t\tlearn_press_send_json( array( 'users' => $users ) );\n\t\t\t}",
"\t\t\t$api->calculate_course_results( $sync );\n\t\t\tlearn_press_send_json( array( 'result' => 'success' ) );",
"\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Sync orders for each course\n\t\t *\n\t\t * @since 3.1.0\n\t\t * @editor tungnx\n\t\t * @modify 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function sync_course_orders() {\n\t\t\tif ( empty( $_REQUEST['sync'] ) ) {\n\t\t\t\tdie();\n\t\t\t}",
"\t\t\tglobal $wpdb;\n\t\t\t$api = LP_Repair_Database::instance();\n\t\t\t$sync = $_REQUEST['sync'];",
"\t\t\tif ( $sync === 'get-courses' ) {\n\t\t\t\tlearn_press_send_json( array( 'courses' => $api->get_all_courses() ) );\n\t\t\t}",
"\t\t\t$api->sync_course_orders( $sync );\n\t\t\tlearn_press_send_json( array( 'result' => 'success' ) );",
"\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Sync orders for each user\n\t\t *\n\t\t * @since 3.1.0\n\t\t * @editor tungnx\n\t\t * @modify 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function sync_user_orders() {\n\t\t\tif ( empty( $_REQUEST['sync'] ) ) {\n\t\t\t\tdie();\n\t\t\t}",
"\t\t\tglobal $wpdb;\n\t\t\t$api = LP_Repair_Database::instance();\n\t\t\t$sync = $_REQUEST['sync'];",
"\t\t\tif ( $sync === 'get-users' ) {\n\t\t\t\t$query = $wpdb->prepare(\n\t\t\t\t\t\"\n\t\t\t\t\tSELECT ID\n\t\t\t\t\tFROM {$wpdb->users}\n\t\t\t\t\tWHERE 1\n\t\t\t\t\",\n\t\t\t\t\t1\n\t\t\t\t);",
"\t\t\t\t$users = $wpdb->get_col( $query );",
"\t\t\t\tlearn_press_send_json( array( 'users' => $users ) );\n\t\t\t}",
"\t\t\t$api->sync_user_orders( $sync );\n\t\t\tlearn_press_send_json( array( 'result' => 'success' ) );",
"\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Remap final quiz for each course\n\t\t *\n\t\t * @since 3.1.0\n\t\t */\n\t\tpublic static function sync_course_final_quiz() {\n\t\t\tif ( empty( $_REQUEST['sync'] ) ) {\n\t\t\t\tdie();\n\t\t\t}",
"\t\t\tglobal $wpdb;\n\t\t\t$api = LP_Repair_Database::instance();\n\t\t\t$sync = $_REQUEST['sync'];",
"\t\t\tif ( $sync === 'get-courses' ) {\n\t\t\t\tlearn_press_send_json( array( 'courses' => $api->get_all_courses() ) );\n\t\t\t}",
"\t\t\t$api->sync_course_final_quiz( $sync );\n\t\t\tlearn_press_send_json( array( 'result' => 'success' ) );",
"\t\t\tdie();\n\t\t}",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @comment 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function sync_remove_older_data() {\n\t\t\t$api = LP_Repair_Database::instance();\n\t\t\t$api->remove_older_post_meta();\n\t\t\tlearn_press_send_json( array( 'result' => 'success' ) );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Get html of order status to display in WP Dashboad\n\t\t * @editor tungnx\n\t\t * @modify 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function dashboard_order_status() {\n\t\t\tlearn_press_admin_view( 'dashboard/order-status' );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @modify 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function dashboard_plugin_status() {\n\t\t\t$dashboard = new LP_Admin_Dashboard();\n\t\t\t$plugin_data = $dashboard->get_data();\n\t\t\tif ( ! $plugin_data || is_wp_error( $plugin_data ) ) {\n\t\t\t\tlearn_press_admin_view( 'dashboard/plugin-status/html-no-data' );\n\t\t\t} else {\n\t\t\t\tlearn_press_admin_view( 'dashboard/plugin-status/html-results', array( 'plugin_data' => $plugin_data ) );\n\t\t\t}\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Search user on some pages on the Backend\n\t\t */\n\t\tpublic static function search_authors() {\n\t\t\t$args = array(\n\t\t\t\t'orderby' => 'name',\n\t\t\t\t'order' => 'ASC',\n\t\t\t\t'search' => sprintf( '*%s*', esc_attr( LP_Request::get_string( 'term' ) ) ),\n\t\t\t\t'search_columns' => array( 'user_login', 'user_email' ),\n\t\t\t);\n\t\t\t$q = new WP_User_Query( $args );\n\t\t\t$users = array();",
"\t\t\t$results = $q->get_results();",
"\t\t\tif ( $results ) {\n\t\t\t\tforeach ( $results as $result ) {\n\t\t\t\t\t$users[] = array(\n\t\t\t\t\t\t'id' => $result->ID,\n\t\t\t\t\t\t'text' => learn_press_get_profile_display_name( $result->ID ),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\techo json_encode(\n\t\t\t\tarray(\n\t\t\t\t\t'results' => $users,\n\t\t\t\t)\n\t\t\t);\n\t\t\tdie();\n\t\t}",
"\t\t/**\n\t\t * Hide notice install\n\t\t */\n\t\tpublic static function skip_notice_install() {\n\t\t\tdelete_option( 'learn_press_install' );\n\t\t}",
"\t\t/**\n\t\t * Handle ajax admin course editor.\n\t\t *\n\t\t * @since 3.0.0\n\t\t */\n\t\tpublic static function admin_course_editor() {\n\t\t\t$editor = LP_Admin_Editor::get_editor_course();\n\t\t\tself::admin_editor( $editor );\n\t\t}",
"\t\t/**\n\t\t * Handle ajax admin question editor.\n\t\t *\n\t\t * @since 3.0.0\n\t\t */\n\t\tpublic static function admin_question_editor() {\n\t\t\t$editor = LP_Admin_Editor::get_editor_question();\n\t\t\tself::admin_editor( $editor );\n\t\t}",
"\t\t/**\n\t\t * Handle ajax admin quiz editor.\n\t\t *\n\t\t * @since 3.0.0\n\t\t */\n\t\tpublic static function admin_quiz_editor() {\n\t\t\t$editor = LP_Admin_Editor::get_editor_quiz();\n\t\t\tself::admin_editor( $editor );\n\t\t}",
"\t\t/**\n\t\t * @param LP_Admin_Editor $editor\n\t\t *\n\t\t * @since 3.0.2\n\t\t */\n\t\tpublic static function admin_editor( &$editor ) {\n\t\t\t$result = $editor->dispatch();",
"\t\t\tif ( is_wp_error( $result ) ) {\n\t\t\t\tlearn_press_send_json_error( $result->get_error_message() );\n\t\t\t} elseif ( ! $result ) {\n\t\t\t\tlearn_press_send_json_error();\n\t\t\t}",
"\t\t\tlearn_press_send_json_success( $result );\n\t\t}",
"\t\t/**\n\t\t * Send data to join newsletter or dismiss.\n\t\t *\n\t\t * [\n\t\t * This function has deprecated since 3.2.6 from this class.\n\t\t * Please check class LP_Admin and hook learn-press/dismissed-notice-response for more details.\n\t\t * Newsletter function be hooked to the hook above to send subscription when\n\t\t * notice has already dismissed.\n\t\t * ]\n\t\t *\n\t\t * @deprecated\n\t\t *\n\t\t * @since 3.0.10\n\t\t * @editable tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function join_newsletter() {\n\t\t\t$context = LP_Request::get_string( 'context' );\n\t\t\tif ( ! $context || $context != 'newsletter' ) {\n\t\t\t\tupdate_option( 'learn-press-dismissed-newsletter-button', 1 );\n\t\t\t\tlearn_press_send_json_success( __( 'Dismissed!', 'learnpress' ) );\n\t\t\t}\n\t\t\t$user = learn_press_get_current_user();\n\t\t\tif ( ! $user || $user->get_email() == '' ) {\n\t\t\t\tlearn_press_send_json_error( __( 'Fail while joining newsletter! Please try again!', 'learnpress' ) );\n\t\t\t}\n\t\t\t$url = 'https://thimpress.com/mailster/subscribe';\n\t\t\t$response = wp_remote_post(\n\t\t\t\t$url,\n\t\t\t\tarray(\n\t\t\t\t\t'method' => 'POST',\n\t\t\t\t\t'timeout' => 45,\n\t\t\t\t\t'redirection' => 5,\n\t\t\t\t\t'httpversion' => '1.0',\n\t\t\t\t\t'blocking' => true,\n\t\t\t\t\t'headers' => array(),\n\t\t\t\t\t'body' => array(\n\t\t\t\t\t\t'_referer' => 'extern',\n\t\t\t\t\t\t'_nonce' => '4b266caf7b',\n\t\t\t\t\t\t'formid' => '19',\n\t\t\t\t\t\t'email' => $user->get_email(),\n\t\t\t\t\t\t'website' => site_url(),\n\t\t\t\t\t),\n\t\t\t\t\t'cookies' => array(),\n\t\t\t\t)\n\t\t\t);\n\t\t\tif ( is_wp_error( $response ) ) {\n\t\t\t\t$error_message = $response->get_error_message();\n\t\t\t\tlearn_press_send_json_error( __( 'Something went wrong: ', 'learnpress' ) . $error_message );\n\t\t\t} else {\n\t\t\t\tupdate_option( 'learn-press-dismissed-newsletter-button', 1 );\n\t\t\t\tlearn_press_send_json_success( __( 'Thank you for subscribing! Please check and click the confirmation link from the email we\\'ve just sent to your mail box.', 'learnpress' ) );\n\t\t\t}\n\t\t}*/",
"\t\t/**\n\t\t * Duplicate course, lesson, quiz, question.\n\t\t *\n\t\t * @since 3.0.0\n\t\t *\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function duplicator() {\n\t\t\t$post_id = intval( $_GET['id'] ?? 0 );",
"\t\t\t// get post type\n\t\t\t$post_type = learn_press_get_post_type( $post_id );",
"\t\t\tif ( ! $post_id ) {\n\t\t\t\tlearn_press_send_json_error( __( 'Ops! ID not found', 'learnpress' ) );\n\t\t\t} else {",
"\t\t\t\t$new_item_id = '';",
"\t\t\t\t$duplicate_args = apply_filters( 'learn-press/duplicate-post-args', array( 'post_status' => 'publish' ) );",
"\t\t\t\tswitch ( $post_type ) {\n\t\t\t\t\tcase LP_COURSE_CPT:\n\t\t\t\t\t\t$curd = new LP_Course_CURD();\n\t\t\t\t\t\t$new_item_id = $curd->duplicate(\n\t\t\t\t\t\t\t$post_id,\n\t\t\t\t\t\t\tarray(\n\t\t\t\t\t\t\t\t'exclude_meta' => array(\n\t\t\t\t\t\t\t\t\t'order-pending',\n\t\t\t\t\t\t\t\t\t'order-processing',\n\t\t\t\t\t\t\t\t\t'order-completed',\n\t\t\t\t\t\t\t\t\t'order-cancelled',\n\t\t\t\t\t\t\t\t\t'order-failed',\n\t\t\t\t\t\t\t\t\t'count_enrolled_users',\n\t\t\t\t\t\t\t\t\t'_lp_sample_data',\n\t\t\t\t\t\t\t\t\t'_lp_retake_count',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LP_LESSON_CPT:\n\t\t\t\t\t\t$curd = new LP_Lesson_CURD();\n\t\t\t\t\t\t$new_item_id = $curd->duplicate( $post_id, $duplicate_args );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LP_QUIZ_CPT:\n\t\t\t\t\t\t$curd = new LP_Quiz_CURD();\n\t\t\t\t\t\t$new_item_id = $curd->duplicate( $post_id, $duplicate_args );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LP_QUESTION_CPT:\n\t\t\t\t\t\t$curd = new LP_Question_CURD();\n\t\t\t\t\t\t$new_item_id = $curd->duplicate( $post_id, $duplicate_args );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}",
"\t\t\t\tif ( is_wp_error( $new_item_id ) ) {\n\t\t\t\t\tlearn_press_send_json_error( __( 'Duplicate post fail, please try again', 'learnpress' ) );\n\t\t\t\t} else {\n\t\t\t\t\tlearn_press_send_json_success( admin_url( 'post.php?post=' . $new_item_id . '&action=edit' ) );\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\t/**\n\t\t * Update ordering of payments when user changing.\n\t\t *\n\t\t * @since 3.0.0\n\t\t * @use for sorting by type payment gateway\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function update_payment_order() {\n\t\t\t$payment_order = learn_press_get_request( 'order' );\n\t\t\tupdate_option( 'learn_press_payment_order', $payment_order );\n\t\t}",
"\t\t/**\n\t\t * Enable type payment\n\t\t *\n\t\t * @since 3.0.0\n\t\t * @use for enable type payment gateway\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function update_payment_status() {\n\t\t\t$payment_id = learn_press_get_request( 'id' );\n\t\t\t$status = LP_Request::get_string( 'status' );\n\t\t\t$payment = LP_Gateways::instance()->get_gateway( $payment_id );",
"\t\t\tif ( ! $payment ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\t$response[ $payment->id ] = $payment->enable( $status == 'yes' );",
"\t\t\tlearn_press_send_json( $response );\n\t\t}",
"\t\t/**\n\t\t * nable email on LP Settings\n\t\t *\n\t\t * @since 3.0.0\n\t\t * @note tungnnx checked has use\n\t\t */\n\t\tpublic static function update_email_status() {",
"\t\t\t$email_id = LP_Request::get_string( 'id' );\n\t\t\t$status = LP_Request::get_string( 'status' );\n\t\t\t$response = array();",
"\t\t\tif ( $email_id ) {",
"\t\t\t\t$email = LP_Emails::get_email( $email_id );\n\t\t\t\tif ( ! $email ) {\n\t\t\t\t\treturn;\n\t\t\t\t}",
"\t\t\t\t$response[ $email->id ] = $email->enable( $status == 'yes' );\n\t\t\t} else {\n\t\t\t\t$emails = LP_Emails::instance()->emails;\n\t\t\t\tforeach ( $emails as $email ) {\n\t\t\t\t\t$response[ $email->id ] = $email->enable( $status == 'yes' );\n\t\t\t\t}\n\t\t\t}\n\t\t\tlearn_press_send_json( $response );\n\t\t}",
"\t\t/**\n\t\t * Toggle lesson preview.\n\t\t */\n\t\t/*public static function toggle_item_preview() {\n\t\t\t$id = learn_press_get_request( 'item_id' );\n\t\t\tif ( in_array(\n\t\t\t\tget_post_type( $id ),\n\t\t\t\tapply_filters(\n\t\t\t\t\t'learn-press/reviewable-post-types',\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'lp_lesson',\n\t\t\t\t\t\t'lp_quiz',\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t) && wp_verify_nonce( learn_press_get_request( 'nonce' ), 'learn-press-toggle-item-preview' )\n\t\t\t) {\n\t\t\t\t$previewable = learn_press_get_request( 'previewable' );\n\t\t\t\tif ( is_null( $previewable ) ) {\n\t\t\t\t\t$previewable = '0';\n\t\t\t\t}\n\t\t\t\tupdate_post_meta( $id, '_lp_preview', $previewable );\n\t\t\t}\n\t\t}*/",
"\t\t/**\n\t\t * Search items by requesting params.\n\t\t */\n\t\tpublic static function modal_search_items() {\n\t\t\t$term = LP_Helper::sanitize_params_submitted( $_POST['term'] ?? '' );\n\t\t\t$type = LP_Helper::sanitize_params_submitted( $_POST['type'] ?? '' );\n\t\t\t$context = LP_Helper::sanitize_params_submitted( $_POST['context'] ?? '' );\n\t\t\t$context_id = LP_Helper::sanitize_params_submitted( $_POST['context_id'] ?? '' );\n\t\t\t$paged = LP_Helper::sanitize_params_submitted( $_POST['paged'] ?? '' );\n\t\t\t$exclude = LP_Request::get( 'exclude' );",
"\t\t\t$search = new LP_Modal_Search_Items( compact( 'term', 'type', 'context', 'context_id', 'paged', 'exclude' ) );",
"\t\t\tlearn_press_send_json(\n\t\t\t\tarray(\n\t\t\t\t\t'html' => $search->get_html_items(),\n\t\t\t\t\t'nav' => $search->get_pagination(),\n\t\t\t\t\t'items' => $search->get_items(),\n\t\t\t\t)\n\t\t\t);\n\t\t}",
"\t\t/**\n\t\t * Search items by requesting params.\n\t\t *\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function modal_search_users() {\n\t\t\t$term = LP_Helper::sanitize_params_submitted( $_POST['term'] ?? '' );\n\t\t\t$type = LP_Helper::sanitize_params_submitted( $_POST['type'] ?? '' );\n\t\t\t$context = LP_Helper::sanitize_params_submitted( $_POST['context'] ?? '' );\n\t\t\t$context_id = LP_Helper::sanitize_params_submitted( $_POST['context_id'] ?? '' );\n\t\t\t$paged = LP_Helper::sanitize_params_submitted( $_POST['paged'] ?? '' );\n\t\t\t$multiple = LP_Helper::sanitize_params_submitted( $_POST['multiple'] ?? '' ) == 'yes';\n\t\t\t$text_format = LP_Helper::sanitize_params_submitted( $_POST['text_format'] ?? '' );\n\t\t\t$exclude = LP_Request::get( 'exclude' );",
"\t\t\t$search = new LP_Modal_Search_Users( compact( 'term', 'type', 'context', 'context_id', 'paged', 'multiple', 'text_format', 'exclude' ) );",
"\t\t\tlearn_press_send_json(\n\t\t\t\tarray(\n\t\t\t\t\t'html' => $search->get_html_items(),\n\t\t\t\t\t'nav' => $search->get_pagination(),\n\t\t\t\t\t'users' => $search->get_items(),\n\t\t\t\t)\n\t\t\t);\n\t\t}",
"\t\t/**\n\t\t * Search course category.\n\t\t */\n\t\tpublic static function search_course_category() {\n\t\t\tglobal $wpdb;\n\t\t\t$sql = 'SELECT `t`.`term_id` as `id`, '\n\t\t\t\t\t . ' `t`.`name` `text` '\n\t\t\t\t\t . \" FROM {$wpdb->terms} t \"\n\t\t\t\t\t . \"\t\tINNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id AND taxonomy='course_category' \"\n\t\t\t\t\t . ' WHERE `t`.`name` LIKE %s';\n\t\t\t$s = '%' . filter_input( INPUT_GET, 'q' ) . '%';\n\t\t\t$query = $wpdb->prepare( $sql, $s );\n\t\t\t$items = $wpdb->get_results( $query );\n\t\t\t$data = array( 'items' => $items );\n\t\t\techo json_encode( $data );\n\t\t\texit();\n\t\t}",
"\t\t/**\n\t\t * Remove an item from lp order\n\t\t *\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function remove_items_from_order() {\n\t\t\t// ensure that user has permission\n\t\t\tif ( ! current_user_can( 'edit_lp_orders' ) ) {\n\t\t\t\tdie( __( 'Access denied', 'learnpress' ) );\n\t\t\t}",
"\t\t\t// verify nonce\n\t\t\t$nonce = learn_press_get_request( 'remove_nonce' );\n\t\t\tif ( ! wp_verify_nonce( $nonce, 'remove_order_item' ) ) {\n\t\t\t\tdie( __( 'Check nonce failed', 'learnpress' ) );\n\t\t\t}",
"\t\t\t// validate order\n\t\t\t$order_id = learn_press_get_request( 'order_id' );\n\t\t\tif ( ! is_numeric( $order_id ) || learn_press_get_post_type( $order_id ) != 'lp_order' ) {\n\t\t\t\tdie( __( 'Invalid order', 'learnpress' ) );\n\t\t\t}",
"\t\t\t// validate item\n\t\t\t$items = learn_press_get_request( 'items' );",
"\t\t\t$order = learn_press_get_order( $order_id );",
"\t\t\tglobal $wpdb;",
"\t\t\tforeach ( $items as $item_id ) {\n\t\t\t\t$order->remove_item( $item_id );\n\t\t\t}",
"\t\t\t$order_data = learn_press_update_order_items( $order_id );\n\t\t\t$currency_symbol = learn_press_get_currency_symbol( $order_data['currency'] );\n\t\t\t$order_data['subtotal_html'] = learn_press_format_price( $order_data['subtotal'], $currency_symbol );\n\t\t\t$order_data['total_html'] = learn_press_format_price( $order_data['total'], $currency_symbol );\n\t\t\t$order_items = $order->get_items();\n\t\t\tif ( $order_items ) {\n\t\t\t\t$html = '';\n\t\t\t\tforeach ( $order_items as $item ) {\n\t\t\t\t\tob_start();\n\t\t\t\t\tinclude learn_press_get_admin_view( 'meta-boxes/order/order-item.php' );\n\t\t\t\t\t$html .= ob_get_clean();\n\t\t\t\t}\n\t\t\t}",
"\t\t\tlearn_press_send_json(\n\t\t\t\tarray(\n\t\t\t\t\t'result' => 'success',\n\t\t\t\t\t'item_html' => $html,\n\t\t\t\t\t'order_data' => $order_data,\n\t\t\t\t)\n\t\t\t);\n\t\t}",
"\t\t/**\n\t\t * Add courses to order\n\t\t *\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function add_items_to_order() {\n\t\t\t// ensure that user has permission\n\t\t\tif ( ! current_user_can( 'edit_lp_orders' ) ) {\n\t\t\t\tdie( __( 'Permission denied', 'learnpress' ) );\n\t\t\t}",
"\t\t\t// validate order\n\t\t\t$order_id = learn_press_get_request( 'order_id' );\n\t\t\tif ( ! is_numeric( $order_id ) || learn_press_get_post_type( $order_id ) != 'lp_order' ) {\n\t\t\t\tdie( __( 'Invalid order', 'learnpress' ) );\n\t\t\t}",
"\t\t\t// validate item\n\t\t\t$item_ids = learn_press_get_request( 'items' );\n\t\t\t$order = learn_press_get_order( $order_id );",
"\t\t\t$response = array(\n\t\t\t\t'result' => 'error',\n\t\t\t);",
"\t\t\t$order_item_ids = $order->add_items( $item_ids );",
"\t\t\tif ( $order_item_ids ) {\n\t\t\t\t$html = '';\n\t\t\t\t$order_items = $order->get_items();",
"\t\t\t\t$order_data = learn_press_update_order_items( $order_id );\n\t\t\t\t$currency_symbol = learn_press_get_currency_symbol( $order_data['currency'] );\n\t\t\t\t$order_data['subtotal_html'] = learn_press_format_price( $order_data['subtotal'], $currency_symbol );\n\t\t\t\t$order_data['total_html'] = learn_press_format_price( $order_data['total'], $currency_symbol );",
"\t\t\t\tif ( $order_items ) {\n\t\t\t\t\tforeach ( $order_items as $item ) {",
"\t\t\t\t\t\tif ( ! in_array( $item['id'], $order_item_ids ) ) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}",
"\t\t\t\t\t\tob_start();\n\t\t\t\t\t\tinclude learn_press_get_admin_view( 'meta-boxes/order/order-item.php' );\n\t\t\t\t\t\t$html .= ob_get_clean();\n\t\t\t\t\t}\n\t\t\t\t}",
"\t\t\t\t$response = array(\n\t\t\t\t\t'result' => 'success',\n\t\t\t\t\t'item_html' => $html,\n\t\t\t\t\t'order_data' => $order_data,\n\t\t\t\t);\n\t\t\t}",
"\t\t\tlearn_press_send_json( $response );\n\t\t}",
"\t\t/**\n\t\t * Get content send via payload and parse to json.\n\t\t *\n\t\t * @param mixed $params (Optional) List of keys want to get from payload.\n\t\t *\n\t\t * @return array|bool|mixed|object\n\t\t */\n\t\tpublic static function get_php_input( $params = '' ) {\n\t\t\tstatic $data = false;\n\t\t\tif ( false === $data ) {\n\t\t\t\ttry {\n\t\t\t\t\t$data = json_decode( file_get_contents( 'php://input' ), true );\n\t\t\t\t} catch ( Exception $exception ) {\n\t\t\t\t}\n\t\t\t}",
"\t\t\tif ( $data && func_num_args() > 0 ) {\n\t\t\t\t$params = is_array( func_get_arg( 0 ) ) ? func_get_arg( 0 ) : func_get_args();\n\t\t\t\tif ( $params ) {\n\t\t\t\t\t$request = array();\n\t\t\t\t\tforeach ( $params as $key ) {\n\t\t\t\t\t\t$request[] = array_key_exists( $key, $data ) ? $data[ $key ] : false;\n\t\t\t\t\t}",
"\t\t\t\t\treturn $request;\n\t\t\t\t}\n\t\t\t}",
"\t\t\treturn $data;\n\t\t}",
"\t\t/**\n\t\t * Parse request content into var.\n\t\t * Normally, parse and assign to $_POST or $_GET.\n\t\t *\n\t\t * @param $var\n\t\t */\n\t\tpublic static function parsePhpInput( &$var ) {\n\t\t\t$data = self::get_php_input();",
"\t\t\tif ( $data ) {\n\t\t\t\tforeach ( $data as $k => $v ) {\n\t\t\t\t\t$var[ $k ] = $v;\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\tpublic static function load_chart() {\n\t\t\tif ( ! class_exists( 'LP_Submenu_Statistics' ) ) {\n\t\t\t\t$statistic = include_once LP_PLUGIN_PATH . '/inc/admin/sub-menus/class-lp-submenu-statistics.php';\n\t\t\t} else {\n\t\t\t\t$statistic = new LP_Submenu_Statistics();\n\t\t\t}\n\t\t\t$statistic->load_chart();\n\t\t}",
"\t\t/**\n\t\t * @param $query\n\t\t *\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function search_users() {\n\t\t\tif ( ! current_user_can( 'edit_lp_orders' ) ) {\n\t\t\t\tdie( - 1 );\n\t\t\t}",
"\t\t\t$term = LP_Helper::sanitize_params_submitted( $_REQUEST['term'] );",
"\t\t\tif ( empty( $term ) ) {\n\t\t\t\tdie( __FILE__ . '::' . __FUNCTION__ );",
"\t\t\t}",
"\t\t\t$found_customers = array();",
"\t\t\tadd_action( 'pre_user_query', array( __CLASS__, 'json_search_customer_name' ) );",
"\t\t\t$customers_query = new WP_User_Query(\n\t\t\t\tapply_filters(\n\t\t\t\t\t'learn_press_search_customers_query',\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'fields' => 'all',\n\t\t\t\t\t\t'orderby' => 'display_name',\n\t\t\t\t\t\t'search' => '*' . $term . '*',\n\t\t\t\t\t\t'search_columns' => array( 'ID', 'user_login', 'user_email', 'user_nicename' ),\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t);",
"\t\t\tremove_action( 'pre_user_query', array( __CLASS__, 'json_search_customer_name' ) );",
"\t\t\t$customers = $customers_query->get_results();",
"\t\t\tif ( ! empty( $customers ) ) {\n\t\t\t\tforeach ( $customers as $customer ) {\n\t\t\t\t\t$found_customers[] = array(\n\t\t\t\t\t\t'label' => $customer->display_name . ' (#' . $customer->ID . ' – ' . sanitize_email( $customer->user_email ) . ')',\n\t\t\t\t\t\t'value' => $customer->ID,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}",
"\t\t\techo json_encode( $found_customers );\n\t\t\tdie();\n\t\t}*/",
"\t\tpublic static function json_search_customer_name( $query ) {\n\t\t\tglobal $wpdb;",
"\t\t\t$term = LP_Helper::sanitize_params_submitted( $_REQUEST['term'] );\n\t\t\tif ( method_exists( $wpdb, 'esc_like' ) ) {\n\t\t\t\t$term = $wpdb->esc_like( $term );\n\t\t\t} else {\n\t\t\t\t$term = like_escape( $term );\n\t\t\t}",
"\t\t\t$query->query_from .= \" INNER JOIN {$wpdb->usermeta} AS user_name ON {$wpdb->users}.ID = user_name.user_id AND ( user_name.meta_key = 'first_name' OR user_name.meta_key = 'last_name' ) \";\n\t\t\t$query->query_where .= $wpdb->prepare( ' OR user_name.meta_value LIKE %s ', '%' . $term . '%' );\n\t\t}",
"\t\t/**\n\t\t * Dismiss notice\n\t\t *\n\t\t * @update 3.2.6\n\t\t * @editor tungnx\n\t\t * @comment 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function dismiss_notice() {\n\t\t\t$name = learn_press_get_request( 'name' );\n\t\t\t$value = learn_press_get_request( 'value' );\n\t\t\t$expired = learn_press_get_request( 'expired' );",
"\t\t\t// LP_Admin_Notice::instance()->dismiss_notice_2( $name, $value, $expired );",
"\t\t\tdie();\n\t\t}*/",
"\t\t/*\n\t\t * comment by tungnnx\n\t\t * @reason not uses - low security\n\t\t * @since 3.2.6.8\n\t\t */\n\t\t/*\n\t\tpublic static function plugin_action() {\n\t\t\t$url = learn_press_get_request( 'url' );\n\t\t\tob_start();\n\t\t\twp_remote_get( $url );\n\t\t\tob_get_clean();\n\t\t\techo wp_remote_get( admin_url( 'admin.php?page=learn-press-addons&tab=installed' ) );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * create new page on LP Settings\n\t\t *\n\t\t * @note tungnnx checked use\n\t\t */\n\t\tpublic static function create_page() {\n\t\t\t$response = array(\n\t\t\t\t'code' => 0,\n\t\t\t\t'message' => '',\n\t\t\t);",
"\t\t\t/**\n\t\t\t * Check valid\n\t\t\t *\n\t\t\t * 1. Capability - user can edit pages (add\\edit\\delete)\n\t\t\t * 2. Check nonce return true\n\t\t\t * 3. param post page_name not empty\n\t\t\t *\n\t\t\t * @since 3.2.6.8\n\t\t\t * @author tungnx\n\t\t\t */\n\t\t\tif ( ! current_user_can( 'edit_pages' ) || empty( $_POST['page_name'] ) ) {\n\t\t\t\t$response['message'] = 'Request invalid';\n\t\t\t\tlearn_press_send_json( $response );\n\t\t\t}",
"\t\t\t$page_name = LP_Helper::sanitize_params_submitted( $_POST['page_name'] );",
"\t\t\tif ( $page_name ) {\n\t\t\t\t$page_id = LP_Helper::create_page( $page_name );",
"\t\t\t\tif ( $page_id ) {\n\t\t\t\t\t$response['code'] = 1;\n\t\t\t\t\t$response['message'] = 'create page success';\n\t\t\t\t\t$response['page'] = get_post( $page_id );\n\t\t\t\t\t$html = learn_press_pages_dropdown( '', '', array( 'echo' => false ) );\n\t\t\t\t\tpreg_match_all( '!value=\\\"([0-9]+)\\\"!', $html, $matches );\n\t\t\t\t\t$response['positions'] = $matches[1];\n\t\t\t\t\t$response['html'] = '<a href=\"' . get_edit_post_link( $page_id ) . '\" target=\"_blank\">' . __( 'Edit Page', 'learnpress' ) . '</a> ';\n\t\t\t\t\t$response['html'] .= '<a href=\"' . get_permalink( $page_id ) . '\" target=\"_blank\">' . __( 'View Page', 'learnpress' ) . '</a>';\n\t\t\t\t} else {\n\t\t\t\t\t$response['error'] = __( 'Error! Page creation failed. Please try again.', 'learnpress' );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$response['error'] = __( 'Empty page name!', 'learnpress' );\n\t\t\t}\n\t\t\tlearn_press_send_json( $response );\n\t\t}",
"\t\t/**\n\t\t * Create LP static pages\n\t\t *\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function create_pages() {\n\t\t\tcheck_admin_referer( 'create-pages' );",
"\t\t\t$pages = LP_Request::get_list_array( 'pages' );\n\t\t\t$pages = array_fill_keys( $pages, '' );\n\t\t\t$all_pages = learn_press_static_page_ids();\n\t\t\t$page_names = learn_press_static_pages();",
"\t\t\tif ( empty( $pages ) ) {\n\t\t\t\t$pages = $all_pages;\n\t\t\t}",
"\t\t\tforeach ( $pages as $id => $page_id ) {\n\t\t\t\tif ( ! empty( $all_pages[ $id ] ) ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}",
"\t\t\t\t$page_id = LP_Helper::create_page( isset( $page_names[ $id ] ) ? $page_names[ $id ] : ucfirst( $id ), $id );\n\t\t\t}",
"\t\t\tLP()->flush_rewrite_rules();",
"\t\t\techo esc_html__( 'The required pages are successfully created.', 'learnpress' );",
"\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Install sample data or dismiss the notice depending on user's option\n\t\t */\n\t\t/*public static function install_sample_data() {\n\t\t\t$yes = ! empty( $_REQUEST['yes'] ) ? $_REQUEST['yes'] : '';\n\t\t\t$response = array( 'result' => 'fail' );\n\t\t\t$retry_button = sprintf( '<a href=\"\" class=\"button yes\" data-action=\"yes\">%s</a>', __( 'Please try again.', 'learnpress' ) );\n\t\t\t$dismiss_button = sprintf( '<a href=\"\" class=\"button disabled no\" data-action=\"no\">%s</a>', __( 'Cancel', 'learnpress' ) );\n\t\t\t$buttons = sprintf( '<p>%s %s</p>', $retry_button, $dismiss_button );\n\t\t\tif ( 'no' == $yes ) {\n\t\t\t\tset_transient( 'learn_press_install_sample_data', 'off', 12 * HOUR_IN_SECONDS );\n\t\t\t} else {\n\t\t\t\t$result = array( 'status' => 'activate' );// learn_press_install_and_active_add_on( 'learnpress-import-export' );\n\t\t\t\tif ( 'activate' == $result['status'] ) {\n\t\t\t\t\t// copy dummy-data.xml to import folder of the add-on\n\t\t\t\t\tlpie_mkdir( lpie_import_path() );\n\t\t\t\t\tif ( file_exists( lpie_import_path() ) ) {\n\t\t\t\t\t\t$import_source = LP_PLUGIN_PATH . '/dummy-data/dummy-data.xml';\n\t\t\t\t\t\t$file = 'dummy-data-' . time() . '.xml';\n\t\t\t\t\t\t$copy = lpie_import_path() . '/' . $file;\n\t\t\t\t\t\tcopy( $import_source, $copy );\n\t\t\t\t\t\tif ( file_exists( $copy ) ) {\n\t\t\t\t\t\t\t$url = admin_url( 'admin-ajax.php?page=learn_press_import_export&tab=import-course' );\n\t\t\t\t\t\t\t$postdata = array(\n\t\t\t\t\t\t\t\t'step' => 2,\n\t\t\t\t\t\t\t\t'action' => 'learn_press_import',\n\t\t\t\t\t\t\t\t'import-file' => 'import/' . $file,\n\t\t\t\t\t\t\t\t'nonce' => wp_create_nonce( 'lpie-import-file' ),\n\t\t\t\t\t\t\t\t'x' => 1,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t$response['url'] = $url = $url . '&' . http_build_query( $postdata ) . \"\\n\";\n\t\t\t\t\t\t\t$response['result'] = 'success';\n\t\t\t\t\t\t\t$response['message'] = sprintf( '<p>%s <a href=\"edit.php?post_type=lp_course\">%s</a> </p>', __( 'Successfully import sample data.', 'learnpress' ), __( 'View courses', 'learnpress' ) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif ( $response['result'] == 'fail' ) {\n\t\t\t\t\t\t$response['message'] = sprintf( '<p>%s</p>%s', __( 'Failed to import sample data. Please try again.', 'learnpress' ), $buttons );\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t$response['result'] = 'fail';\n\t\t\t\t\t$response['message'] = sprintf( '<p>%s</p>', __( 'Unknown error when installing/activating Import/Export add-on. Please try again!', 'learnpress' ) ) . $buttons;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlearn_press_send_json( $response );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Activate a bundle of add-ons, if an add-on is not installed then install it first\n\t\t *\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function bundle_activate_add_ons() {\n\t\t\tglobal $learn_press_add_ons;\n\t\t\tinclude_once ABSPATH . 'wp-admin/includes/plugin-install.php'; // for plugins_api..\n\t\t\t$response = array( 'addons' => array() );",
"\t\t\tif ( ! current_user_can( 'activate_plugins' ) ) {\n\t\t\t\t$response['error'] = __( 'You do not have the permission to deactivate plugins on this site.', 'learnpress' );\n\t\t\t} else {",
"\t\t\t\t$add_ons = $learn_press_add_ons['bundle_activate'];",
"\t\t\t\tif ( $add_ons ) {\n\t\t\t\t\tforeach ( $add_ons as $slug ) {\n\t\t\t\t\t\t$response['addons'][ $slug ] = learn_press_install_and_active_add_on( $slug );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlearn_press_send_json( $response );\n\t\t}*/",
"\t\t/**\n\t\t * Activate a bundle of add-ons, if an add-on is not installed then install it first\n\t\t *\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function bundle_activate_add_on() {\n\t\t\t$response = array();\n\t\t\tinclude_once ABSPATH . 'wp-admin/includes/plugin-install.php'; // for plugins_api..\n\t\t\tif ( ! current_user_can( 'activate_plugins' ) ) {\n\t\t\t\t$response['error'] = __( 'You do not have the permission to deactivate plugins on this site.', 'learnpress' );\n\t\t\t} else {\n\t\t\t\t$slug = ! empty( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : null;\n\t\t\t\t$response[ $slug ] = learn_press_install_and_active_add_on( $slug );\n\t\t\t}\n\t\t\tlearn_press_send_json( $response );\n\t\t}*/",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @reason not use\n\t\t * @deprecated 4.0.0.\n\t\t */\n\t\t/*\n\t\tpublic static function plugin_install() {\n\t\t\t$plugin_name = ! empty( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';\n\t\t\t$response = learn_press_install_add_on( $plugin_name );\n\t\t\tlearn_press_send_json( $response );\n\t\t\tdie();\n\t\t}*/",
"\t\t/*\n\t\t * @editor tungnx\n\t\t * @reason not use\n\t\t * @since 3.2.6.8\n\t\t */\n\t\t/*\n\t\tpublic static function update_add_on_status() {\n\t\t\t$plugin = ! empty( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';\n\t\t\t$t = ! empty( $_REQUEST['t'] ) ? $_REQUEST['t'] : '';\n\t\t\t$response = array();\n\t\t\tif ( ! current_user_can( 'activate_plugins' ) ) {\n\t\t\t\t$response['error'] = __( 'You do not have the permission to deactivate plugins on this site.', 'learnpress' );\n\t\t\t}\n\t\t\tif ( $plugin && $t ) {\n\t\t\t\tif ( $t == 'activate' ) {\n\t\t\t\t\tactivate_plugin( $plugin, false, is_network_admin() );\n\t\t\t\t} else {\n\t\t\t\t\tdeactivate_plugins( $plugin, false, is_network_admin() );\n\t\t\t\t}\n\t\t\t\t$is_activate = is_plugin_active( $plugin );\n\t\t\t\t$response['status'] = $is_activate ? 'activate' : 'deactivate';",
"\t\t\t}\n\t\t\twp_send_json( $response );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Output the image to browser with text and params passed via $_GET\n\t\t */\n\t\t/*public static function dummy_image() {\n\t\t\t$text = LP_Helper::sanitize_params_submitted( $_REQUEST['text'] ?? '' );\n\t\t\tlearn_press_text_image( $text, $_GET );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Get edit|view link of a page\n\t\t */\n\t\tpublic static function get_page_permalink() {\n\t\t\t$page_id = (int) $_REQUEST['page_id'] ?? 0;\n\t\t\t?>",
"\t\t\t<a href=\"<?php echo get_edit_post_link( $page_id ); ?>\"\n\t\t\t target=\"_blank\"><?php _e( 'Edit Page', 'learnpress' ); ?></a>\n\t\t\t<a href=\"<?php echo get_permalink( $page_id ); ?>\"\n\t\t\t target=\"_blank\"><?php _e( 'View Page', 'learnpress' ); ?></a>",
"\t\t\t<?php\n\t\t\tdie();\n\t\t}",
"\t\t/**\n\t\t * Get date from, to for static chart\n\t\t */\n\t\tpublic static function custom_stats() {\n\t\t\t$from = LP_Helper::sanitize_params_submitted( $_REQUEST['from'] ?? 0 );\n\t\t\t$to = LP_Helper::sanitize_params_submitted( $_REQUEST['to'] ?? 0 );\n\t\t\t$date_diff = strtotime( $to ) - strtotime( $from );\n\t\t\tif ( $date_diff <= 0 || $from == 0 || $to == 0 ) {\n\t\t\t\tdie();\n\t\t\t}\n\t\t\tlearn_press_process_chart( learn_press_get_chart_students( $to, 'days', floor( $date_diff / ( 60 * 60 * 24 ) ) + 1 ) );\n\t\t\tdie();\n\t\t}",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function ignore_setting_up() {\n\t\t\tupdate_option( '_lpr_ignore_setting_up', 1, true );\n\t\t\tdie;\n\t\t}*/",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function remove_notice_popup() {\n\t\t\tif ( isset( $_POST['action'] ) && $_POST['action'] === 'learnpress_remove_notice_popup' && isset( $_POST['slug'] ) && ! empty( $_POST['slug'] ) && isset( $_POST['user'] ) && ! empty( $_POST['user'] ) ) {\n\t\t\t\t$slug = 'learnpress_notice_' . $_POST['slug'] . '_' . $_POST['user'];\n\t\t\t\tset_transient( $slug, true, 30 * DAY_IN_SECONDS );\n\t\t\t}",
"\t\t\twp_die();\n\t\t}*/",
"\t\t/*\n\t\tpublic static function update_order_status() {",
"\t\t\t$order_id = learn_press_get_request( 'order_id' );\n\t\t\t$value = learn_press_get_request( 'value' );",
"\t\t\t$order = array(\n\t\t\t\t'ID' => $order_id,\n\t\t\t\t'post_status' => $value,\n\t\t\t);",
"\t\t\twp_update_post( $order ) ? $response['success'] = true : $response['success'] = false;",
"\t\t\tlearn_press_send_json( $response );",
"\t\t\tdie();\n\t\t}*/\n",
"",
"\t\tpublic static function upload_user_avatar() {",
"",
"\t\t\t$file = $_FILES['lp-upload-avatar'];\n\t\t\t$upload_dir = learn_press_user_profile_picture_upload_dir();",
"\t\t\tadd_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );",
"",
"\n\t\t\t$result = wp_handle_upload(\n\t\t\t\t$file,\n\t\t\t\tarray(\n\t\t\t\t\t'test_form' => false,\n\t\t\t\t)\n\t\t\t);",
"\t\t\tremove_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );\n\t\t\tif ( is_array( $result ) ) {\n\t\t\t\t$result['name'] = $upload_dir['subdir'] . '/' . basename( $result['file'] );",
"",
"\t\t\t\tunset( $result['file'] );\n\t\t\t} else {\n\t\t\t\t$result = array(\n\t\t\t\t\t'error' => __( 'Profile picture upload failed', 'learnpress' ),\n\t\t\t\t);\n\t\t\t}\n\t\t\tlearn_press_send_json( $result );",
"",
"\t\t}",
"\t\tpublic static function _user_avatar_upload_dir( $dir ) {\n\t\t\t$dir = learn_press_user_profile_picture_upload_dir();",
"\t\t\treturn $dir;\n\t\t}",
"\t\t/**\n\t\t * Export Order invoice to PDF\n\t\t *\n\t\t * @since 3.2.7.8\n\t\t * @author hungkv\n\t\t */\n\t\tpublic static function update_order_exports() {\n\t\t\t$order_id = absint( $_POST['order_id'] );\n\t\t\t//$site_title = LP_Helper::sanitize_params_submitted( $_POST['site_title'] );\n\t\t\t//$order_date = LP_Helper::sanitize_params_submitted( $_POST['order_date'] );\n\t\t\t//$invoice_no = LP_Helper::sanitize_params_submitted( $_POST['invoice_no'] );\n\t\t\t//$order_customer = LP_Helper::sanitize_params_submitted( $_POST['order_customer'] );\n\t\t\t//$order_email = LP_Helper::sanitize_params_submitted( $_POST['order_email'] );\n\t\t\t//$order_payment = LP_Helper::sanitize_params_submitted( $_POST['order_payment'] );\n\t\t\t$order = learn_press_get_order( $order_id );\n\t\t\t$currency_symbol = learn_press_get_currency_symbol( $order->get_currency() );",
"\t\t\tob_start();\n\t\t\tlearn_press_admin_view(\n\t\t\t\t'meta-boxes/order/content-tab-preview-exports-invoice.php',\n\t\t\t\tarray(\n\t\t\t\t\t'order' => $order,\n\t\t\t\t\t'currency_symbol' => $currency_symbol,\n\t\t\t\t)\n\t\t\t);\n\t\t\t$html = ob_get_clean();\n\t\t\techo $html;\n\t\t\tdie();\n\t\t}\n\t}",
"\tif ( defined( 'DOING_AJAX' ) ) {\n\t\tadd_action( 'wp_ajax_learnpress_upload-user-avatar', array( 'LP_Admin_Ajax', 'upload_user_avatar' ) );",
"",
"\t}",
"\tadd_action( 'init', array( 'LP_Admin_Ajax', 'init' ) );\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
0,
1,
1,
0,
1,
1,
0,
1,
0,
1,
1,
1,
1,
1,
1,
0,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [61, 1262, 233, 1156], "buggy_code_start_loc": [27, 1198, 14, 1081], "filenames": ["assets/src/js/frontend/profile.js", "inc/admin/class-lp-admin-ajax.php", "inc/class-lp-ajax.php", "inc/user/lp-user-functions.php"], "fixing_code_end_loc": [71, 1364, 200, 1152], "fixing_code_start_loc": [27, 1199, 14, 1082], "message": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thimpress:learnpress:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "F74AC61D-6728-4759-B5A4-F03B9519485C", "versionEndExcluding": "4.1.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site."}, {"lang": "es", "value": "Los usuarios del plugin LearnPress de WordPress versiones anteriores a 4.1.5, pueden subir una imagen como avatar de perfil tras el registro. Tras este proceso, el usuario recorta y guarda la imagen. A continuaci\u00f3n, se env\u00eda al servidor una petici\u00f3n \"POST\" que contiene el nombre de la imagen suministrado por el usuario para cambiar el nombre y recortar la imagen. Como resultado de esta petici\u00f3n, el nombre de la imagen suministrada por el usuario es cambiada con un valor MD5. Este proceso s\u00f3lo puede llevarse a cabo cuando el tipo de la imagen es JPG o PNG. Un atacante puede usar esta vulnerabilidad para cambiar el nombre de un archivo de imagen arbitrario. Al hacer esto, podr\u00edan destruir el dise\u00f1o del sitio web."}], "evaluatorComment": null, "id": "CVE-2022-0377", "lastModified": "2022-03-08T16:39:46.640", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-28T09:15:09.093", "references": [{"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://bozogullarindan.com/en/2022/01/wordpress-learnpress-plugin-4.1.4.1-arbitrary-image-renaming/"}, {"source": "contact@wpscan.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, {"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://wpscan.com/vulnerability/0d95ada6-53e3-4a80-a395-eacd7b090f26"}], "sourceIdentifier": "contact@wpscan.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-610"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-73"}], "source": "contact@wpscan.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, "type": "CWE-610"}
| 263
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"/**\n * Class LP_Admin_Ajax\n *\n * @author ThimPress\n * @package LearnPress/Classes\n * @version 3.0.0\n */",
"/**\n * Prevent loading this file directly\n */\ndefined( 'ABSPATH' ) || exit();",
"if ( ! class_exists( 'LP_Admin_Ajax' ) ) {",
"\t/**\n\t * Class LP_Admin_Ajax\n\t */\n\tclass LP_Admin_Ajax {",
"\t\t/**\n\t\t * Add action ajax\n\t\t */\n\t\tpublic static function init() {",
"\t\t\tif ( ! is_user_logged_in() ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\t$ajax_events = array(\n\t\t\t\t'create_page' => false, // Use create new page on Settings\n\t\t\t\t// 'plugin_action' => false,\n\t\t\t\t// 'modal_search_items' => false,\n\t\t\t\t//'dismiss_notice' => false,\n\t\t\t\t//'search_users' => false,\n\t\t\t\t'load_chart' => false,\n\t\t\t\t'search_course_category' => false,\n\t\t\t\t'custom_stats' => false,\n\t\t\t\t//'ignore_setting_up' => false,\n\t\t\t\t'get_page_permalink' => false,\n\t\t\t\t//'dummy_image' => false,\n\t\t\t\t// 'update_add_on_status' => false,\n\t\t\t\t// 'plugin_install' => false,\n\t\t\t\t//'bundle_activate_add_ons' => false,\n\t\t\t\t//'install_sample_data' => false,",
"\t\t\t\t// Remove Notice\n\t\t\t\t//'remove_notice_popup' => false,\n\t\t\t\t// Update order status\n\t\t\t\t// 'update_order_status' => false,\n\t\t\t\t'update_order_exports' => false,\n\t\t\t);",
"\t\t\tforeach ( $ajax_events as $ajax_event => $nopriv ) {\n\t\t\t\tadd_action( 'wp_ajax_learnpress_' . $ajax_event, array( __CLASS__, $ajax_event ) );",
"\t\t\t\t// enable for non-logged in users\n\t\t\t\tif ( $nopriv ) {\n\t\t\t\t\tadd_action( 'wp_ajax_nopriv_learnpress_' . $ajax_event, array( __CLASS__, $ajax_event ) );\n\t\t\t\t}\n\t\t\t}",
"\t\t\tdo_action( 'learn-press/ajax/admin-load', __CLASS__ );",
"\t\t\t$ajax_events = array(\n\t\t\t\t'search_items' => 'modal_search_items',\n\t\t\t\t'update-payment-order', // Update ordering of payments when user changing.\n\t\t\t\t'update-payment-status', // Enable type payment\n\t\t\t\t//'toggle_item_preview',",
"\t\t\t\t// admin editor\n\t\t\t\t'admin_course_editor',\n\t\t\t\t'admin_quiz_editor',\n\t\t\t\t'admin_question_editor',\n\t\t\t\t// duplicator\n\t\t\t\t'duplicator', // Duplicate course, lesson, quiz, question.",
"\t\t\t\t//'add_item_to_order',\n\t\t\t\t//'remove_order_item',",
"\t\t\t\t'modal_search_items', // Used to search courses on LP Order\n\t\t\t\t'modal_search_users', // Used to search users on LP Order\n\t\t\t\t'add_items_to_order', // Used to add courses on LP Order\n\t\t\t\t'remove_items_from_order', // Used to remove items from LP Order\n\t\t\t\t'update_email_status', // Use for enable email on LP Settings\n\t\t\t\t//'create-pages',\n\t\t\t\t'search-authors', // Used to search username on input some page (list courses, lp orders, quizzes, questions... on the Backend\n\t\t\t\t'skip-notice-install',\n\t\t\t\t//'join_newsletter',\n\t\t\t\t//'dashboard-order-status',\n\t\t\t\t//'dashboard-plugin-status',\n\t\t\t\t//'dismiss-notice',\n\t\t\t\t//'sync-user-orders',\n\t\t\t\t//'sync-course-final-quiz',\n\t\t\t\t//'sync-remove-older-data',\n\t\t\t\t//'sync-calculate-course-results',\n\t\t\t\t//'create-question-type',\n\t\t\t\t// 'sync-user-courses',\n\t\t\t);",
"\t\t\tforeach ( $ajax_events as $action => $callback ) {\n\t\t\t\tif ( is_numeric( $action ) ) {\n\t\t\t\t\t$action = $callback;\n\t\t\t\t}",
"\t\t\t\t$actions = LP_Request::parse_action( $action );\n\t\t\t\t$method = $actions['action'];",
"\t\t\t\tif ( ! is_callable( $callback ) ) {\n\t\t\t\t\t$method = preg_replace( '/-/', '_', $method );\n\t\t\t\t\t$callback = array( __CLASS__, $method );\n\t\t\t\t}",
"\t\t\t\tLP_Request::register_ajax( $action, $callback );\n\t\t\t}\n\t\t}",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function sync_calculate_course_results() {\n\t\t\tif ( ! isset( $_REQUEST['sync'] ) ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\t$sync = LP_Helper::sanitize_params_submitted( $_REQUEST['sync'] );",
"\t\t\tif ( empty( $sync ) ) {\n\t\t\t\tdie();\n\t\t\t}",
"\t\t\tglobal $wpdb;\n\t\t\t$api = LP_Repair_Database::instance();",
"\t\t\tif ( $sync === 'get-users' ) {\n\t\t\t\t$query = $wpdb->prepare(\n\t\t\t\t\t\"\n\t\t\t\t\tSELECT ID\n\t\t\t\t\tFROM {$wpdb->users}\n\t\t\t\t\tWHERE 1\n\t\t\t\t\",\n\t\t\t\t\t1\n\t\t\t\t);",
"\t\t\t\t$users = $wpdb->get_col( $query );",
"\t\t\t\tlearn_press_send_json( array( 'users' => $users ) );\n\t\t\t}",
"\t\t\t$api->calculate_course_results( $sync );\n\t\t\tlearn_press_send_json( array( 'result' => 'success' ) );",
"\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Sync orders for each course\n\t\t *\n\t\t * @since 3.1.0\n\t\t * @editor tungnx\n\t\t * @modify 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function sync_course_orders() {\n\t\t\tif ( empty( $_REQUEST['sync'] ) ) {\n\t\t\t\tdie();\n\t\t\t}",
"\t\t\tglobal $wpdb;\n\t\t\t$api = LP_Repair_Database::instance();\n\t\t\t$sync = $_REQUEST['sync'];",
"\t\t\tif ( $sync === 'get-courses' ) {\n\t\t\t\tlearn_press_send_json( array( 'courses' => $api->get_all_courses() ) );\n\t\t\t}",
"\t\t\t$api->sync_course_orders( $sync );\n\t\t\tlearn_press_send_json( array( 'result' => 'success' ) );",
"\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Sync orders for each user\n\t\t *\n\t\t * @since 3.1.0\n\t\t * @editor tungnx\n\t\t * @modify 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function sync_user_orders() {\n\t\t\tif ( empty( $_REQUEST['sync'] ) ) {\n\t\t\t\tdie();\n\t\t\t}",
"\t\t\tglobal $wpdb;\n\t\t\t$api = LP_Repair_Database::instance();\n\t\t\t$sync = $_REQUEST['sync'];",
"\t\t\tif ( $sync === 'get-users' ) {\n\t\t\t\t$query = $wpdb->prepare(\n\t\t\t\t\t\"\n\t\t\t\t\tSELECT ID\n\t\t\t\t\tFROM {$wpdb->users}\n\t\t\t\t\tWHERE 1\n\t\t\t\t\",\n\t\t\t\t\t1\n\t\t\t\t);",
"\t\t\t\t$users = $wpdb->get_col( $query );",
"\t\t\t\tlearn_press_send_json( array( 'users' => $users ) );\n\t\t\t}",
"\t\t\t$api->sync_user_orders( $sync );\n\t\t\tlearn_press_send_json( array( 'result' => 'success' ) );",
"\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Remap final quiz for each course\n\t\t *\n\t\t * @since 3.1.0\n\t\t */\n\t\tpublic static function sync_course_final_quiz() {\n\t\t\tif ( empty( $_REQUEST['sync'] ) ) {\n\t\t\t\tdie();\n\t\t\t}",
"\t\t\tglobal $wpdb;\n\t\t\t$api = LP_Repair_Database::instance();\n\t\t\t$sync = $_REQUEST['sync'];",
"\t\t\tif ( $sync === 'get-courses' ) {\n\t\t\t\tlearn_press_send_json( array( 'courses' => $api->get_all_courses() ) );\n\t\t\t}",
"\t\t\t$api->sync_course_final_quiz( $sync );\n\t\t\tlearn_press_send_json( array( 'result' => 'success' ) );",
"\t\t\tdie();\n\t\t}",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @comment 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function sync_remove_older_data() {\n\t\t\t$api = LP_Repair_Database::instance();\n\t\t\t$api->remove_older_post_meta();\n\t\t\tlearn_press_send_json( array( 'result' => 'success' ) );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Get html of order status to display in WP Dashboad\n\t\t * @editor tungnx\n\t\t * @modify 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function dashboard_order_status() {\n\t\t\tlearn_press_admin_view( 'dashboard/order-status' );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @modify 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function dashboard_plugin_status() {\n\t\t\t$dashboard = new LP_Admin_Dashboard();\n\t\t\t$plugin_data = $dashboard->get_data();\n\t\t\tif ( ! $plugin_data || is_wp_error( $plugin_data ) ) {\n\t\t\t\tlearn_press_admin_view( 'dashboard/plugin-status/html-no-data' );\n\t\t\t} else {\n\t\t\t\tlearn_press_admin_view( 'dashboard/plugin-status/html-results', array( 'plugin_data' => $plugin_data ) );\n\t\t\t}\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Search user on some pages on the Backend\n\t\t */\n\t\tpublic static function search_authors() {\n\t\t\t$args = array(\n\t\t\t\t'orderby' => 'name',\n\t\t\t\t'order' => 'ASC',\n\t\t\t\t'search' => sprintf( '*%s*', esc_attr( LP_Request::get_string( 'term' ) ) ),\n\t\t\t\t'search_columns' => array( 'user_login', 'user_email' ),\n\t\t\t);\n\t\t\t$q = new WP_User_Query( $args );\n\t\t\t$users = array();",
"\t\t\t$results = $q->get_results();",
"\t\t\tif ( $results ) {\n\t\t\t\tforeach ( $results as $result ) {\n\t\t\t\t\t$users[] = array(\n\t\t\t\t\t\t'id' => $result->ID,\n\t\t\t\t\t\t'text' => learn_press_get_profile_display_name( $result->ID ),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\techo json_encode(\n\t\t\t\tarray(\n\t\t\t\t\t'results' => $users,\n\t\t\t\t)\n\t\t\t);\n\t\t\tdie();\n\t\t}",
"\t\t/**\n\t\t * Hide notice install\n\t\t */\n\t\tpublic static function skip_notice_install() {\n\t\t\tdelete_option( 'learn_press_install' );\n\t\t}",
"\t\t/**\n\t\t * Handle ajax admin course editor.\n\t\t *\n\t\t * @since 3.0.0\n\t\t */\n\t\tpublic static function admin_course_editor() {\n\t\t\t$editor = LP_Admin_Editor::get_editor_course();\n\t\t\tself::admin_editor( $editor );\n\t\t}",
"\t\t/**\n\t\t * Handle ajax admin question editor.\n\t\t *\n\t\t * @since 3.0.0\n\t\t */\n\t\tpublic static function admin_question_editor() {\n\t\t\t$editor = LP_Admin_Editor::get_editor_question();\n\t\t\tself::admin_editor( $editor );\n\t\t}",
"\t\t/**\n\t\t * Handle ajax admin quiz editor.\n\t\t *\n\t\t * @since 3.0.0\n\t\t */\n\t\tpublic static function admin_quiz_editor() {\n\t\t\t$editor = LP_Admin_Editor::get_editor_quiz();\n\t\t\tself::admin_editor( $editor );\n\t\t}",
"\t\t/**\n\t\t * @param LP_Admin_Editor $editor\n\t\t *\n\t\t * @since 3.0.2\n\t\t */\n\t\tpublic static function admin_editor( &$editor ) {\n\t\t\t$result = $editor->dispatch();",
"\t\t\tif ( is_wp_error( $result ) ) {\n\t\t\t\tlearn_press_send_json_error( $result->get_error_message() );\n\t\t\t} elseif ( ! $result ) {\n\t\t\t\tlearn_press_send_json_error();\n\t\t\t}",
"\t\t\tlearn_press_send_json_success( $result );\n\t\t}",
"\t\t/**\n\t\t * Send data to join newsletter or dismiss.\n\t\t *\n\t\t * [\n\t\t * This function has deprecated since 3.2.6 from this class.\n\t\t * Please check class LP_Admin and hook learn-press/dismissed-notice-response for more details.\n\t\t * Newsletter function be hooked to the hook above to send subscription when\n\t\t * notice has already dismissed.\n\t\t * ]\n\t\t *\n\t\t * @deprecated\n\t\t *\n\t\t * @since 3.0.10\n\t\t * @editable tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function join_newsletter() {\n\t\t\t$context = LP_Request::get_string( 'context' );\n\t\t\tif ( ! $context || $context != 'newsletter' ) {\n\t\t\t\tupdate_option( 'learn-press-dismissed-newsletter-button', 1 );\n\t\t\t\tlearn_press_send_json_success( __( 'Dismissed!', 'learnpress' ) );\n\t\t\t}\n\t\t\t$user = learn_press_get_current_user();\n\t\t\tif ( ! $user || $user->get_email() == '' ) {\n\t\t\t\tlearn_press_send_json_error( __( 'Fail while joining newsletter! Please try again!', 'learnpress' ) );\n\t\t\t}\n\t\t\t$url = 'https://thimpress.com/mailster/subscribe';\n\t\t\t$response = wp_remote_post(\n\t\t\t\t$url,\n\t\t\t\tarray(\n\t\t\t\t\t'method' => 'POST',\n\t\t\t\t\t'timeout' => 45,\n\t\t\t\t\t'redirection' => 5,\n\t\t\t\t\t'httpversion' => '1.0',\n\t\t\t\t\t'blocking' => true,\n\t\t\t\t\t'headers' => array(),\n\t\t\t\t\t'body' => array(\n\t\t\t\t\t\t'_referer' => 'extern',\n\t\t\t\t\t\t'_nonce' => '4b266caf7b',\n\t\t\t\t\t\t'formid' => '19',\n\t\t\t\t\t\t'email' => $user->get_email(),\n\t\t\t\t\t\t'website' => site_url(),\n\t\t\t\t\t),\n\t\t\t\t\t'cookies' => array(),\n\t\t\t\t)\n\t\t\t);\n\t\t\tif ( is_wp_error( $response ) ) {\n\t\t\t\t$error_message = $response->get_error_message();\n\t\t\t\tlearn_press_send_json_error( __( 'Something went wrong: ', 'learnpress' ) . $error_message );\n\t\t\t} else {\n\t\t\t\tupdate_option( 'learn-press-dismissed-newsletter-button', 1 );\n\t\t\t\tlearn_press_send_json_success( __( 'Thank you for subscribing! Please check and click the confirmation link from the email we\\'ve just sent to your mail box.', 'learnpress' ) );\n\t\t\t}\n\t\t}*/",
"\t\t/**\n\t\t * Duplicate course, lesson, quiz, question.\n\t\t *\n\t\t * @since 3.0.0\n\t\t *\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function duplicator() {\n\t\t\t$post_id = intval( $_GET['id'] ?? 0 );",
"\t\t\t// get post type\n\t\t\t$post_type = learn_press_get_post_type( $post_id );",
"\t\t\tif ( ! $post_id ) {\n\t\t\t\tlearn_press_send_json_error( __( 'Ops! ID not found', 'learnpress' ) );\n\t\t\t} else {",
"\t\t\t\t$new_item_id = '';",
"\t\t\t\t$duplicate_args = apply_filters( 'learn-press/duplicate-post-args', array( 'post_status' => 'publish' ) );",
"\t\t\t\tswitch ( $post_type ) {\n\t\t\t\t\tcase LP_COURSE_CPT:\n\t\t\t\t\t\t$curd = new LP_Course_CURD();\n\t\t\t\t\t\t$new_item_id = $curd->duplicate(\n\t\t\t\t\t\t\t$post_id,\n\t\t\t\t\t\t\tarray(\n\t\t\t\t\t\t\t\t'exclude_meta' => array(\n\t\t\t\t\t\t\t\t\t'order-pending',\n\t\t\t\t\t\t\t\t\t'order-processing',\n\t\t\t\t\t\t\t\t\t'order-completed',\n\t\t\t\t\t\t\t\t\t'order-cancelled',\n\t\t\t\t\t\t\t\t\t'order-failed',\n\t\t\t\t\t\t\t\t\t'count_enrolled_users',\n\t\t\t\t\t\t\t\t\t'_lp_sample_data',\n\t\t\t\t\t\t\t\t\t'_lp_retake_count',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LP_LESSON_CPT:\n\t\t\t\t\t\t$curd = new LP_Lesson_CURD();\n\t\t\t\t\t\t$new_item_id = $curd->duplicate( $post_id, $duplicate_args );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LP_QUIZ_CPT:\n\t\t\t\t\t\t$curd = new LP_Quiz_CURD();\n\t\t\t\t\t\t$new_item_id = $curd->duplicate( $post_id, $duplicate_args );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LP_QUESTION_CPT:\n\t\t\t\t\t\t$curd = new LP_Question_CURD();\n\t\t\t\t\t\t$new_item_id = $curd->duplicate( $post_id, $duplicate_args );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}",
"\t\t\t\tif ( is_wp_error( $new_item_id ) ) {\n\t\t\t\t\tlearn_press_send_json_error( __( 'Duplicate post fail, please try again', 'learnpress' ) );\n\t\t\t\t} else {\n\t\t\t\t\tlearn_press_send_json_success( admin_url( 'post.php?post=' . $new_item_id . '&action=edit' ) );\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\t/**\n\t\t * Update ordering of payments when user changing.\n\t\t *\n\t\t * @since 3.0.0\n\t\t * @use for sorting by type payment gateway\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function update_payment_order() {\n\t\t\t$payment_order = learn_press_get_request( 'order' );\n\t\t\tupdate_option( 'learn_press_payment_order', $payment_order );\n\t\t}",
"\t\t/**\n\t\t * Enable type payment\n\t\t *\n\t\t * @since 3.0.0\n\t\t * @use for enable type payment gateway\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function update_payment_status() {\n\t\t\t$payment_id = learn_press_get_request( 'id' );\n\t\t\t$status = LP_Request::get_string( 'status' );\n\t\t\t$payment = LP_Gateways::instance()->get_gateway( $payment_id );",
"\t\t\tif ( ! $payment ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\t$response[ $payment->id ] = $payment->enable( $status == 'yes' );",
"\t\t\tlearn_press_send_json( $response );\n\t\t}",
"\t\t/**\n\t\t * nable email on LP Settings\n\t\t *\n\t\t * @since 3.0.0\n\t\t * @note tungnnx checked has use\n\t\t */\n\t\tpublic static function update_email_status() {",
"\t\t\t$email_id = LP_Request::get_string( 'id' );\n\t\t\t$status = LP_Request::get_string( 'status' );\n\t\t\t$response = array();",
"\t\t\tif ( $email_id ) {",
"\t\t\t\t$email = LP_Emails::get_email( $email_id );\n\t\t\t\tif ( ! $email ) {\n\t\t\t\t\treturn;\n\t\t\t\t}",
"\t\t\t\t$response[ $email->id ] = $email->enable( $status == 'yes' );\n\t\t\t} else {\n\t\t\t\t$emails = LP_Emails::instance()->emails;\n\t\t\t\tforeach ( $emails as $email ) {\n\t\t\t\t\t$response[ $email->id ] = $email->enable( $status == 'yes' );\n\t\t\t\t}\n\t\t\t}\n\t\t\tlearn_press_send_json( $response );\n\t\t}",
"\t\t/**\n\t\t * Toggle lesson preview.\n\t\t */\n\t\t/*public static function toggle_item_preview() {\n\t\t\t$id = learn_press_get_request( 'item_id' );\n\t\t\tif ( in_array(\n\t\t\t\tget_post_type( $id ),\n\t\t\t\tapply_filters(\n\t\t\t\t\t'learn-press/reviewable-post-types',\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'lp_lesson',\n\t\t\t\t\t\t'lp_quiz',\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t) && wp_verify_nonce( learn_press_get_request( 'nonce' ), 'learn-press-toggle-item-preview' )\n\t\t\t) {\n\t\t\t\t$previewable = learn_press_get_request( 'previewable' );\n\t\t\t\tif ( is_null( $previewable ) ) {\n\t\t\t\t\t$previewable = '0';\n\t\t\t\t}\n\t\t\t\tupdate_post_meta( $id, '_lp_preview', $previewable );\n\t\t\t}\n\t\t}*/",
"\t\t/**\n\t\t * Search items by requesting params.\n\t\t */\n\t\tpublic static function modal_search_items() {\n\t\t\t$term = LP_Helper::sanitize_params_submitted( $_POST['term'] ?? '' );\n\t\t\t$type = LP_Helper::sanitize_params_submitted( $_POST['type'] ?? '' );\n\t\t\t$context = LP_Helper::sanitize_params_submitted( $_POST['context'] ?? '' );\n\t\t\t$context_id = LP_Helper::sanitize_params_submitted( $_POST['context_id'] ?? '' );\n\t\t\t$paged = LP_Helper::sanitize_params_submitted( $_POST['paged'] ?? '' );\n\t\t\t$exclude = LP_Request::get( 'exclude' );",
"\t\t\t$search = new LP_Modal_Search_Items( compact( 'term', 'type', 'context', 'context_id', 'paged', 'exclude' ) );",
"\t\t\tlearn_press_send_json(\n\t\t\t\tarray(\n\t\t\t\t\t'html' => $search->get_html_items(),\n\t\t\t\t\t'nav' => $search->get_pagination(),\n\t\t\t\t\t'items' => $search->get_items(),\n\t\t\t\t)\n\t\t\t);\n\t\t}",
"\t\t/**\n\t\t * Search items by requesting params.\n\t\t *\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function modal_search_users() {\n\t\t\t$term = LP_Helper::sanitize_params_submitted( $_POST['term'] ?? '' );\n\t\t\t$type = LP_Helper::sanitize_params_submitted( $_POST['type'] ?? '' );\n\t\t\t$context = LP_Helper::sanitize_params_submitted( $_POST['context'] ?? '' );\n\t\t\t$context_id = LP_Helper::sanitize_params_submitted( $_POST['context_id'] ?? '' );\n\t\t\t$paged = LP_Helper::sanitize_params_submitted( $_POST['paged'] ?? '' );\n\t\t\t$multiple = LP_Helper::sanitize_params_submitted( $_POST['multiple'] ?? '' ) == 'yes';\n\t\t\t$text_format = LP_Helper::sanitize_params_submitted( $_POST['text_format'] ?? '' );\n\t\t\t$exclude = LP_Request::get( 'exclude' );",
"\t\t\t$search = new LP_Modal_Search_Users( compact( 'term', 'type', 'context', 'context_id', 'paged', 'multiple', 'text_format', 'exclude' ) );",
"\t\t\tlearn_press_send_json(\n\t\t\t\tarray(\n\t\t\t\t\t'html' => $search->get_html_items(),\n\t\t\t\t\t'nav' => $search->get_pagination(),\n\t\t\t\t\t'users' => $search->get_items(),\n\t\t\t\t)\n\t\t\t);\n\t\t}",
"\t\t/**\n\t\t * Search course category.\n\t\t */\n\t\tpublic static function search_course_category() {\n\t\t\tglobal $wpdb;\n\t\t\t$sql = 'SELECT `t`.`term_id` as `id`, '\n\t\t\t\t\t . ' `t`.`name` `text` '\n\t\t\t\t\t . \" FROM {$wpdb->terms} t \"\n\t\t\t\t\t . \"\t\tINNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id AND taxonomy='course_category' \"\n\t\t\t\t\t . ' WHERE `t`.`name` LIKE %s';\n\t\t\t$s = '%' . filter_input( INPUT_GET, 'q' ) . '%';\n\t\t\t$query = $wpdb->prepare( $sql, $s );\n\t\t\t$items = $wpdb->get_results( $query );\n\t\t\t$data = array( 'items' => $items );\n\t\t\techo json_encode( $data );\n\t\t\texit();\n\t\t}",
"\t\t/**\n\t\t * Remove an item from lp order\n\t\t *\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function remove_items_from_order() {\n\t\t\t// ensure that user has permission\n\t\t\tif ( ! current_user_can( 'edit_lp_orders' ) ) {\n\t\t\t\tdie( __( 'Access denied', 'learnpress' ) );\n\t\t\t}",
"\t\t\t// verify nonce\n\t\t\t$nonce = learn_press_get_request( 'remove_nonce' );\n\t\t\tif ( ! wp_verify_nonce( $nonce, 'remove_order_item' ) ) {\n\t\t\t\tdie( __( 'Check nonce failed', 'learnpress' ) );\n\t\t\t}",
"\t\t\t// validate order\n\t\t\t$order_id = learn_press_get_request( 'order_id' );\n\t\t\tif ( ! is_numeric( $order_id ) || learn_press_get_post_type( $order_id ) != 'lp_order' ) {\n\t\t\t\tdie( __( 'Invalid order', 'learnpress' ) );\n\t\t\t}",
"\t\t\t// validate item\n\t\t\t$items = learn_press_get_request( 'items' );",
"\t\t\t$order = learn_press_get_order( $order_id );",
"\t\t\tglobal $wpdb;",
"\t\t\tforeach ( $items as $item_id ) {\n\t\t\t\t$order->remove_item( $item_id );\n\t\t\t}",
"\t\t\t$order_data = learn_press_update_order_items( $order_id );\n\t\t\t$currency_symbol = learn_press_get_currency_symbol( $order_data['currency'] );\n\t\t\t$order_data['subtotal_html'] = learn_press_format_price( $order_data['subtotal'], $currency_symbol );\n\t\t\t$order_data['total_html'] = learn_press_format_price( $order_data['total'], $currency_symbol );\n\t\t\t$order_items = $order->get_items();\n\t\t\tif ( $order_items ) {\n\t\t\t\t$html = '';\n\t\t\t\tforeach ( $order_items as $item ) {\n\t\t\t\t\tob_start();\n\t\t\t\t\tinclude learn_press_get_admin_view( 'meta-boxes/order/order-item.php' );\n\t\t\t\t\t$html .= ob_get_clean();\n\t\t\t\t}\n\t\t\t}",
"\t\t\tlearn_press_send_json(\n\t\t\t\tarray(\n\t\t\t\t\t'result' => 'success',\n\t\t\t\t\t'item_html' => $html,\n\t\t\t\t\t'order_data' => $order_data,\n\t\t\t\t)\n\t\t\t);\n\t\t}",
"\t\t/**\n\t\t * Add courses to order\n\t\t *\n\t\t * @note tungnx checked has use\n\t\t */\n\t\tpublic static function add_items_to_order() {\n\t\t\t// ensure that user has permission\n\t\t\tif ( ! current_user_can( 'edit_lp_orders' ) ) {\n\t\t\t\tdie( __( 'Permission denied', 'learnpress' ) );\n\t\t\t}",
"\t\t\t// validate order\n\t\t\t$order_id = learn_press_get_request( 'order_id' );\n\t\t\tif ( ! is_numeric( $order_id ) || learn_press_get_post_type( $order_id ) != 'lp_order' ) {\n\t\t\t\tdie( __( 'Invalid order', 'learnpress' ) );\n\t\t\t}",
"\t\t\t// validate item\n\t\t\t$item_ids = learn_press_get_request( 'items' );\n\t\t\t$order = learn_press_get_order( $order_id );",
"\t\t\t$response = array(\n\t\t\t\t'result' => 'error',\n\t\t\t);",
"\t\t\t$order_item_ids = $order->add_items( $item_ids );",
"\t\t\tif ( $order_item_ids ) {\n\t\t\t\t$html = '';\n\t\t\t\t$order_items = $order->get_items();",
"\t\t\t\t$order_data = learn_press_update_order_items( $order_id );\n\t\t\t\t$currency_symbol = learn_press_get_currency_symbol( $order_data['currency'] );\n\t\t\t\t$order_data['subtotal_html'] = learn_press_format_price( $order_data['subtotal'], $currency_symbol );\n\t\t\t\t$order_data['total_html'] = learn_press_format_price( $order_data['total'], $currency_symbol );",
"\t\t\t\tif ( $order_items ) {\n\t\t\t\t\tforeach ( $order_items as $item ) {",
"\t\t\t\t\t\tif ( ! in_array( $item['id'], $order_item_ids ) ) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}",
"\t\t\t\t\t\tob_start();\n\t\t\t\t\t\tinclude learn_press_get_admin_view( 'meta-boxes/order/order-item.php' );\n\t\t\t\t\t\t$html .= ob_get_clean();\n\t\t\t\t\t}\n\t\t\t\t}",
"\t\t\t\t$response = array(\n\t\t\t\t\t'result' => 'success',\n\t\t\t\t\t'item_html' => $html,\n\t\t\t\t\t'order_data' => $order_data,\n\t\t\t\t);\n\t\t\t}",
"\t\t\tlearn_press_send_json( $response );\n\t\t}",
"\t\t/**\n\t\t * Get content send via payload and parse to json.\n\t\t *\n\t\t * @param mixed $params (Optional) List of keys want to get from payload.\n\t\t *\n\t\t * @return array|bool|mixed|object\n\t\t */\n\t\tpublic static function get_php_input( $params = '' ) {\n\t\t\tstatic $data = false;\n\t\t\tif ( false === $data ) {\n\t\t\t\ttry {\n\t\t\t\t\t$data = json_decode( file_get_contents( 'php://input' ), true );\n\t\t\t\t} catch ( Exception $exception ) {\n\t\t\t\t}\n\t\t\t}",
"\t\t\tif ( $data && func_num_args() > 0 ) {\n\t\t\t\t$params = is_array( func_get_arg( 0 ) ) ? func_get_arg( 0 ) : func_get_args();\n\t\t\t\tif ( $params ) {\n\t\t\t\t\t$request = array();\n\t\t\t\t\tforeach ( $params as $key ) {\n\t\t\t\t\t\t$request[] = array_key_exists( $key, $data ) ? $data[ $key ] : false;\n\t\t\t\t\t}",
"\t\t\t\t\treturn $request;\n\t\t\t\t}\n\t\t\t}",
"\t\t\treturn $data;\n\t\t}",
"\t\t/**\n\t\t * Parse request content into var.\n\t\t * Normally, parse and assign to $_POST or $_GET.\n\t\t *\n\t\t * @param $var\n\t\t */\n\t\tpublic static function parsePhpInput( &$var ) {\n\t\t\t$data = self::get_php_input();",
"\t\t\tif ( $data ) {\n\t\t\t\tforeach ( $data as $k => $v ) {\n\t\t\t\t\t$var[ $k ] = $v;\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\tpublic static function load_chart() {\n\t\t\tif ( ! class_exists( 'LP_Submenu_Statistics' ) ) {\n\t\t\t\t$statistic = include_once LP_PLUGIN_PATH . '/inc/admin/sub-menus/class-lp-submenu-statistics.php';\n\t\t\t} else {\n\t\t\t\t$statistic = new LP_Submenu_Statistics();\n\t\t\t}\n\t\t\t$statistic->load_chart();\n\t\t}",
"\t\t/**\n\t\t * @param $query\n\t\t *\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function search_users() {\n\t\t\tif ( ! current_user_can( 'edit_lp_orders' ) ) {\n\t\t\t\tdie( - 1 );\n\t\t\t}",
"\t\t\t$term = LP_Helper::sanitize_params_submitted( $_REQUEST['term'] );",
"\t\t\tif ( empty( $term ) ) {\n\t\t\t\tdie( __FILE__ . '::' . __FUNCTION__ );",
"\t\t\t}",
"\t\t\t$found_customers = array();",
"\t\t\tadd_action( 'pre_user_query', array( __CLASS__, 'json_search_customer_name' ) );",
"\t\t\t$customers_query = new WP_User_Query(\n\t\t\t\tapply_filters(\n\t\t\t\t\t'learn_press_search_customers_query',\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'fields' => 'all',\n\t\t\t\t\t\t'orderby' => 'display_name',\n\t\t\t\t\t\t'search' => '*' . $term . '*',\n\t\t\t\t\t\t'search_columns' => array( 'ID', 'user_login', 'user_email', 'user_nicename' ),\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t);",
"\t\t\tremove_action( 'pre_user_query', array( __CLASS__, 'json_search_customer_name' ) );",
"\t\t\t$customers = $customers_query->get_results();",
"\t\t\tif ( ! empty( $customers ) ) {\n\t\t\t\tforeach ( $customers as $customer ) {\n\t\t\t\t\t$found_customers[] = array(\n\t\t\t\t\t\t'label' => $customer->display_name . ' (#' . $customer->ID . ' – ' . sanitize_email( $customer->user_email ) . ')',\n\t\t\t\t\t\t'value' => $customer->ID,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}",
"\t\t\techo json_encode( $found_customers );\n\t\t\tdie();\n\t\t}*/",
"\t\tpublic static function json_search_customer_name( $query ) {\n\t\t\tglobal $wpdb;",
"\t\t\t$term = LP_Helper::sanitize_params_submitted( $_REQUEST['term'] );\n\t\t\tif ( method_exists( $wpdb, 'esc_like' ) ) {\n\t\t\t\t$term = $wpdb->esc_like( $term );\n\t\t\t} else {\n\t\t\t\t$term = like_escape( $term );\n\t\t\t}",
"\t\t\t$query->query_from .= \" INNER JOIN {$wpdb->usermeta} AS user_name ON {$wpdb->users}.ID = user_name.user_id AND ( user_name.meta_key = 'first_name' OR user_name.meta_key = 'last_name' ) \";\n\t\t\t$query->query_where .= $wpdb->prepare( ' OR user_name.meta_value LIKE %s ', '%' . $term . '%' );\n\t\t}",
"\t\t/**\n\t\t * Dismiss notice\n\t\t *\n\t\t * @update 3.2.6\n\t\t * @editor tungnx\n\t\t * @comment 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function dismiss_notice() {\n\t\t\t$name = learn_press_get_request( 'name' );\n\t\t\t$value = learn_press_get_request( 'value' );\n\t\t\t$expired = learn_press_get_request( 'expired' );",
"\t\t\t// LP_Admin_Notice::instance()->dismiss_notice_2( $name, $value, $expired );",
"\t\t\tdie();\n\t\t}*/",
"\t\t/*\n\t\t * comment by tungnnx\n\t\t * @reason not uses - low security\n\t\t * @since 3.2.6.8\n\t\t */\n\t\t/*\n\t\tpublic static function plugin_action() {\n\t\t\t$url = learn_press_get_request( 'url' );\n\t\t\tob_start();\n\t\t\twp_remote_get( $url );\n\t\t\tob_get_clean();\n\t\t\techo wp_remote_get( admin_url( 'admin.php?page=learn-press-addons&tab=installed' ) );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * create new page on LP Settings\n\t\t *\n\t\t * @note tungnnx checked use\n\t\t */\n\t\tpublic static function create_page() {\n\t\t\t$response = array(\n\t\t\t\t'code' => 0,\n\t\t\t\t'message' => '',\n\t\t\t);",
"\t\t\t/**\n\t\t\t * Check valid\n\t\t\t *\n\t\t\t * 1. Capability - user can edit pages (add\\edit\\delete)\n\t\t\t * 2. Check nonce return true\n\t\t\t * 3. param post page_name not empty\n\t\t\t *\n\t\t\t * @since 3.2.6.8\n\t\t\t * @author tungnx\n\t\t\t */\n\t\t\tif ( ! current_user_can( 'edit_pages' ) || empty( $_POST['page_name'] ) ) {\n\t\t\t\t$response['message'] = 'Request invalid';\n\t\t\t\tlearn_press_send_json( $response );\n\t\t\t}",
"\t\t\t$page_name = LP_Helper::sanitize_params_submitted( $_POST['page_name'] );",
"\t\t\tif ( $page_name ) {\n\t\t\t\t$page_id = LP_Helper::create_page( $page_name );",
"\t\t\t\tif ( $page_id ) {\n\t\t\t\t\t$response['code'] = 1;\n\t\t\t\t\t$response['message'] = 'create page success';\n\t\t\t\t\t$response['page'] = get_post( $page_id );\n\t\t\t\t\t$html = learn_press_pages_dropdown( '', '', array( 'echo' => false ) );\n\t\t\t\t\tpreg_match_all( '!value=\\\"([0-9]+)\\\"!', $html, $matches );\n\t\t\t\t\t$response['positions'] = $matches[1];\n\t\t\t\t\t$response['html'] = '<a href=\"' . get_edit_post_link( $page_id ) . '\" target=\"_blank\">' . __( 'Edit Page', 'learnpress' ) . '</a> ';\n\t\t\t\t\t$response['html'] .= '<a href=\"' . get_permalink( $page_id ) . '\" target=\"_blank\">' . __( 'View Page', 'learnpress' ) . '</a>';\n\t\t\t\t} else {\n\t\t\t\t\t$response['error'] = __( 'Error! Page creation failed. Please try again.', 'learnpress' );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$response['error'] = __( 'Empty page name!', 'learnpress' );\n\t\t\t}\n\t\t\tlearn_press_send_json( $response );\n\t\t}",
"\t\t/**\n\t\t * Create LP static pages\n\t\t *\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function create_pages() {\n\t\t\tcheck_admin_referer( 'create-pages' );",
"\t\t\t$pages = LP_Request::get_list_array( 'pages' );\n\t\t\t$pages = array_fill_keys( $pages, '' );\n\t\t\t$all_pages = learn_press_static_page_ids();\n\t\t\t$page_names = learn_press_static_pages();",
"\t\t\tif ( empty( $pages ) ) {\n\t\t\t\t$pages = $all_pages;\n\t\t\t}",
"\t\t\tforeach ( $pages as $id => $page_id ) {\n\t\t\t\tif ( ! empty( $all_pages[ $id ] ) ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}",
"\t\t\t\t$page_id = LP_Helper::create_page( isset( $page_names[ $id ] ) ? $page_names[ $id ] : ucfirst( $id ), $id );\n\t\t\t}",
"\t\t\tLP()->flush_rewrite_rules();",
"\t\t\techo esc_html__( 'The required pages are successfully created.', 'learnpress' );",
"\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Install sample data or dismiss the notice depending on user's option\n\t\t */\n\t\t/*public static function install_sample_data() {\n\t\t\t$yes = ! empty( $_REQUEST['yes'] ) ? $_REQUEST['yes'] : '';\n\t\t\t$response = array( 'result' => 'fail' );\n\t\t\t$retry_button = sprintf( '<a href=\"\" class=\"button yes\" data-action=\"yes\">%s</a>', __( 'Please try again.', 'learnpress' ) );\n\t\t\t$dismiss_button = sprintf( '<a href=\"\" class=\"button disabled no\" data-action=\"no\">%s</a>', __( 'Cancel', 'learnpress' ) );\n\t\t\t$buttons = sprintf( '<p>%s %s</p>', $retry_button, $dismiss_button );\n\t\t\tif ( 'no' == $yes ) {\n\t\t\t\tset_transient( 'learn_press_install_sample_data', 'off', 12 * HOUR_IN_SECONDS );\n\t\t\t} else {\n\t\t\t\t$result = array( 'status' => 'activate' );// learn_press_install_and_active_add_on( 'learnpress-import-export' );\n\t\t\t\tif ( 'activate' == $result['status'] ) {\n\t\t\t\t\t// copy dummy-data.xml to import folder of the add-on\n\t\t\t\t\tlpie_mkdir( lpie_import_path() );\n\t\t\t\t\tif ( file_exists( lpie_import_path() ) ) {\n\t\t\t\t\t\t$import_source = LP_PLUGIN_PATH . '/dummy-data/dummy-data.xml';\n\t\t\t\t\t\t$file = 'dummy-data-' . time() . '.xml';\n\t\t\t\t\t\t$copy = lpie_import_path() . '/' . $file;\n\t\t\t\t\t\tcopy( $import_source, $copy );\n\t\t\t\t\t\tif ( file_exists( $copy ) ) {\n\t\t\t\t\t\t\t$url = admin_url( 'admin-ajax.php?page=learn_press_import_export&tab=import-course' );\n\t\t\t\t\t\t\t$postdata = array(\n\t\t\t\t\t\t\t\t'step' => 2,\n\t\t\t\t\t\t\t\t'action' => 'learn_press_import',\n\t\t\t\t\t\t\t\t'import-file' => 'import/' . $file,\n\t\t\t\t\t\t\t\t'nonce' => wp_create_nonce( 'lpie-import-file' ),\n\t\t\t\t\t\t\t\t'x' => 1,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t$response['url'] = $url = $url . '&' . http_build_query( $postdata ) . \"\\n\";\n\t\t\t\t\t\t\t$response['result'] = 'success';\n\t\t\t\t\t\t\t$response['message'] = sprintf( '<p>%s <a href=\"edit.php?post_type=lp_course\">%s</a> </p>', __( 'Successfully import sample data.', 'learnpress' ), __( 'View courses', 'learnpress' ) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif ( $response['result'] == 'fail' ) {\n\t\t\t\t\t\t$response['message'] = sprintf( '<p>%s</p>%s', __( 'Failed to import sample data. Please try again.', 'learnpress' ), $buttons );\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t$response['result'] = 'fail';\n\t\t\t\t\t$response['message'] = sprintf( '<p>%s</p>', __( 'Unknown error when installing/activating Import/Export add-on. Please try again!', 'learnpress' ) ) . $buttons;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlearn_press_send_json( $response );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Activate a bundle of add-ons, if an add-on is not installed then install it first\n\t\t *\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function bundle_activate_add_ons() {\n\t\t\tglobal $learn_press_add_ons;\n\t\t\tinclude_once ABSPATH . 'wp-admin/includes/plugin-install.php'; // for plugins_api..\n\t\t\t$response = array( 'addons' => array() );",
"\t\t\tif ( ! current_user_can( 'activate_plugins' ) ) {\n\t\t\t\t$response['error'] = __( 'You do not have the permission to deactivate plugins on this site.', 'learnpress' );\n\t\t\t} else {",
"\t\t\t\t$add_ons = $learn_press_add_ons['bundle_activate'];",
"\t\t\t\tif ( $add_ons ) {\n\t\t\t\t\tforeach ( $add_ons as $slug ) {\n\t\t\t\t\t\t$response['addons'][ $slug ] = learn_press_install_and_active_add_on( $slug );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlearn_press_send_json( $response );\n\t\t}*/",
"\t\t/**\n\t\t * Activate a bundle of add-ons, if an add-on is not installed then install it first\n\t\t *\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function bundle_activate_add_on() {\n\t\t\t$response = array();\n\t\t\tinclude_once ABSPATH . 'wp-admin/includes/plugin-install.php'; // for plugins_api..\n\t\t\tif ( ! current_user_can( 'activate_plugins' ) ) {\n\t\t\t\t$response['error'] = __( 'You do not have the permission to deactivate plugins on this site.', 'learnpress' );\n\t\t\t} else {\n\t\t\t\t$slug = ! empty( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : null;\n\t\t\t\t$response[ $slug ] = learn_press_install_and_active_add_on( $slug );\n\t\t\t}\n\t\t\tlearn_press_send_json( $response );\n\t\t}*/",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @reason not use\n\t\t * @deprecated 4.0.0.\n\t\t */\n\t\t/*\n\t\tpublic static function plugin_install() {\n\t\t\t$plugin_name = ! empty( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';\n\t\t\t$response = learn_press_install_add_on( $plugin_name );\n\t\t\tlearn_press_send_json( $response );\n\t\t\tdie();\n\t\t}*/",
"\t\t/*\n\t\t * @editor tungnx\n\t\t * @reason not use\n\t\t * @since 3.2.6.8\n\t\t */\n\t\t/*\n\t\tpublic static function update_add_on_status() {\n\t\t\t$plugin = ! empty( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';\n\t\t\t$t = ! empty( $_REQUEST['t'] ) ? $_REQUEST['t'] : '';\n\t\t\t$response = array();\n\t\t\tif ( ! current_user_can( 'activate_plugins' ) ) {\n\t\t\t\t$response['error'] = __( 'You do not have the permission to deactivate plugins on this site.', 'learnpress' );\n\t\t\t}\n\t\t\tif ( $plugin && $t ) {\n\t\t\t\tif ( $t == 'activate' ) {\n\t\t\t\t\tactivate_plugin( $plugin, false, is_network_admin() );\n\t\t\t\t} else {\n\t\t\t\t\tdeactivate_plugins( $plugin, false, is_network_admin() );\n\t\t\t\t}\n\t\t\t\t$is_activate = is_plugin_active( $plugin );\n\t\t\t\t$response['status'] = $is_activate ? 'activate' : 'deactivate';",
"\t\t\t}\n\t\t\twp_send_json( $response );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Output the image to browser with text and params passed via $_GET\n\t\t */\n\t\t/*public static function dummy_image() {\n\t\t\t$text = LP_Helper::sanitize_params_submitted( $_REQUEST['text'] ?? '' );\n\t\t\tlearn_press_text_image( $text, $_GET );\n\t\t\tdie();\n\t\t}*/",
"\t\t/**\n\t\t * Get edit|view link of a page\n\t\t */\n\t\tpublic static function get_page_permalink() {\n\t\t\t$page_id = (int) $_REQUEST['page_id'] ?? 0;\n\t\t\t?>",
"\t\t\t<a href=\"<?php echo get_edit_post_link( $page_id ); ?>\"\n\t\t\t target=\"_blank\"><?php _e( 'Edit Page', 'learnpress' ); ?></a>\n\t\t\t<a href=\"<?php echo get_permalink( $page_id ); ?>\"\n\t\t\t target=\"_blank\"><?php _e( 'View Page', 'learnpress' ); ?></a>",
"\t\t\t<?php\n\t\t\tdie();\n\t\t}",
"\t\t/**\n\t\t * Get date from, to for static chart\n\t\t */\n\t\tpublic static function custom_stats() {\n\t\t\t$from = LP_Helper::sanitize_params_submitted( $_REQUEST['from'] ?? 0 );\n\t\t\t$to = LP_Helper::sanitize_params_submitted( $_REQUEST['to'] ?? 0 );\n\t\t\t$date_diff = strtotime( $to ) - strtotime( $from );\n\t\t\tif ( $date_diff <= 0 || $from == 0 || $to == 0 ) {\n\t\t\t\tdie();\n\t\t\t}\n\t\t\tlearn_press_process_chart( learn_press_get_chart_students( $to, 'days', floor( $date_diff / ( 60 * 60 * 24 ) ) + 1 ) );\n\t\t\tdie();\n\t\t}",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function ignore_setting_up() {\n\t\t\tupdate_option( '_lpr_ignore_setting_up', 1, true );\n\t\t\tdie;\n\t\t}*/",
"\t\t/**\n\t\t * @editor tungnx\n\t\t * @model 4.1.4 comment - not use\n\t\t */\n\t\t/*public static function remove_notice_popup() {\n\t\t\tif ( isset( $_POST['action'] ) && $_POST['action'] === 'learnpress_remove_notice_popup' && isset( $_POST['slug'] ) && ! empty( $_POST['slug'] ) && isset( $_POST['user'] ) && ! empty( $_POST['user'] ) ) {\n\t\t\t\t$slug = 'learnpress_notice_' . $_POST['slug'] . '_' . $_POST['user'];\n\t\t\t\tset_transient( $slug, true, 30 * DAY_IN_SECONDS );\n\t\t\t}",
"\t\t\twp_die();\n\t\t}*/",
"\t\t/*\n\t\tpublic static function update_order_status() {",
"\t\t\t$order_id = learn_press_get_request( 'order_id' );\n\t\t\t$value = learn_press_get_request( 'value' );",
"\t\t\t$order = array(\n\t\t\t\t'ID' => $order_id,\n\t\t\t\t'post_status' => $value,\n\t\t\t);",
"\t\t\twp_update_post( $order ) ? $response['success'] = true : $response['success'] = false;",
"\t\t\tlearn_press_send_json( $response );",
"\t\t\tdie();\n\t\t}*/\n",
"\t\t/**\n\t\t * Upload avatar of user\n\t\t *\n\t\t * @editor tungnx\n\t\t * @modify 4.1.4.2\n\t\t */",
"\t\tpublic static function upload_user_avatar() {",
"\t\t\t$user_id = get_current_user_id();",
"\t\t\tif ( ! $user_id ) {\n\t\t\t\treturn;\n\t\t\t}\n",
"\t\t\t$file = $_FILES['lp-upload-avatar'];\n\t\t\t$upload_dir = learn_press_user_profile_picture_upload_dir();",
"\t\t\tadd_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );",
"\n\t\t\t$file_info_arr = explode( '.', $file['name'] );\n\t\t\t$file_info_arr_length = count( $file_info_arr );\n\t\t\t$file_ext_index = $file_info_arr_length - 1;\n\t\t\t$file_ext = $file_info_arr[ $file_ext_index ];\n\t\t\t$file['name'] = $user_id . '.' . $file_ext;",
"\t\t\t// Delete old image if exists\n\t\t\t$path_img = get_user_meta( $user_id, '_lp_profile_picture', true );\n\t\t\tif ( $path_img ) {\n\t\t\t\t$path = $upload_dir['basedir'] . '/' . $path_img;\n\t\t\t\tif ( file_exists( $path ) ) {\n\t\t\t\t\t@unlink( $path );\n\t\t\t\t}\n\t\t\t}",
"\n\t\t\t$result = wp_handle_upload(\n\t\t\t\t$file,\n\t\t\t\tarray(\n\t\t\t\t\t'test_form' => false,\n\t\t\t\t)\n\t\t\t);",
"\t\t\tremove_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );\n\t\t\tif ( is_array( $result ) ) {\n\t\t\t\t$result['name'] = $upload_dir['subdir'] . '/' . basename( $result['file'] );",
"\t\t\t\tupdate_user_meta( $user_id, '_lp_profile_picture', $result['name'] );",
"\t\t\t\tunset( $result['file'] );\n\t\t\t} else {\n\t\t\t\t$result = array(\n\t\t\t\t\t'error' => __( 'Profile picture upload failed', 'learnpress' ),\n\t\t\t\t);\n\t\t\t}\n\t\t\tlearn_press_send_json( $result );",
"\t\t}",
"\t\t/**\n\t\t * Crop avatar of user\n\t\t *\n\t\t * @editor tungnx\n\t\t * @return void\n\t\t */\n\t\tpublic static function save_uploaded_user_avatar() {\n\t\t\t$avatar_data = wp_parse_args(\n\t\t\t\tLP_Request::get( 'lp-user-avatar-crop' ),\n\t\t\t\tarray(\n\t\t\t\t\t'name' => '',\n\t\t\t\t\t'width' => '',\n\t\t\t\t\t'height' => '',\n\t\t\t\t\t'points' => '',\n\t\t\t\t\t'nonce' => '',\n\t\t\t\t)\n\t\t\t);",
"\t\t\t$current_user_id = get_current_user_id();",
"\t\t\tif ( ! wp_verify_nonce( $avatar_data['nonce'], 'save-uploaded-profile-' . $current_user_id ) ) {\n\t\t\t\tdie( 'ERROR VERIFY NONCE!' );\n\t\t\t}",
"\t\t\t$url = learn_press_update_user_profile_avatar();\n\t\t\tif ( $url ) {\n\t\t\t\tlearn_press_send_json(\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'success' => true,\n\t\t\t\t\t\t'avatar' => sprintf( '<img src=\"%s\" />', $url ),\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t};",
"\t\t\twp_die();\n\t\t}",
"\t\t/**\n\t\t * Remove avatar of user\n\t\t *\n\t\t * @author tungnx\n\t\t * @since 4.1.4.2\n\t\t * @version 1.0.0\n\t\t * @return void\n\t\t */\n\t\tpublic static function remove_avatar() {\n\t\t\t$response = new LP_REST_Response();",
"\t\t\ttry {\n\t\t\t\t$user_id = get_current_user_id();\n\t\t\t\tif ( ! $user_id ) {\n\t\t\t\t\tthrow new Exception( __( 'User is invalid', 'learnpress' ) );\n\t\t\t\t}",
"\t\t\t\t// Delete old image if exists\n\t\t\t\t$path_img = get_user_meta( $user_id, '_lp_profile_picture', true );\n\t\t\t\tif ( $path_img ) {\n\t\t\t\t\t$upload_dir = learn_press_user_profile_picture_upload_dir();\n\t\t\t\t\t$path = $upload_dir['basedir'] . '/' . $path_img;\n\t\t\t\t\tif ( file_exists( $path ) ) {\n\t\t\t\t\t\tunlink( $path );\n\t\t\t\t\t\t$response->status = 'success';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch ( Throwable $e ) {\n\t\t\t\t$response->message = $e->getMessage();\n\t\t\t}",
"\t\t\twp_send_json( $response );",
"\t\t}",
"\t\tpublic static function _user_avatar_upload_dir( $dir ) {\n\t\t\t$dir = learn_press_user_profile_picture_upload_dir();",
"\t\t\treturn $dir;\n\t\t}",
"\t\t/**\n\t\t * Export Order invoice to PDF\n\t\t *\n\t\t * @since 3.2.7.8\n\t\t * @author hungkv\n\t\t */\n\t\tpublic static function update_order_exports() {\n\t\t\t$order_id = absint( $_POST['order_id'] );\n\t\t\t//$site_title = LP_Helper::sanitize_params_submitted( $_POST['site_title'] );\n\t\t\t//$order_date = LP_Helper::sanitize_params_submitted( $_POST['order_date'] );\n\t\t\t//$invoice_no = LP_Helper::sanitize_params_submitted( $_POST['invoice_no'] );\n\t\t\t//$order_customer = LP_Helper::sanitize_params_submitted( $_POST['order_customer'] );\n\t\t\t//$order_email = LP_Helper::sanitize_params_submitted( $_POST['order_email'] );\n\t\t\t//$order_payment = LP_Helper::sanitize_params_submitted( $_POST['order_payment'] );\n\t\t\t$order = learn_press_get_order( $order_id );\n\t\t\t$currency_symbol = learn_press_get_currency_symbol( $order->get_currency() );",
"\t\t\tob_start();\n\t\t\tlearn_press_admin_view(\n\t\t\t\t'meta-boxes/order/content-tab-preview-exports-invoice.php',\n\t\t\t\tarray(\n\t\t\t\t\t'order' => $order,\n\t\t\t\t\t'currency_symbol' => $currency_symbol,\n\t\t\t\t)\n\t\t\t);\n\t\t\t$html = ob_get_clean();\n\t\t\techo $html;\n\t\t\tdie();\n\t\t}\n\t}",
"\tif ( defined( 'DOING_AJAX' ) ) {\n\t\tadd_action( 'wp_ajax_learnpress_upload-user-avatar', array( 'LP_Admin_Ajax', 'upload_user_avatar' ) );",
"\t\tadd_action( 'wp_ajax_learnpress_save-uploaded-user-avatar', array( 'LP_Admin_Ajax', 'save_uploaded_user_avatar' ) );\n\t\tadd_action( 'wp_ajax_learnpress_remove-avatar', array( 'LP_Admin_Ajax', 'remove_avatar' ) );",
"\t}",
"\tadd_action( 'init', array( 'LP_Admin_Ajax', 'init' ) );\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [61, 1262, 233, 1156], "buggy_code_start_loc": [27, 1198, 14, 1081], "filenames": ["assets/src/js/frontend/profile.js", "inc/admin/class-lp-admin-ajax.php", "inc/class-lp-ajax.php", "inc/user/lp-user-functions.php"], "fixing_code_end_loc": [71, 1364, 200, 1152], "fixing_code_start_loc": [27, 1199, 14, 1082], "message": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thimpress:learnpress:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "F74AC61D-6728-4759-B5A4-F03B9519485C", "versionEndExcluding": "4.1.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site."}, {"lang": "es", "value": "Los usuarios del plugin LearnPress de WordPress versiones anteriores a 4.1.5, pueden subir una imagen como avatar de perfil tras el registro. Tras este proceso, el usuario recorta y guarda la imagen. A continuaci\u00f3n, se env\u00eda al servidor una petici\u00f3n \"POST\" que contiene el nombre de la imagen suministrado por el usuario para cambiar el nombre y recortar la imagen. Como resultado de esta petici\u00f3n, el nombre de la imagen suministrada por el usuario es cambiada con un valor MD5. Este proceso s\u00f3lo puede llevarse a cabo cuando el tipo de la imagen es JPG o PNG. Un atacante puede usar esta vulnerabilidad para cambiar el nombre de un archivo de imagen arbitrario. Al hacer esto, podr\u00edan destruir el dise\u00f1o del sitio web."}], "evaluatorComment": null, "id": "CVE-2022-0377", "lastModified": "2022-03-08T16:39:46.640", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-28T09:15:09.093", "references": [{"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://bozogullarindan.com/en/2022/01/wordpress-learnpress-plugin-4.1.4.1-arbitrary-image-renaming/"}, {"source": "contact@wpscan.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, {"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://wpscan.com/vulnerability/0d95ada6-53e3-4a80-a395-eacd7b090f26"}], "sourceIdentifier": "contact@wpscan.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-610"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-73"}], "source": "contact@wpscan.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, "type": "CWE-610"}
| 263
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\ndefined( 'ABSPATH' ) || exit;",
"if ( ! class_exists( 'LP_AJAX' ) ) {\n\tclass LP_AJAX {\n\t\t/**\n\t\t * Init common ajax events\n\t\t */\n\t\tpublic static function init() {\n\t\t\t$ajax_events = array(\n\t\t\t\t'checkout-user-email-exists:nopriv',\n\t\t\t\t'recover-order',\n\t\t\t\t'request-become-a-teacher:nonce',",
"\t\t\t\t'upload-user-avatar',",
"\t\t\t\t'checkout:nopriv',\n\t\t\t\t'complete-lesson',\n\t\t\t\t'finish-course', // finish_course.\n\t\t\t\t// 'retake-course', // retake_course.\n\t\t\t\t'external-link:nopriv',",
"\t\t\t\t'save-uploaded-user-avatar',",
"\t\t\t\t'load-more-courses',\n\t\t\t);",
"\t\t\t$ajax_events = apply_filters( 'learn-press/ajax/events', $ajax_events );",
"\t\t\tforeach ( $ajax_events as $action => $callback ) {",
"\t\t\t\tif ( is_numeric( $action ) ) {\n\t\t\t\t\t$action = $callback;\n\t\t\t\t}",
"\t\t\t\t$actions = LP_Request::parse_action( $action );\n\t\t\t\t$method = $actions['action'];",
"\t\t\t\tif ( ! is_callable( $callback ) ) {\n\t\t\t\t\t$method = preg_replace( '/-/', '_', $method );\n\t\t\t\t\t$callback = array( __CLASS__, $method );\n\t\t\t\t}",
"\t\t\t\tLP_Request::register_ajax( $action, $callback );\n\t\t\t}\n",
"\t\t\tadd_action( 'wp_ajax_learnpress_upload-user-avatar', array( __CLASS__, 'upload_user_avatar' ) );",
"\t\t}",
"\t\tpublic static function load_more_courses() {\n\t\t\t$type = LP_Request::get( 'type' );\n\t\t\t$user_id = LP_Request::get_int( 'user', 0 );\n\t\t\t$paged = LP_Request::get_int( 'current_page', 1 );\n\t\t\t$template = LP_Request::get( 'template' );",
"\t\t\t$user = learn_press_get_user( $user_id );\n\t\t\t$template_args = array();",
"\t\t\tif ( in_array( $type, array( 'featured', 'latest' ) ) ) {\n\t\t\t\t$query_args = array(\n\t\t\t\t\t'paginate' => true,\n\t\t\t\t\t'return' => 'ids',\n\t\t\t\t\t'author' => $user->get_id(),\n\t\t\t\t\t'paged' => $paged,\n\t\t\t\t);",
"\t\t\t\tif ( 'featured' === $type ) {\n\t\t\t\t\t$query_args['featured'] = 1;\n\t\t\t\t}",
"\t\t\t\t$query = new LP_Course_Query( $query_args );\n\t\t\t\t$template_args = (array) $query->get_courses();\n\t\t\t\t$template = \"profile/dashboard/{$type}-courses\";",
"\t\t\t} else {\n\t\t\t\t$profile = LP_Profile::instance( $user_id );\n\t\t\t\t$filter_status = LP_Request::get_string( 'filter-status' );\n\t\t\t\t$query = $profile->query_courses( 'purchased', array( 'status' => $filter_status ) );\n\t\t\t}",
"\t\t\tlearn_press_get_template( $template, $template_args );",
"\t\t\twp_die();\n\t\t}",
"\t\tpublic static function external_link() {\n\t\t\t$nonce = LP_Request::get( 'nonce' );\n\t\t\t$id = LP_Request::get( 'id' );\n\t\t\t$course = learn_press_get_course( $id );",
"\t\t\tif ( ! $course ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\t$link = $course->get_external_link();",
"\t\t\tif ( ! wp_verify_nonce( $nonce, 'external-link-' . $link ) ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\tif ( apply_filters( 'learn-press/course-redirect-external-link', $id ) ) {\n\t\t\t\twp_redirect( $link );\n\t\t\t\texit();\n\t\t\t}\n\t\t}",
"\t\tpublic static function checkout() {\n\t\t\tLP()->checkout()->process_checkout_handler();\n\t\t}",
"\t\tpublic static function request_become_a_teacher() {\n\t\t\tLP_Forms_Handler::process_become_teacher();\n\t\t}",
"\t\tpublic static function recover_order() {\n\t\t\tif ( ! LP_Request::verify_nonce( 'recover-order' ) ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\t$factory = LP_Factory::get_order_factory();\n\t\t\t$user_id = get_current_user_id();\n\t\t\t$order_key = LP_Request::get_string( 'order-key' );\n\t\t\t$order = $factory->recover( $order_key, $user_id );\n\t\t\t$result = array( 'result' => 'success' );",
"\t\t\tif ( is_wp_error( $order ) ) {\n\t\t\t\t$result['message'] = $order->get_error_message();\n\t\t\t\t$result['result'] = 'error';\n\t\t\t} else {\n\t\t\t\t$result['message'] = sprintf(\n\t\t\t\t\t__( 'The order %s has been successfully recovered.', 'learnpress' ),\n\t\t\t\t\t$order_key\n\t\t\t\t);\n\t\t\t\t$result['redirect'] = $order->get_view_order_url();\n\t\t\t}",
"\t\t\t$result = apply_filters( 'learn-press/order/recover-result', $result, $order_key, $user_id );",
"\t\t\tlearn_press_maybe_send_json( $result );",
"\t\t\tif ( ! empty( $result['message'] ) ) {\n\t\t\t\tlearn_press_add_message( $result['message'] );\n\t\t\t}",
"\t\t\tif ( ! empty( $result['redirect'] ) ) {\n\t\t\t\twp_redirect( $result['redirect'] );\n\t\t\t\texit();\n\t\t\t}\n\t\t}",
"\t\tpublic static function checkout_user_email_exists() {\n\t\t\t$email = LP_Request::get_email( 'email' );\n\t\t\t$response = array(\n\t\t\t\t'exists' => 0,\n\t\t\t);",
"\t\t\tif ( email_exists( $email ) ) {\n\t\t\t\t$response['exists'] = $email;\n\t\t\t\t$output = '<div class=\"lp-guest-checkout-output\">' . __(\n\t\t\t\t\t'Your email is already exists. Continue with this email?',\n\t\t\t\t\t'learnpress'\n\t\t\t\t) . '</div>';\n\t\t\t} else {\n\t\t\t\t$output = '<label class=\"lp-guest-checkout-output\">\n\t\t\t\t\t<input type=\"checkbox\" name=\"checkout-email-option\" value=\"new-account\">\n\t\t\t\t' . __(\n\t\t\t\t\t'Create new account with this email? Account information will be sent to this email.',\n\t\t\t\t\t'learnpress'\n\t\t\t\t) . '\n\t\t\t\t</label>';\n\t\t\t}",
"\t\t\t$response['output'] = apply_filters( 'learnpress/guest_checkout_email_exist_output', $output, $email );",
"\t\t\tlearn_press_maybe_send_json( $response );\n\t\t}\n",
"\t\tpublic static function upload_user_avatar() {",
"\t\t\t$file = $_FILES['lp-upload-avatar'];\n\t\t\t$upload_dir = learn_press_user_profile_picture_upload_dir();",
"\t\t\tadd_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );",
"\t\t\t$result = wp_handle_upload(\n\t\t\t\t$file,\n\t\t\t\tarray(\n\t\t\t\t\t'test_form' => false,\n\t\t\t\t)\n\t\t\t);",
"\t\t\tremove_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );",
"\t\t\tif ( is_array( $result ) ) {\n\t\t\t\t$result['name'] = $upload_dir['subdir'] . '/' . basename( $result['file'] );\n\t\t\t\tunset( $result['file'] );\n\t\t\t} else {\n\t\t\t\t$result = array(\n\t\t\t\t\t'error' => __( 'Profile picture upload failed', 'learnpress' ),\n\t\t\t\t);\n\t\t\t}",
"\t\t\tlearn_press_send_json( $result );",
"\t\t}",
"\t\tpublic static function save_uploaded_user_avatar() {\n\t\t\t$avatar_data = wp_parse_args(\n\t\t\t\tLP_Request::get( 'lp-user-avatar-crop' ),\n\t\t\t\tarray(\n\t\t\t\t\t'name' => '',\n\t\t\t\t\t'width' => '',\n\t\t\t\t\t'height' => '',\n\t\t\t\t\t'points' => '',\n\t\t\t\t\t'nonce' => '',\n\t\t\t\t)\n\t\t\t);",
"\t\t\t$current_user_id = get_current_user_id();",
"\t\t\tif ( ! wp_verify_nonce( $avatar_data['nonce'], 'save-uploaded-profile-' . $current_user_id ) ) {\n\t\t\t\tdie( 'ERROR VERIFY NONCE!' );\n\t\t\t}",
"\t\t\t$url = learn_press_update_user_profile_avatar();\n\t\t\tif ( $url ) {\n\t\t\t\t$user = learn_press_get_current_user();",
"\t\t\t\tlearn_press_send_json(\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'success' => true,\n\t\t\t\t\t\t'avatar' => sprintf( '<img src=\"%s\" />', $url ),\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t};",
"\t\t\twp_die();\n\t\t}",
"\n\t\tpublic static function _user_avatar_upload_dir( $dir ) {\n\t\t\t$dir = learn_press_user_profile_picture_upload_dir();",
"\t\t\treturn $dir;\n\t\t}",
"\t\t/**\n\t\t * Request finish course\n\t\t *\n\t\t * TODO: should move this function to api - tungnx\n\t\t */\n\t\tpublic static function finish_course() {\n\t\t\t$nonce = LP_Request::get_string( 'finish-course-nonce' );\n\t\t\t$course_id = LP_Request::get_int( 'course-id' );\n\t\t\t$course = learn_press_get_course( $course_id );\n\t\t\t$user = learn_press_get_current_user();",
"\t\t\t$nonce_action = sprintf( 'finish-course-%d-%d', $course_id, $user->get_id() );",
"\t\t\tif ( ! $user->get_id() || ! $course || ! wp_verify_nonce( $nonce, $nonce_action ) ) {\n\t\t\t\twp_die( __( 'Access denied!', 'learnpress' ) );\n\t\t\t}",
"\t\t\t$finished = $user->finish_course( $course_id );\n\t\t\t$lp_redirect = LP_Settings::get_option( 'course_finish_redirect' );\n\t\t\t$redirect = ! empty( $lp_redirect ) ? $lp_redirect : get_the_permalink( $course_id );",
"\t\t\t$response = array(\n\t\t\t\t'redirect' => apply_filters(\n\t\t\t\t\t'learn-press/finish-course-redirect',\n\t\t\t\t\t$redirect,\n\t\t\t\t\t$course_id\n\t\t\t\t),\n\t\t\t);",
"\t\t\tif ( $finished ) {\n\t\t\t\tlearn_press_update_user_item_meta( $finished, 'finishing_type', 'click' );\n\t\t\t\tlearn_press_add_message( sprintf( __( 'You have finished this course \"%s\"', 'learnpress' ), $course->get_title() ) );\n\t\t\t\t$response['result'] = 'success';\n\t\t\t} else {\n\t\t\t\tlearn_press_add_message( __( 'Error! You cannot finish this course. Please contact your administrator for more information.', 'learnpress' ) );\n\t\t\t\t$response['result'] = 'error';\n\t\t\t}",
"\t\t\tlearn_press_maybe_send_json( $response );",
"\t\t\tif ( ! empty( $response['redirect'] ) ) {\n\t\t\t\twp_redirect( $response['redirect'] );\n\t\t\t\texit();\n\t\t\t}\n\t\t}",
"\t\t/**\n\t\t * Complete lesson\n\t\t */\n\t\tpublic static function complete_lesson() {\n\t\t\t$nonce = LP_Request::get_string( 'complete-lesson-nonce' );\n\t\t\t$item_id = LP_Request::get_int( 'id' );\n\t\t\t$course_id = LP_Request::get_int( 'course_id' );",
"\t\t\t$post = get_post( $item_id );\n\t\t\t$user = learn_press_get_current_user();\n\t\t\t$course = learn_press_get_course( $course_id );\n\t\t\t$response = array(\n\t\t\t\t'result' => 'success',\n\t\t\t\t'redirect' => $course->get_item_link( $item_id ),\n\t\t\t);",
"\t\t\t$item = $course->get_item( $item_id );\n\t\t\t$nonce_action = $item->get_nonce_action( 'complete', $course_id, $user->get_id() );\n\t\t\ttry {\n\t\t\t\t// security check\n\t\t\t\tif ( ! $post || ( $post && ! wp_verify_nonce( $nonce, $nonce_action ) ) ) {\n\t\t\t\t\tthrow new Exception( __( 'Error! Invalid lesson or failed security check.', 'learnpress' ), 8000 );\n\t\t\t\t}",
"\t\t\t\t$result = $user->complete_lesson( $item_id );",
"\t\t\t\tif ( ! is_wp_error( $result ) ) {\n\t\t\t\t\tif ( $course->get_next_item() ) {\n\t\t\t\t\t\t$next = $course->get_next_item();\n\t\t\t\t\t\t$response['redirect'] = $course->get_item_link( $next );\n\t\t\t\t\t}",
"\t\t\t\t\tlearn_press_add_message( sprintf( __( 'Congrats! You have completed \"%s\".', 'learnpress' ), $item->get_title() ) );\n\t\t\t\t} else {\n\t\t\t\t\tlearn_press_add_message( $result->get_error_message(), 'error' );\n\t\t\t\t}",
"\t\t\t\t$response = apply_filters( 'learn-press/user-completed-lesson-result', $response, $item_id, $course_id, $user->get_id() );\n\t\t\t} catch ( Exception $ex ) {\n\t\t\t\tlearn_press_add_message( $ex->getMessage(), 'error' );\n\t\t\t}",
"\t\t\tif ( learn_press_message_count( 'error' ) ) {\n\t\t\t\t$response['result'] = 'error';\n\t\t\t}",
"\t\t\tlearn_press_maybe_send_json( $response );",
"\t\t\tif ( ! empty( $response['redirect'] ) ) {\n\t\t\t\t// wp_cache_flush();\n\t\t\t\twp_redirect( $response['redirect'] );\n\t\t\t\texit();\n\t\t\t}\n\t\t}",
"\t\t/**\n\t\t * Retake course action\n\t\t *\n\t\t * @TODO move this function to API\n\t\t */\n\t\t/*\n\t\tpublic static function retake_course() {\n\t\t\t$security = LP_Request::get_string( 'retake-course-nonce' );\n\t\t\t$course_id = LP_Request::get_int( 'retake-course' );\n\t\t\t$user = learn_press_get_current_user();\n\t\t\t$course = learn_press_get_course( $course_id );\n\t\t\t$response = array(\n\t\t\t\t'result' => 'error',\n\t\t\t);",
"\t\t\t$security_action = sprintf( 'retake-course-%d-%d', $course->get_id(), $user->get_id() );\n\t\t\t// security check\n\t\t\tif ( ! wp_verify_nonce( $security, $security_action ) ) {\n\t\t\t\tlearn_press_add_message( __( 'Error! Invalid course or failed security check.', 'learnpress' ),\n\t\t\t\t\t'error' );\n\t\t\t} else {\n\t\t\t\tif ( $user->can_retake_course( $course_id ) ) {\n\t\t\t\t\t$result = $user->retry_course( $course_id );",
"\t\t\t\t\tif ( ! $result ) {\n\t\t\t\t\t\tlearn_press_add_message( __( 'Error!', 'learnpress' ), 'error' );\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlearn_press_add_message( sprintf( __( 'You have retaken the course \"%s\"', 'learnpress' ),\n\t\t\t\t\t\t\t$course->get_title() ) );\n\t\t\t\t\t\t$response['result'] = 'success';\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlearn_press_add_message( __( 'Error! You can not retake the course', 'learnpress' ), 'error' );\n\t\t\t\t}\n\t\t\t}",
"\t\t\tif ( learn_press_message_count( 'error' ) == 0 ) {\n\t\t\t\t$item = $course->get_item_at( 0 );",
"\t\t\t\tif ( $item ) {\n\t\t\t\t\t$redirect = $course->get_item_link( $item );\n\t\t\t\t} else {\n\t\t\t\t\t$redirect = $course->get_permalink();\n\t\t\t\t}\n\t\t\t\t$response['redirect'] = apply_filters( 'learn-press/user-retake-course-redirect', $redirect );\n\t\t\t\t$response = apply_filters( 'learn-press/user-retaken-course-result', $response, $course_id,\n\t\t\t\t\t$user->get_id() );\n\t\t\t} else {\n\t\t\t\t$response['redirect'] = $course->get_permalink();\n\t\t\t\t$response = apply_filters( 'learn-press/user-retake-course-failed-result', $response,\n\t\t\t\t\t$course_id, $user->get_id() );\n\t\t\t}",
"\t\t\tlearn_press_maybe_send_json( $response );",
"\t\t\tif ( ! empty( $response['redirect'] ) ) {\n\t\t\t\twp_redirect( $response['redirect'] );\n\t\t\t\texit();\n\t\t\t}\n\t\t}*/\n\t}\n}",
"LP_AJAX::init();"
] |
[
1,
1,
0,
1,
0,
1,
1,
1,
1,
1,
1,
1,
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,
0,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [61, 1262, 233, 1156], "buggy_code_start_loc": [27, 1198, 14, 1081], "filenames": ["assets/src/js/frontend/profile.js", "inc/admin/class-lp-admin-ajax.php", "inc/class-lp-ajax.php", "inc/user/lp-user-functions.php"], "fixing_code_end_loc": [71, 1364, 200, 1152], "fixing_code_start_loc": [27, 1199, 14, 1082], "message": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thimpress:learnpress:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "F74AC61D-6728-4759-B5A4-F03B9519485C", "versionEndExcluding": "4.1.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site."}, {"lang": "es", "value": "Los usuarios del plugin LearnPress de WordPress versiones anteriores a 4.1.5, pueden subir una imagen como avatar de perfil tras el registro. Tras este proceso, el usuario recorta y guarda la imagen. A continuaci\u00f3n, se env\u00eda al servidor una petici\u00f3n \"POST\" que contiene el nombre de la imagen suministrado por el usuario para cambiar el nombre y recortar la imagen. Como resultado de esta petici\u00f3n, el nombre de la imagen suministrada por el usuario es cambiada con un valor MD5. Este proceso s\u00f3lo puede llevarse a cabo cuando el tipo de la imagen es JPG o PNG. Un atacante puede usar esta vulnerabilidad para cambiar el nombre de un archivo de imagen arbitrario. Al hacer esto, podr\u00edan destruir el dise\u00f1o del sitio web."}], "evaluatorComment": null, "id": "CVE-2022-0377", "lastModified": "2022-03-08T16:39:46.640", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-28T09:15:09.093", "references": [{"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://bozogullarindan.com/en/2022/01/wordpress-learnpress-plugin-4.1.4.1-arbitrary-image-renaming/"}, {"source": "contact@wpscan.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, {"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://wpscan.com/vulnerability/0d95ada6-53e3-4a80-a395-eacd7b090f26"}], "sourceIdentifier": "contact@wpscan.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-610"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-73"}], "source": "contact@wpscan.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, "type": "CWE-610"}
| 263
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\ndefined( 'ABSPATH' ) || exit;",
"if ( ! class_exists( 'LP_AJAX' ) ) {\n\tclass LP_AJAX {\n\t\t/**\n\t\t * Init common ajax events\n\t\t */\n\t\tpublic static function init() {\n\t\t\t$ajax_events = array(\n\t\t\t\t'checkout-user-email-exists:nopriv',\n\t\t\t\t'recover-order',\n\t\t\t\t'request-become-a-teacher:nonce',",
"\t\t\t\t// 'upload-user-avatar',",
"\t\t\t\t'checkout:nopriv',\n\t\t\t\t'complete-lesson',\n\t\t\t\t'finish-course', // finish_course.\n\t\t\t\t// 'retake-course', // retake_course.\n\t\t\t\t'external-link:nopriv',",
"\t\t\t\t// 'save-uploaded-user-avatar',",
"\t\t\t\t'load-more-courses',\n\t\t\t);",
"\t\t\t$ajax_events = apply_filters( 'learn-press/ajax/events', $ajax_events );",
"\t\t\tforeach ( $ajax_events as $action => $callback ) {",
"\t\t\t\tif ( is_numeric( $action ) ) {\n\t\t\t\t\t$action = $callback;\n\t\t\t\t}",
"\t\t\t\t$actions = LP_Request::parse_action( $action );\n\t\t\t\t$method = $actions['action'];",
"\t\t\t\tif ( ! is_callable( $callback ) ) {\n\t\t\t\t\t$method = preg_replace( '/-/', '_', $method );\n\t\t\t\t\t$callback = array( __CLASS__, $method );\n\t\t\t\t}",
"\t\t\t\tLP_Request::register_ajax( $action, $callback );\n\t\t\t}\n",
"\t\t\t//add_action( 'wp_ajax_learnpress_upload-user-avatar', array( __CLASS__, 'upload_user_avatar' ) );",
"\t\t}",
"\t\tpublic static function load_more_courses() {\n\t\t\t$type = LP_Request::get( 'type' );\n\t\t\t$user_id = LP_Request::get_int( 'user', 0 );\n\t\t\t$paged = LP_Request::get_int( 'current_page', 1 );\n\t\t\t$template = LP_Request::get( 'template' );",
"\t\t\t$user = learn_press_get_user( $user_id );\n\t\t\t$template_args = array();",
"\t\t\tif ( in_array( $type, array( 'featured', 'latest' ) ) ) {\n\t\t\t\t$query_args = array(\n\t\t\t\t\t'paginate' => true,\n\t\t\t\t\t'return' => 'ids',\n\t\t\t\t\t'author' => $user->get_id(),\n\t\t\t\t\t'paged' => $paged,\n\t\t\t\t);",
"\t\t\t\tif ( 'featured' === $type ) {\n\t\t\t\t\t$query_args['featured'] = 1;\n\t\t\t\t}",
"\t\t\t\t$query = new LP_Course_Query( $query_args );\n\t\t\t\t$template_args = (array) $query->get_courses();\n\t\t\t\t$template = \"profile/dashboard/{$type}-courses\";",
"\t\t\t} else {\n\t\t\t\t$profile = LP_Profile::instance( $user_id );\n\t\t\t\t$filter_status = LP_Request::get_string( 'filter-status' );\n\t\t\t\t$query = $profile->query_courses( 'purchased', array( 'status' => $filter_status ) );\n\t\t\t}",
"\t\t\tlearn_press_get_template( $template, $template_args );",
"\t\t\twp_die();\n\t\t}",
"\t\tpublic static function external_link() {\n\t\t\t$nonce = LP_Request::get( 'nonce' );\n\t\t\t$id = LP_Request::get( 'id' );\n\t\t\t$course = learn_press_get_course( $id );",
"\t\t\tif ( ! $course ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\t$link = $course->get_external_link();",
"\t\t\tif ( ! wp_verify_nonce( $nonce, 'external-link-' . $link ) ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\tif ( apply_filters( 'learn-press/course-redirect-external-link', $id ) ) {\n\t\t\t\twp_redirect( $link );\n\t\t\t\texit();\n\t\t\t}\n\t\t}",
"\t\tpublic static function checkout() {\n\t\t\tLP()->checkout()->process_checkout_handler();\n\t\t}",
"\t\tpublic static function request_become_a_teacher() {\n\t\t\tLP_Forms_Handler::process_become_teacher();\n\t\t}",
"\t\tpublic static function recover_order() {\n\t\t\tif ( ! LP_Request::verify_nonce( 'recover-order' ) ) {\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\t$factory = LP_Factory::get_order_factory();\n\t\t\t$user_id = get_current_user_id();\n\t\t\t$order_key = LP_Request::get_string( 'order-key' );\n\t\t\t$order = $factory->recover( $order_key, $user_id );\n\t\t\t$result = array( 'result' => 'success' );",
"\t\t\tif ( is_wp_error( $order ) ) {\n\t\t\t\t$result['message'] = $order->get_error_message();\n\t\t\t\t$result['result'] = 'error';\n\t\t\t} else {\n\t\t\t\t$result['message'] = sprintf(\n\t\t\t\t\t__( 'The order %s has been successfully recovered.', 'learnpress' ),\n\t\t\t\t\t$order_key\n\t\t\t\t);\n\t\t\t\t$result['redirect'] = $order->get_view_order_url();\n\t\t\t}",
"\t\t\t$result = apply_filters( 'learn-press/order/recover-result', $result, $order_key, $user_id );",
"\t\t\tlearn_press_maybe_send_json( $result );",
"\t\t\tif ( ! empty( $result['message'] ) ) {\n\t\t\t\tlearn_press_add_message( $result['message'] );\n\t\t\t}",
"\t\t\tif ( ! empty( $result['redirect'] ) ) {\n\t\t\t\twp_redirect( $result['redirect'] );\n\t\t\t\texit();\n\t\t\t}\n\t\t}",
"\t\tpublic static function checkout_user_email_exists() {\n\t\t\t$email = LP_Request::get_email( 'email' );\n\t\t\t$response = array(\n\t\t\t\t'exists' => 0,\n\t\t\t);",
"\t\t\tif ( email_exists( $email ) ) {\n\t\t\t\t$response['exists'] = $email;\n\t\t\t\t$output = '<div class=\"lp-guest-checkout-output\">' . __(\n\t\t\t\t\t'Your email is already exists. Continue with this email?',\n\t\t\t\t\t'learnpress'\n\t\t\t\t) . '</div>';\n\t\t\t} else {\n\t\t\t\t$output = '<label class=\"lp-guest-checkout-output\">\n\t\t\t\t\t<input type=\"checkbox\" name=\"checkout-email-option\" value=\"new-account\">\n\t\t\t\t' . __(\n\t\t\t\t\t'Create new account with this email? Account information will be sent to this email.',\n\t\t\t\t\t'learnpress'\n\t\t\t\t) . '\n\t\t\t\t</label>';\n\t\t\t}",
"\t\t\t$response['output'] = apply_filters( 'learnpress/guest_checkout_email_exist_output', $output, $email );",
"\t\t\tlearn_press_maybe_send_json( $response );\n\t\t}\n",
"\t\t/*public static function upload_user_avatar() {",
"\t\t\t$file = $_FILES['lp-upload-avatar'];\n\t\t\t$upload_dir = learn_press_user_profile_picture_upload_dir();",
"\t\t\tadd_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );",
"\t\t\t$result = wp_handle_upload(\n\t\t\t\t$file,\n\t\t\t\tarray(\n\t\t\t\t\t'test_form' => false,\n\t\t\t\t)\n\t\t\t);",
"\t\t\tremove_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );",
"\t\t\tif ( is_array( $result ) ) {\n\t\t\t\t$result['name'] = $upload_dir['subdir'] . '/' . basename( $result['file'] );\n\t\t\t\tunset( $result['file'] );\n\t\t\t} else {\n\t\t\t\t$result = array(\n\t\t\t\t\t'error' => __( 'Profile picture upload failed', 'learnpress' ),\n\t\t\t\t);\n\t\t\t}",
"\t\t\tlearn_press_send_json( $result );",
"\t\t}*/",
"\n\t\tpublic static function _user_avatar_upload_dir( $dir ) {\n\t\t\t$dir = learn_press_user_profile_picture_upload_dir();",
"\t\t\treturn $dir;\n\t\t}",
"\t\t/**\n\t\t * Request finish course\n\t\t *\n\t\t * TODO: should move this function to api - tungnx\n\t\t */\n\t\tpublic static function finish_course() {\n\t\t\t$nonce = LP_Request::get_string( 'finish-course-nonce' );\n\t\t\t$course_id = LP_Request::get_int( 'course-id' );\n\t\t\t$course = learn_press_get_course( $course_id );\n\t\t\t$user = learn_press_get_current_user();",
"\t\t\t$nonce_action = sprintf( 'finish-course-%d-%d', $course_id, $user->get_id() );",
"\t\t\tif ( ! $user->get_id() || ! $course || ! wp_verify_nonce( $nonce, $nonce_action ) ) {\n\t\t\t\twp_die( __( 'Access denied!', 'learnpress' ) );\n\t\t\t}",
"\t\t\t$finished = $user->finish_course( $course_id );\n\t\t\t$lp_redirect = LP_Settings::get_option( 'course_finish_redirect' );\n\t\t\t$redirect = ! empty( $lp_redirect ) ? $lp_redirect : get_the_permalink( $course_id );",
"\t\t\t$response = array(\n\t\t\t\t'redirect' => apply_filters(\n\t\t\t\t\t'learn-press/finish-course-redirect',\n\t\t\t\t\t$redirect,\n\t\t\t\t\t$course_id\n\t\t\t\t),\n\t\t\t);",
"\t\t\tif ( $finished ) {\n\t\t\t\tlearn_press_update_user_item_meta( $finished, 'finishing_type', 'click' );\n\t\t\t\tlearn_press_add_message( sprintf( __( 'You have finished this course \"%s\"', 'learnpress' ), $course->get_title() ) );\n\t\t\t\t$response['result'] = 'success';\n\t\t\t} else {\n\t\t\t\tlearn_press_add_message( __( 'Error! You cannot finish this course. Please contact your administrator for more information.', 'learnpress' ) );\n\t\t\t\t$response['result'] = 'error';\n\t\t\t}",
"\t\t\tlearn_press_maybe_send_json( $response );",
"\t\t\tif ( ! empty( $response['redirect'] ) ) {\n\t\t\t\twp_redirect( $response['redirect'] );\n\t\t\t\texit();\n\t\t\t}\n\t\t}",
"\t\t/**\n\t\t * Complete lesson\n\t\t */\n\t\tpublic static function complete_lesson() {\n\t\t\t$nonce = LP_Request::get_string( 'complete-lesson-nonce' );\n\t\t\t$item_id = LP_Request::get_int( 'id' );\n\t\t\t$course_id = LP_Request::get_int( 'course_id' );",
"\t\t\t$post = get_post( $item_id );\n\t\t\t$user = learn_press_get_current_user();\n\t\t\t$course = learn_press_get_course( $course_id );\n\t\t\t$response = array(\n\t\t\t\t'result' => 'success',\n\t\t\t\t'redirect' => $course->get_item_link( $item_id ),\n\t\t\t);",
"\t\t\t$item = $course->get_item( $item_id );\n\t\t\t$nonce_action = $item->get_nonce_action( 'complete', $course_id, $user->get_id() );\n\t\t\ttry {\n\t\t\t\t// security check\n\t\t\t\tif ( ! $post || ( $post && ! wp_verify_nonce( $nonce, $nonce_action ) ) ) {\n\t\t\t\t\tthrow new Exception( __( 'Error! Invalid lesson or failed security check.', 'learnpress' ), 8000 );\n\t\t\t\t}",
"\t\t\t\t$result = $user->complete_lesson( $item_id );",
"\t\t\t\tif ( ! is_wp_error( $result ) ) {\n\t\t\t\t\tif ( $course->get_next_item() ) {\n\t\t\t\t\t\t$next = $course->get_next_item();\n\t\t\t\t\t\t$response['redirect'] = $course->get_item_link( $next );\n\t\t\t\t\t}",
"\t\t\t\t\tlearn_press_add_message( sprintf( __( 'Congrats! You have completed \"%s\".', 'learnpress' ), $item->get_title() ) );\n\t\t\t\t} else {\n\t\t\t\t\tlearn_press_add_message( $result->get_error_message(), 'error' );\n\t\t\t\t}",
"\t\t\t\t$response = apply_filters( 'learn-press/user-completed-lesson-result', $response, $item_id, $course_id, $user->get_id() );\n\t\t\t} catch ( Exception $ex ) {\n\t\t\t\tlearn_press_add_message( $ex->getMessage(), 'error' );\n\t\t\t}",
"\t\t\tif ( learn_press_message_count( 'error' ) ) {\n\t\t\t\t$response['result'] = 'error';\n\t\t\t}",
"\t\t\tlearn_press_maybe_send_json( $response );",
"\t\t\tif ( ! empty( $response['redirect'] ) ) {\n\t\t\t\t// wp_cache_flush();\n\t\t\t\twp_redirect( $response['redirect'] );\n\t\t\t\texit();\n\t\t\t}\n\t\t}",
"\t\t/**\n\t\t * Retake course action\n\t\t *\n\t\t * @TODO move this function to API\n\t\t */\n\t\t/*\n\t\tpublic static function retake_course() {\n\t\t\t$security = LP_Request::get_string( 'retake-course-nonce' );\n\t\t\t$course_id = LP_Request::get_int( 'retake-course' );\n\t\t\t$user = learn_press_get_current_user();\n\t\t\t$course = learn_press_get_course( $course_id );\n\t\t\t$response = array(\n\t\t\t\t'result' => 'error',\n\t\t\t);",
"\t\t\t$security_action = sprintf( 'retake-course-%d-%d', $course->get_id(), $user->get_id() );\n\t\t\t// security check\n\t\t\tif ( ! wp_verify_nonce( $security, $security_action ) ) {\n\t\t\t\tlearn_press_add_message( __( 'Error! Invalid course or failed security check.', 'learnpress' ),\n\t\t\t\t\t'error' );\n\t\t\t} else {\n\t\t\t\tif ( $user->can_retake_course( $course_id ) ) {\n\t\t\t\t\t$result = $user->retry_course( $course_id );",
"\t\t\t\t\tif ( ! $result ) {\n\t\t\t\t\t\tlearn_press_add_message( __( 'Error!', 'learnpress' ), 'error' );\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlearn_press_add_message( sprintf( __( 'You have retaken the course \"%s\"', 'learnpress' ),\n\t\t\t\t\t\t\t$course->get_title() ) );\n\t\t\t\t\t\t$response['result'] = 'success';\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlearn_press_add_message( __( 'Error! You can not retake the course', 'learnpress' ), 'error' );\n\t\t\t\t}\n\t\t\t}",
"\t\t\tif ( learn_press_message_count( 'error' ) == 0 ) {\n\t\t\t\t$item = $course->get_item_at( 0 );",
"\t\t\t\tif ( $item ) {\n\t\t\t\t\t$redirect = $course->get_item_link( $item );\n\t\t\t\t} else {\n\t\t\t\t\t$redirect = $course->get_permalink();\n\t\t\t\t}\n\t\t\t\t$response['redirect'] = apply_filters( 'learn-press/user-retake-course-redirect', $redirect );\n\t\t\t\t$response = apply_filters( 'learn-press/user-retaken-course-result', $response, $course_id,\n\t\t\t\t\t$user->get_id() );\n\t\t\t} else {\n\t\t\t\t$response['redirect'] = $course->get_permalink();\n\t\t\t\t$response = apply_filters( 'learn-press/user-retake-course-failed-result', $response,\n\t\t\t\t\t$course_id, $user->get_id() );\n\t\t\t}",
"\t\t\tlearn_press_maybe_send_json( $response );",
"\t\t\tif ( ! empty( $response['redirect'] ) ) {\n\t\t\t\twp_redirect( $response['redirect'] );\n\t\t\t\texit();\n\t\t\t}\n\t\t}*/\n\t}\n}",
"LP_AJAX::init();"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [61, 1262, 233, 1156], "buggy_code_start_loc": [27, 1198, 14, 1081], "filenames": ["assets/src/js/frontend/profile.js", "inc/admin/class-lp-admin-ajax.php", "inc/class-lp-ajax.php", "inc/user/lp-user-functions.php"], "fixing_code_end_loc": [71, 1364, 200, 1152], "fixing_code_start_loc": [27, 1199, 14, 1082], "message": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thimpress:learnpress:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "F74AC61D-6728-4759-B5A4-F03B9519485C", "versionEndExcluding": "4.1.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site."}, {"lang": "es", "value": "Los usuarios del plugin LearnPress de WordPress versiones anteriores a 4.1.5, pueden subir una imagen como avatar de perfil tras el registro. Tras este proceso, el usuario recorta y guarda la imagen. A continuaci\u00f3n, se env\u00eda al servidor una petici\u00f3n \"POST\" que contiene el nombre de la imagen suministrado por el usuario para cambiar el nombre y recortar la imagen. Como resultado de esta petici\u00f3n, el nombre de la imagen suministrada por el usuario es cambiada con un valor MD5. Este proceso s\u00f3lo puede llevarse a cabo cuando el tipo de la imagen es JPG o PNG. Un atacante puede usar esta vulnerabilidad para cambiar el nombre de un archivo de imagen arbitrario. Al hacer esto, podr\u00edan destruir el dise\u00f1o del sitio web."}], "evaluatorComment": null, "id": "CVE-2022-0377", "lastModified": "2022-03-08T16:39:46.640", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-28T09:15:09.093", "references": [{"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://bozogullarindan.com/en/2022/01/wordpress-learnpress-plugin-4.1.4.1-arbitrary-image-renaming/"}, {"source": "contact@wpscan.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, {"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://wpscan.com/vulnerability/0d95ada6-53e3-4a80-a395-eacd7b090f26"}], "sourceIdentifier": "contact@wpscan.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-610"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-73"}], "source": "contact@wpscan.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, "type": "CWE-610"}
| 263
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/**\n * Common functions to process actions about user\n *\n * @author ThimPress\n * @package LearnPress/Functions/User\n * @version 1.0\n */",
"function learn_press_get_user_profile_tabs() {\n\treturn LP_Profile::instance()->get_tabs();\n}",
"/**\n * Delete user data by user ID\n *\n * @param int $user_id\n * @param int $course_id\n */\nfunction learn_press_delete_user_data( $user_id, $course_id = 0 ) {\n\tglobal $wpdb;\n\t// TODO: Should be deleted user's order and order data???",
"\t$query_args = array( $user_id );",
"\tif ( $course_id ) {\n\t\t$query_args[] = $course_id;\n\t}",
"\t$query = $wpdb->prepare(\n\t\t\"\n SELECT user_item_id\n FROM {$wpdb->prefix}learnpress_user_items\n WHERE user_id = %d\n \" . ( $course_id ? ' AND item_id = %d' : '' ) . '\n ',\n\t\t$query_args\n\t);",
"\t// delete all courses user has enrolled\n\t$query = $wpdb->prepare(\n\t\t\"\n DELETE FROM {$wpdb->prefix}learnpress_user_items\n WHERE user_id = %d\n \" . ( $course_id ? ' AND item_id = %d' : '' ) . '\n ',\n\t\t$query_args\n\t);",
"\t@$wpdb->query( $query );\n}",
"/**\n * Get user_item_id field in table learnpress_user_items\n * with the user_id, item_id. If $course_id is not passed\n * then item_id is ID of a course. Otherwise, item_id is\n * ID of an item (like quiz/lesson).\n *\n * @param int $user_id\n * @param int $item_id\n * @param int $course_id\n *\n * @return bool\n * @editor tungnx\n * @reason this function only get cache, not handle get user_item_id\n */\nfunction learn_press_get_user_item_id( $user_id, $item_id, $course_id = 0 /* added 3.0.0 */ ) {\n\treturn false;\n}",
"/**\n * Get current user ID\n *\n * @return int\n */\nfunction learn_press_get_current_user_id() {\n\t$user = learn_press_get_current_user();",
"\treturn $user->get_id();\n}",
"/**\n * Get the user by $user_id passed. If $user_id is NULL, get current user.\n * If current user is not logged in, return a GUEST user\n *\n * @param bool $create_temp - Optional. Create temp user if user is not logged in.\n *\n * @return bool|LP_User|LP_User_Guest\n * @editor tungnx\n * @modify 4.1.4\n * @version 1.0.1\n */\nfunction learn_press_get_current_user( $create_temp = true ) {\n\t$user_id = get_current_user_id();",
"\tif ( $user_id ) {\n\t\treturn learn_press_get_user( $user_id );\n\t}",
"\t// Return LP_User_Guest\n\treturn learn_press_get_user( 0 );\n}",
"if ( ! function_exists( 'learn_press_get_user' ) ) {\n\t/**\n\t * Get user by ID. Return false if the user does not exists.\n\t *\n\t * @param int $user_id\n\t * @param bool $current\n\t *\n\t * @return LP_User|mixed\n\t * Todo: check this function - tungnx\n\t */\n\tfunction learn_press_get_user( $user_id, $current = false, $force_new = false ) {\n\t\t$is_guest = false;\n\t\tif ( $user_id != LP()->session->guest_user_id ) {\n\t\t\tif ( $current && ! get_user_by( 'id', $user_id ) ) {\n\t\t\t\t$user_id = get_current_user_id();\n\t\t\t}\n\t\t}",
"\t\tif ( ! $user_id && isset( LP()->session ) ) {\n\t\t\tif ( ! LP()->session->guest_user_id ) {\n\t\t\t\tLP()->session->set_customer_session_cookie( 1 );\n\t\t\t\tLP()->session->guest_user_id = time();\n\t\t\t}",
"\t\t\t$user_id = LP()->session->guest_user_id;\n\t\t\t$is_guest = true;\n\t\t}",
"\t\tif ( ! $user_id ) {\n\t\t\treturn false;\n\t\t}",
"\t\t$user_id = '' . $user_id;",
"\t\tif ( $force_new || ! array_key_exists( $user_id, LP_Global::$users ) ) {\n\t\t\t/**\n\t\t\t * LP Hook.\n\t\t\t *\n\t\t\t * Filter the default class name to get LP user.\n\t\t\t *\n\t\t\t * @since 3.3.0\n\t\t\t */\n\t\t\t$userClass = apply_filters( 'learn-press/user-class', $is_guest ? 'LP_User_Guest' : 'LP_User', $is_guest );",
"\t\t\tLP_Global::$users[ $user_id ] = new $userClass( $user_id );",
"\t\t\tdo_action( 'learn-press/get-user', LP_Global::$users[ $user_id ], $user_id );\n\t\t}",
"\t\treturn LP_Global::$users[ $user_id ];\n\t}\n}",
"/**\n * Add more 2 user roles teacher and student\n */\nfunction learn_press_add_user_roles() {",
"\t$settings = LP()->settings;",
"\t/* translators: user role */\n\t_x( 'LP Instructor', 'User role' );",
"\tadd_role(\n\t\tLP_TEACHER_ROLE,\n\t\t'LP Instructor',\n\t\tarray()\n\t);",
"\t$course_cap = LP_COURSE_CPT . 's';\n\t$lesson_cap = LP_LESSON_CPT . 's';\n\t$order_cap = LP_ORDER_CPT . 's';",
"\t$teacher = get_role( LP_TEACHER_ROLE );\n\tif ( $teacher ) {\n\t\t$teacher->add_cap( 'read_private_' . $course_cap );\n\t\t$teacher->add_cap( 'delete_published_' . $course_cap );\n\t\t$teacher->add_cap( 'edit_published_' . $course_cap );\n\t\t$teacher->add_cap( 'edit_' . $course_cap );\n\t\t$teacher->add_cap( 'delete_' . $course_cap );\n\t\t$teacher->add_cap( 'unfiltered_html' );",
"\t\t$settings->get( 'required_review' );",
"\t\tif ( $settings->get( 'required_review' ) == 'yes' ) {\n\t\t\t$teacher->remove_cap( 'publish_' . $course_cap );\n\t\t} else {\n\t\t\t$teacher->add_cap( 'publish_' . $course_cap );\n\t\t}",
"\t\t$teacher->add_cap( 'read_private_' . $lesson_cap );\n\t\t$teacher->add_cap( 'delete_published_' . $lesson_cap );\n\t\t$teacher->add_cap( 'edit_published_' . $lesson_cap );\n\t\t$teacher->add_cap( 'edit_' . $lesson_cap );\n\t\t$teacher->add_cap( 'delete_' . $lesson_cap );\n\t\t$teacher->add_cap( 'publish_' . $lesson_cap );\n\t\t$teacher->add_cap( 'upload_files' );\n\t\t$teacher->add_cap( 'read' );\n\t\t$teacher->add_cap( 'edit_posts' );\n\t}",
"\t// administrator\n\t$admin = get_role( 'administrator' );\n\tif ( $admin ) {\n\t\t$admin->add_cap( 'read_private_' . $course_cap );\n\t\t$admin->add_cap( 'delete_' . $course_cap );\n\t\t$admin->add_cap( 'delete_published_' . $course_cap );\n\t\t$admin->add_cap( 'edit_' . $course_cap );\n\t\t$admin->add_cap( 'edit_published_' . $course_cap );\n\t\t$admin->add_cap( 'publish_' . $course_cap );\n\t\t$admin->add_cap( 'delete_private_' . $course_cap );\n\t\t$admin->add_cap( 'edit_private_' . $course_cap );\n\t\t$admin->add_cap( 'delete_others_' . $course_cap );\n\t\t$admin->add_cap( 'edit_others_' . $course_cap );",
"\t\t$admin->add_cap( 'read_private_' . $lesson_cap );\n\t\t$admin->add_cap( 'delete_' . $lesson_cap );\n\t\t$admin->add_cap( 'delete_published_' . $lesson_cap );\n\t\t$admin->add_cap( 'edit_' . $lesson_cap );\n\t\t$admin->add_cap( 'edit_published_' . $lesson_cap );\n\t\t$admin->add_cap( 'publish_' . $lesson_cap );\n\t\t$admin->add_cap( 'delete_private_' . $lesson_cap );\n\t\t$admin->add_cap( 'edit_private_' . $lesson_cap );\n\t\t$admin->add_cap( 'delete_others_' . $lesson_cap );\n\t\t$admin->add_cap( 'edit_others_' . $lesson_cap );",
"\t\t$admin->add_cap( 'delete_' . $order_cap );\n\t\t$admin->add_cap( 'delete_published_' . $order_cap );\n\t\t$admin->add_cap( 'edit_' . $order_cap );\n\t\t$admin->add_cap( 'edit_published_' . $order_cap );\n\t\t$admin->add_cap( 'publish_' . $order_cap );\n\t\t$admin->add_cap( 'delete_private_' . $order_cap );\n\t\t$admin->add_cap( 'edit_private_' . $order_cap );\n\t\t$admin->add_cap( 'delete_others_' . $order_cap );\n\t\t$admin->add_cap( 'edit_others_' . $order_cap );\n\t}\n}",
"add_action( 'init', 'learn_press_add_user_roles' );",
"/**\n * @param null $user_id\n * @param array $args\n *\n * @return mixed\n */\nfunction learn_press_get_user_questions( $user_id = null, $args = array() ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}",
"\treturn learn_press_get_user( $user_id )->get_questions( $args );\n}",
"/**\n * Get the type of current user\n *\n * @param null $check_type\n *\n * @return bool|string\n */\nfunction learn_press_current_user_is( $check_type = null ) {\n\tglobal $current_user;\n\t$user_roles = $current_user->roles;\n\t$user_type = '';",
"\tif ( in_array( 'lpr_teacher', $user_roles ) ) {\n\t\t$user_type = 'instructor';\n\t} elseif ( in_array( 'lp_teacher', $user_roles ) ) {\n\t\t$user_type = 'instructor';\n\t} elseif ( in_array( 'administrator', $user_roles ) ) {\n\t\t$user_type = 'administrator';\n\t}",
"\treturn $check_type ? $check_type == $user_type : $user_type;\n}",
"function learn_press_user_has_roles( $roles, $user_id = null ) {\n\t$has_role = false;\n\tif ( ! $user_id ) {\n\t\t$user = wp_get_current_user();\n\t} else {\n\t\t$user = get_user_by( 'id', $user_id );\n\t}\n\t$available_roles = (array) $user->roles;\n\tif ( is_array( $roles ) ) {\n\t\tforeach ( $roles as $role ) {\n\t\t\tif ( in_array( $role, $available_roles ) ) {\n\t\t\t\t$has_role = true;\n\t\t\t\tbreak; // only need one of roles is in available\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif ( in_array( $roles, $available_roles ) ) {\n\t\t\t$has_role = true;\n\t\t}\n\t}",
"\treturn $has_role;\n}",
"/**\n * Add user profile link into admin bar\n */\nfunction learn_press_edit_admin_bar() {\n\tglobal $wp_admin_bar;",
"\t$profile = learn_press_get_page_id( 'profile' );",
"\tif ( $profile && learn_press_get_post_type( $profile ) == 'page' && get_post_status( $profile ) != 'trash' ) {\n\t\t$user_id = learn_press_get_current_user_id();",
"\t\t$wp_admin_bar->add_menu(\n\t\t\tarray(\n\t\t\t\t'id' => 'course_profile',\n\t\t\t\t'parent' => 'user-actions',\n\t\t\t\t'title' => get_the_title( $profile ),\n\t\t\t\t'href' => learn_press_user_profile_link( $user_id, false ),\n\t\t\t)\n\t\t);\n\t}",
"\t$current_user = wp_get_current_user();",
"\tif ( in_array( LP_TEACHER_ROLE, $current_user->roles ) || in_array( 'administrator', $current_user->roles ) ) {\n\t\treturn;\n\t}\n}",
"add_action( 'admin_bar_menu', 'learn_press_edit_admin_bar' );",
"function learn_press_current_user_can_view_profile_section( $section, $user ) {\n\t$current_user = wp_get_current_user();\n\t$view = true;\n\tif ( $user->get_data( 'user_login' ) != $current_user->user_login && $section == LP()->settings->get(\n\t\t'profile_endpoints.profile-orders',\n\t\t'profile-orders'\n\t) ) {\n\t\t$view = false;\n\t}",
"\treturn apply_filters( 'learn_press_current_user_can_view_profile_section', $view, $section, $user );\n}",
"function learn_press_profile_tab_courses_content( $current, $tab, $user ) {\n\tlearn_press_get_template(\n\t\t'profile/tabs/courses.php',\n\t\tarray(\n\t\t\t'user' => $user,\n\t\t\t'current' => $current,\n\t\t\t'tab' => $tab,\n\t\t)\n\t);\n}",
"function learn_press_profile_tab_quizzes_content( $current, $tab, $user ) {\n\tlearn_press_get_template(\n\t\t'profile/tabs/quizzes.php',\n\t\tarray(\n\t\t\t'user' => $user,\n\t\t\t'current' => $current,\n\t\t\t'tab' => $tab,\n\t\t)\n\t);\n}",
"function learn_press_profile_tab_orders_content( $current, $tab, $user ) {\n\tlearn_press_get_template(\n\t\t'profile/tabs/orders.php',\n\t\tarray(\n\t\t\t'user' => $user,\n\t\t\t'current' => $current,\n\t\t\t'tab' => $tab,\n\t\t)\n\t);\n}",
"/**\n * Get queried user in profile link\n *\n * @return false|WP_User\n * @since 3.0.0\n */\nfunction learn_press_get_profile_user() {\n\treturn LP_Profile::get_queried_user();\n}",
"\n/**\n * Add instructor registration button to register page and admin bar\n */\nfunction learn_press_user_become_teacher_registration_form() {\n\tif ( LP()->settings->get( 'instructor_registration' ) != 'yes' ) {\n\t\treturn;\n\t}\n\t?>\n\t<p>\n\t\t<label for=\"become_teacher\">\n\t\t\t<input type=\"checkbox\" name=\"become_teacher\" id=\"become_teacher\">\n\t\t\t<?php esc_html_e( 'Want to become an instructor?', 'learnpress' ); ?>\n\t\t</label>\n\t</p>\n\t<?php\n}",
"add_action( 'register_form', 'learn_press_user_become_teacher_registration_form' );",
"/**\n * Update data into table learnpress_user_items.\n *\n * @param array $fields - Fields and values to be updated.\n * Format: array(\n * field_name_1 => value 1,\n * field_name_2 => value 2,\n * ....\n * field_name_n => value n\n * )\n * @param mixed $where - Optional. Fields with values for conditional update with the same format of $fields.\n * @param bool $update_cache - Optional. Should be update to cache or not (since 3.0.0).\n * @param bool $update_extra_fields_as_meta - Optional. Update extra fields as item meta (since 3.1.0).\n *\n * @return mixed\n */\nfunction learn_press_update_user_item_field( $fields, $where = false, $update_cache = true, $update_extra_fields_as_meta = false ) {\n\tglobal $wpdb;",
"\t// Table fields\n\t$table_fields = array(\n\t\t'user_id' => '%d',\n\t\t'item_id' => '%d',\n\t\t'ref_id' => '%d',\n\t\t'start_time' => '%s',\n\t\t'end_time' => '%s',\n\t\t'access_level' => '%d',\n\t\t'graduation' => '%s',\n\t\t'item_type' => '%s',\n\t\t'status' => '%s',\n\t\t'ref_type' => '%s',\n\t\t'parent_id' => '%d',\n\t);",
"\t/**\n\t * Validate item status\n\t */\n\tif ( ! empty( $fields['item_id'] ) && ! empty( $fields['status'] ) ) {\n\t\t$item_type = learn_press_get_post_type( $fields['item_id'] );",
"\t\tif ( LP_COURSE_CPT === $item_type ) {\n\t\t\tif ( 'completed' === $fields['status'] ) {\n\t\t\t\t$fields['status'] = 'finished';\n\t\t\t}\n\t\t} else {\n\t\t\tif ( 'finished' === $fields['status'] ) {\n\t\t\t\t$fields['status'] = 'completed';\n\t\t\t}\n\t\t}\n\t}",
"\t$data = array();\n\t$data_format = array();\n\t$date_time_fields = array(\n\t\t'start_time',\n\t\t'end_time',\n\t);",
"\tforeach ( $fields as $field => $value ) {\n\t\tif ( ! empty( $table_fields[ $field ] ) ) {\n\t\t\t$data[ $field ] = $value;",
"\t\t\t// Do not format the date-time field if it's value is NULL\n\t\t\tif ( in_array( $field, $date_time_fields ) && ! $value ) {\n\t\t\t\t$data[ $field ] = null;\n\t\t\t\t$data_format[] = '';\n\t\t\t} else {\n\t\t\t\t$data_format[] = $table_fields[ $field ];\n\t\t\t}\n\t\t}\n\t}",
"\tif ( ! empty( $fields['user_item_id'] ) ) {\n\t\t$where = wp_parse_args(\n\t\t\t$where,\n\t\t\tarray( 'user_item_id' => $fields['user_item_id'] )\n\t\t);\n\t}",
"\tif ( $where && empty( $where['user_id'] ) ) {\n\t\t$where['user_id'] = ! empty( $fields['user_id'] ) ? $fields['user_id'] : learn_press_get_current_user_id();\n\t}",
"\t$where_format = array();",
"\t// Build where and where format\n\tif ( $where ) {\n\t\tforeach ( $where as $field => $value ) {\n\t\t\tif ( ! empty( $table_fields[ $field ] ) ) {\n\t\t\t\t$where_format[] = $table_fields[ $field ];\n\t\t\t}\n\t\t}\n\t}",
"\tif ( ! $data ) {\n\t\treturn false;\n\t}",
"\t$inserted = false;\n\t$updated = false;",
"\t// Ensure all fields are instance of LP_Datetime have to\n\t// convert to string of datetime.\n\tforeach ( $data as $k => $v ) {\n\t\tif ( $v instanceof LP_Datetime ) {\n\t\t\t$data[ $k ] = $v->toSql();\n\t\t}\n\t}",
"\t// If $where is not empty consider we are updating\n\tif ( $where ) {\n\t\t$updated = $wpdb->update(\n\t\t\t$wpdb->learnpress_user_items,\n\t\t\t$data,\n\t\t\t$where,\n\t\t\t$data_format,\n\t\t\t$where_format\n\t\t);\n\t} else {",
"\t\t// Otherwise, insert a new one\n\t\tif ( $wpdb->insert(\n\t\t\t$wpdb->learnpress_user_items,\n\t\t\t$data,\n\t\t\t$data_format\n\t\t)\n\t\t) {\n\t\t\t$inserted = $wpdb->insert_id;\n\t\t}\n\t}",
"\tif ( $updated && ! empty( $where['user_item_id'] ) ) {\n\t\t$inserted = $where['user_item_id'];\n\t}",
"\t/**\n\t * @var object|bool $updated_item\n\t */\n\t$updated_item = false;",
"\t// Get the item we just have updated or inserted.\n\tif ( $inserted ) {\n\t\t$updated_item = learn_press_get_user_item( $inserted );\n\t} elseif ( $updated ) {\n\t\t$updated_item = learn_press_get_user_item( $where );\n\t}",
"\t/**\n\t * If there is some fields does not contain in the main table\n\t * then consider update them as meta data.\n\t */\n\tif ( $updated_item && $update_extra_fields_as_meta ) {\n\t\t$extra_fields = array_diff_key( $fields, $table_fields );\n\t\tif ( $extra_fields ) {\n\t\t\tforeach ( $extra_fields as $meta_key => $meta_value ) {\n\t\t\t\tif ( $meta_value == 'user_item_id' ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}",
"\t\t\t\tif ( $meta_value === false ) {\n\t\t\t\t\tlearn_press_delete_user_item_meta( $updated_item->user_item_id, $meta_key );\n\t\t\t\t} else {",
"\t\t\t\t\tif ( empty( $meta_value ) ) {\n\t\t\t\t\t\t$meta_value = '';\n\t\t\t\t\t}\n\t\t\t\t\tlearn_press_update_user_item_meta( $updated_item->user_item_id, $meta_key, $meta_value );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\tdo_action( 'learn-press/updated-user-item-meta', $updated_item );",
"\treturn $updated_item;\n}",
"/**\n * Get user item row(s) from user items table by multiple WHERE conditional\n *\n * @param array|int $where\n * @param bool $single\n *\n * @return array\n */\nfunction learn_press_get_user_item( $where, $single = true ) {\n\tglobal $wpdb;",
"\t// Table fields\n\t$table_fields = array(\n\t\t'user_item_id' => '%d',\n\t\t'user_id' => '%d',\n\t\t'item_id' => '%d',\n\t\t'ref_id' => '%d',\n\t\t'start_time' => '%s',\n\t\t'end_time' => '%s',\n\t\t'item_type' => '%s',\n\t\t'status' => '%s',\n\t\t'ref_type' => '%s',\n\t\t'parent_id' => '%d',\n\t);",
"\t// If $where is a number consider we are searching the record with unique user_item_id\n\tif ( is_numeric( $where ) ) {\n\t\t$where = array( 'user_item_id' => $where );\n\t}",
"\t$where_str = array();\n\tforeach ( $where as $field => $value ) {\n\t\tif ( ! empty( $table_fields[ $field ] ) ) {\n\t\t\t$where_str[] = \"{$field} = \" . $table_fields[ $field ];\n\t\t}\n\t}\n\t$item = false;",
"\tif ( $where_str ) {\n\t\t$query = $wpdb->prepare(\n\t\t\t\"\n\t\t\tSELECT *\n\t\t\tFROM {$wpdb->prefix}learnpress_user_items\n\t\t\tWHERE \" . join( ' AND ', $where_str ) . '\n\t\t\tORDER BY user_item_id DESC\n\t\t',\n\t\t\t$where\n\t\t);\n\t\tif ( $single || ! empty( $where['user_item_id'] ) ) {\n\t\t\t$item = $wpdb->get_row( $query );\n\t\t} else {\n\t\t\t$item = $wpdb->get_results( $query );\n\t\t}\n\t}",
"\treturn $item;\n}",
"/**\n * Get user item meta from user_itemmeta table\n *\n * @param int $user_item_id .\n * @param string $meta_key .\n * @param bool $single .\n *\n * @return mixed\n */\nfunction learn_press_get_user_item_meta( $user_item_id = 0, $meta_key = '', $single = true ) {\n\t$meta = false;\n\tif ( metadata_exists( 'learnpress_user_item', $user_item_id, $meta_key ) ) {\n\t\t$meta = get_metadata( 'learnpress_user_item', $user_item_id, $meta_key, $single );\n\t}",
"\treturn $meta;\n}",
"/**\n * Add user item meta into table user_itemmeta\n *\n * @param int $user_item_id\n * @param string $meta_key\n * @param mixed $meta_value\n * @param string $prev_value\n *\n * @return false|int\n */\nfunction learn_press_add_user_item_meta( $user_item_id, $meta_key, $meta_value, $prev_value = '' ) {\n\treturn add_metadata( 'learnpress_user_item', $user_item_id, $meta_key, $meta_value, $prev_value );\n}",
"/**\n * Update user item meta to table user_itemmeta\n *\n * @param int $user_item_id\n * @param string $meta_key\n * @param mixed $meta_value\n * @param string $prev_value\n *\n * @return bool|int\n */\nfunction learn_press_update_user_item_meta( $user_item_id, $meta_key, $meta_value, $prev_value = '' ) {\n\treturn update_metadata( 'learnpress_user_item', $user_item_id, $meta_key, $meta_value, $prev_value );\n}",
"\n/**\n * Update user item meta to table user_itemmeta\n *\n * @param int $object_id\n * @param string $meta_key\n * @param mixed $meta_value\n * @param bool $delete_all\n *\n * @return bool|int\n */\nfunction learn_press_delete_user_item_meta( $object_id, $meta_key, $meta_value = '', $delete_all = false ) {\n\treturn delete_metadata( 'learnpress_user_item', $object_id, $meta_key, $meta_value, $delete_all );\n}",
"/**\n * Exclude the temp users from query.\n *\n * @param WP_User_Query $q\n */\nfunction learn_press_filter_temp_users( $q ) {\n\t// if ( $temp_users = learn_press_get_temp_users() ) {\n\t// $exclude = (array) $q->get( 'exclude' );\n\t// $exclude = array_merge( $exclude, $temp_users );\n\t// $q->set( 'exclude', $exclude );\n\t// }\n}",
"// add_action( 'pre_get_users', 'learn_press_filter_temp_users' );",
"/**\n * Get temp users.\n *\n * @return array\n */\nfunction learn_press_get_temp_users() {\n\treturn false;\n\tif ( false === ( $temp_users = LP_Object_Cache::get( 'learn-press/temp-users' ) ) ) {\n\t\tglobal $wpdb;\n\t\t$query = $wpdb->prepare(\n\t\t\t\"\n\t\t\tSELECT ID\n\t\t\tFROM {$wpdb->users} u\n\t\t\tINNER JOIN {$wpdb->usermeta} um ON u.ID = um.user_id AND um.meta_key = %s AND um.meta_value = %s\n\t\t\tLEFT JOIN {$wpdb->usermeta} um2 ON u.ID = um2.user_id AND um2.meta_key = %s\n\t\t\",\n\t\t\t'_lp_temp_user',\n\t\t\t'yes',\n\t\t\t'_lp_expiration'\n\t\t);",
"\t\t$temp_users = $wpdb->get_col( $query );",
"\t\tLP_Object_Cache::set( 'learn-press/temp-users', $temp_users );\n\t}",
"\treturn $temp_users;\n}",
"/**\n * Update field created_time after added user item meta\n *\n * @use updated_{meta_type}_meta hook\n *\n * @param $meta_id\n * @param $object_id\n * @param $meta_key\n * @param $_meta_value\n */\nfunction _learn_press_update_created_time_user_item_meta( $meta_id, $object_id, $meta_key, $_meta_value ) {\n\tglobal $wpdb;\n\t$wpdb->update(\n\t\t$wpdb->learnpress_user_itemmeta,\n\t\tarray( 'create_time' => current_time( 'mysql' ) ),\n\t\tarray( 'meta_id' => $meta_id ),\n\t\tarray( '%s' ),\n\t\tarray( '%d' )\n\t);\n}",
"// add_action( 'added_learnpress_user_item_meta', '_learn_press_update_created_time_user_item_meta', 10, 4 );",
"/**\n * Update field updated_time after updated user item meta\n *\n * @use updated_{meta_type}_meta hook\n *\n * @param $meta_id\n * @param $object_id\n * @param $meta_key\n * @param $_meta_value\n */\nfunction _learn_press_update_updated_time_user_item_meta( $meta_id, $object_id, $meta_key, $_meta_value ) {\n\tglobal $wpdb;\n\t$wpdb->update(\n\t\t$wpdb->learnpress_user_itemmeta,\n\t\tarray( 'update_time' => current_time( 'mysql' ) ),\n\t\tarray( 'meta_id' => $meta_id ),\n\t\tarray( '%s' ),\n\t\tarray( '%d' )\n\t);\n}",
"// add_action( 'updated_learnpress_user_item_meta', '_learn_press_update_updated_time_user_item_meta', 10, 4 );",
"/**\n * @param $status\n * @param int $quiz_id\n * @param int $user_id\n * @param int $course_id\n *\n * @return bool|mixed\n */\nfunction learn_press_user_has_quiz_status( $status, $quiz_id = 0, $user_id = 0, $course_id = 0 ) {\n\t$user = learn_press_get_user( $user_id );",
"\treturn $user->has_quiz_status( $status, $quiz_id, $course_id );\n}",
"if ( ! function_exists( 'learn_press_pre_get_avatar_callback' ) ) {\n\t/**\n\t * Filter the avatar\n\t *\n\t * @param string $avatar\n\t * @param string $id_or_email\n\t * @param array $size\n\t *\n\t * @return string\n\t */\n\tfunction learn_press_pre_get_avatar_callback( $avatar, $id_or_email = '', $size = array() ) {",
"\t\t$profile = LP_Profile::instance();",
"\t\tif ( ! $profile->is_enable_avatar() ) {\n\t\t\treturn $avatar;\n\t\t}",
"\t\tif ( ( isset( $size['gravatar'] ) && $size['gravatar'] ) || ( $size['default'] && $size['force_default'] ) ) {\n\t\t\treturn $avatar;\n\t\t}",
"\t\t$user_id = 0;",
"\t\t/**\n\t\t * Get the ID of user from $id_or_email\n\t\t */\n\t\tif ( ! is_numeric( $id_or_email ) && is_string( $id_or_email ) ) {\n\t\t\tif ( $user = get_user_by( 'email', $id_or_email ) ) {\n\t\t\t\t$user_id = $user->ID;\n\t\t\t}\n\t\t} elseif ( is_numeric( $id_or_email ) ) {\n\t\t\t$user_id = $id_or_email;\n\t\t} elseif ( is_object( $id_or_email ) && isset( $id_or_email->user_id ) && $id_or_email->user_id ) {\n\t\t\t$user_id = $id_or_email->user_id;\n\t\t} elseif ( is_object( $id_or_email ) && $id_or_email instanceof WP_Comment ) {\n\t\t\tif ( $user = get_user_by( 'email', $id_or_email->comment_author_email ) ) {\n\t\t\t\t$user_id = $user->ID;\n\t\t\t}\n\t\t}",
"\t\tif ( ! $user_id ) {\n\t\t\treturn $avatar;\n\t\t}",
"\t\t$user = LP_User_Factory::get_user( $user_id );",
"\t\t$profile_picture_src = $user->get_upload_profile_src();\n\t\tif ( $profile_picture_src ) {\n\t\t\t$setting_size = learn_press_get_avatar_thumb_size();\n\t\t\t$img_size = '';",
"\t\t\t// Get avatar size\n\t\t\tif ( ! is_array( $size ) ) {\n\t\t\t\tif ( $size === 'thumbnail' ) {\n\t\t\t\t\t$img_size = '';\n\t\t\t\t\t$height = $setting_size['height'];\n\t\t\t\t\t$width = $setting_size['width'];\n\t\t\t\t} else {\n\t\t\t\t\t$height = 250;\n\t\t\t\t\t$width = 250;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$img_size = $size['size'];\n\t\t\t\t$height = $size['height'];\n\t\t\t\t$width = $size['width'];\n\t\t\t}",
"\t\t\t$avatar = '<img alt=\"' . esc_attr( $user->get_data( 'display_name' ) ) . '\" src=\"' . esc_url( $profile_picture_src ) . '\" class=\"avatar avatar-' . $img_size . ' photo\" height=\"' . $height . '\" width=\"' . $width . '\" />';\n\t\t}",
"\t\treturn $avatar;\n\t}\n}\nadd_filter( 'pre_get_avatar', 'learn_press_pre_get_avatar_callback', 1, 5 );",
"\nfunction learn_press_user_profile_picture_upload_dir( $width_user = true ) {\n\tstatic $upload_dir;\n\tif ( ! $upload_dir ) {\n\t\t$upload_dir = wp_upload_dir();\n\t\t$subdir = apply_filters( 'learn_press_user_profile_folder', 'learn-press-profile', $width_user );\n\t\tif ( $width_user ) {\n\t\t\t$subdir .= '/' . get_current_user_id();\n\t\t}\n\t\t$subdir = '/' . $subdir;",
"\t\tif ( ! empty( $upload_dir['subdir'] ) ) {\n\t\t\t$u_subdir = str_replace( '\\\\', '/', $upload_dir['subdir'] );\n\t\t\t$u_path = str_replace( '\\\\', '/', $upload_dir['path'] );",
"\t\t\t$upload_dir['path'] = str_replace( $u_subdir, $subdir, $u_path );\n\t\t\t$upload_dir['url'] = str_replace( $u_subdir, $subdir, $upload_dir['url'] );\n\t\t} else {\n\t\t\t$upload_dir['path'] = $upload_dir['path'] . $subdir;\n\t\t\t$upload_dir['url'] = $upload_dir['url'] . $subdir;\n\t\t}",
"\t\t$upload_dir['subdir'] = $subdir;",
"\t\t// Point path/url to main site if we are in multisite\n\t\tif ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {\n\t\t\tforeach ( array( 'path', 'url', 'basedir', 'baseurl' ) as $v ) {\n\t\t\t\t$upload_dir[ $v ] = str_replace( '/sites/' . get_current_blog_id(), '', $upload_dir[ $v ] );\n\t\t\t}\n\t\t}\n\t}",
"\treturn $upload_dir;\n}",
"add_action( 'learn_press_before_purchase_course_handler', '_learn_press_before_purchase_course_handler', 10, 2 );\nfunction _learn_press_before_purchase_course_handler( $course_id, $cart ) {\n\t// Redirect to login page if user is not logged in\n\tif ( ! is_user_logged_in() ) {\n\t\t$return_url = add_query_arg( $_POST, get_the_permalink( $course_id ) );\n\t\t$return_url = apply_filters( 'learn_press_purchase_course_login_redirect_return_url', $return_url );\n\t\t$redirect = apply_filters(\n\t\t\t'learn_press_purchase_course_login_redirect',\n\t\t\tlearn_press_get_login_url( $return_url )\n\t\t);\n\t\tif ( $redirect !== false ) {\n\t\t\tlearn_press_add_message( __( 'Please login to enroll this course', 'learnpress' ) );",
"\t\t\tif ( learn_press_is_ajax() ) {\n\t\t\t\tlearn_press_send_json(\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'redirect' => $redirect,\n\t\t\t\t\t\t'result' => 'success',\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\twp_redirect( $redirect );\n\t\t\t\texit();\n\t\t\t}\n\t\t}\n\t} else {\n\t\t$user = learn_press_get_current_user();\n\t\t$redirect = false;\n\t\tif ( $user->has_finished_course( $course_id ) ) {\n\t\t\tlearn_press_add_message( __( 'You have already finished course', 'learnpress' ) );\n\t\t\t$redirect = true;\n\t\t} elseif ( $user->has_purchased_course( $course_id ) ) {\n\t\t\tlearn_press_add_message( __( 'You have already enrolled in this course', 'learnpress' ) );\n\t\t\t$redirect = true;\n\t\t}\n\t\tif ( $redirect ) {\n\t\t\twp_redirect( get_the_permalink( $course_id ) );\n\t\t\texit();\n\t\t}\n\t}\n}",
"function learn_press_user_is( $role, $user_id = 0 ) {\n\tif ( ! $user_id ) {\n\t\t$user = learn_press_get_current_user();\n\t} else {\n\t\t$user = learn_press_get_user( $user_id );\n\t}\n\tif ( $role == 'admin' ) {\n\t\treturn $user->is_admin();\n\t}\n\tif ( $role == 'instructor' ) {\n\t\treturn $user->is_instructor();\n\t}",
"\treturn $role;\n}",
"function learn_press_profile_tab_edit_content( $current, $tab, $user ) {\n\tlearn_press_get_template(\n\t\t'profile/tabs/edit.php',\n\t\tarray(\n\t\t\t'user' => $user,\n\t\t\t'current' => $current,\n\t\t\t'tab' => $tab,\n\t\t)\n\t);\n}",
"function learn_press_get_profile_endpoints() {\n\t$endpoints = (array) LP()->settings->get( 'profile_endpoints' );\n\tif ( $tabs = LP_Profile::instance()->get_tabs() ) {\n\t\tforeach ( $tabs as $slug => $info ) {\n\t\t\tif ( empty( $endpoints[ $slug ] ) ) {\n\t\t\t\t$endpoints[ $slug ] = $slug;\n\t\t\t}\n\t\t}\n\t}",
"\treturn apply_filters( 'learn_press_profile_tab_endpoints', $endpoints );\n}",
"\nfunction learn_press_update_user_option( $name, $value, $id = 0 ) {\n\tif ( ! $id ) {\n\t\t$id = get_current_user_id();\n\t}\n\t$key = 'learnpress_user_options';\n\t$options = get_user_option( $key, $id );\n\t$options[ $name ] = $value;\n\tupdate_user_option( $id, $key, $options, true );\n}",
"/**\n * @param $name\n * @param int $id\n *\n * @return bool\n */\nfunction learn_press_delete_user_option( $name, $id = 0 ) {\n\tif ( ! $id ) {\n\t\t$id = get_current_user_id();\n\t}\n\t$key = 'learnpress_user_options';\n\t$options = get_user_option( $key, $id );\n\tif ( is_array( $options ) && array_key_exists( $name, $options ) ) {\n\t\tunset( $options[ $name ] );\n\t\tupdate_user_option( $id, $key, $options, true );",
"\t\treturn true;\n\t}",
"\treturn false;\n}",
"/**\n * @param $name\n * @param int $id\n *\n * @return bool\n */\nfunction learn_press_get_user_option( $name, $id = 0 ) {\n\tif ( ! $id ) {\n\t\t$id = get_current_user_id();\n\t}\n\t$key = 'learnpress_user_options';\n\t$options = get_user_option( $key, $id );\n\tif ( is_array( $options ) && array_key_exists( $name, $options ) ) {\n\t\treturn $options[ $name ];\n\t}",
"\treturn false;\n}",
"/**\n * Check and update user information from request in user profile page\n */\nfunction learn_press_update_user_profile() {",
"\tif ( ! LP()->is_request( 'post' ) ) {\n\t\treturn;\n\t}\n\t$nonce = learn_press_get_request( 'profile-nonce' );",
"\tif ( ! wp_verify_nonce( $nonce, 'learn-press-update-user-profile-' . get_current_user_id() ) ) {\n\t\treturn;\n\t}\n\t$section = learn_press_get_request( 'lp-profile-section' );",
"\tdo_action( 'learn_press_update_user_profile_' . $section );\n\tdo_action( 'learn_press_update_user_profile', $section );\n}",
"// add_action( 'init', 'learn_press_update_user_profile' );",
"/**\n * Update user avatar\n */\nfunction learn_press_update_user_profile_avatar() {\n\t$user_id = get_current_user_id();",
"",
"\n\tif ( ! $user_id ) {\n\t\treturn new WP_Error( 2, 'User is invalid!' );\n\t}",
"\t$upload_dir = learn_press_user_profile_picture_upload_dir();",
"\tif ( learn_press_get_request( 'lp-user-avatar-custom' ) != 'yes' ) {\n\t\tdelete_user_meta( get_current_user_id(), '_lp_profile_picture' );",
"\t\treturn false;\n\t}\n",
"\t$data = learn_press_get_request( 'lp-user-avatar-crop' );",
"\tif ( ! $data || ! ( $path = $upload_dir['basedir'] . $data['name'] ) && file_exists( $path ) ) {",
"\t\treturn false;\n\t}",
"\t$filetype = wp_check_filetype( $path );",
"\tif ( 'jpg' == $filetype['ext'] ) {\n\t\t$im = imagecreatefromjpeg( $path );\n\t} elseif ( 'png' == $filetype['ext'] ) {\n\t\t$im = imagecreatefrompng( $path );\n\t}",
"\tif ( ! isset( $im ) ) {\n\t\treturn false;\n\t}",
"\t$points = explode( ',', $data['points'] );\n\t$im_crop = imagecreatetruecolor( $data['width'], $data['height'] );",
"\tif ( ! $im ) {\n\t\treturn false;\n\t}",
"\t$dst_x = 0;\n\t$dst_y = 0;\n\t$dst_w = $data['width'];\n\t$dst_h = $data['height'];\n\t$src_x = $points[0];\n\t$src_y = $points[1];\n\t$src_w = $points[2] - $points[0];\n\t$src_h = $points[3] - $points[1];",
"\timagecopyresampled( $im_crop, $im, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );",
"\t$newname = md5( $user_id . microtime( true ) );\n\t$output = dirname( $path );",
"\tif ( 'jpg' == $filetype['ext'] ) {\n\t\t$newname .= '.jpg';\n\t\t$output .= '/' . $newname;\n\t\timagejpeg( $im_crop, $output );\n\t} elseif ( 'png' == $filetype['ext'] ) {\n\t\t$newname .= '.png';\n\t\t$output .= '/' . $newname;\n\t\timagepng( $im_crop, $output );\n\t}",
"\t$new_avatar = false;",
"\tif ( file_exists( $output ) ) {",
"\n\t\t$old_avatar = get_user_meta( $user_id, '_lp_profile_picture', true );",
"\t\tif ( file_exists( $upload_dir['basedir'] . '/' . $old_avatar ) ) {\n\t\t\t@unlink( $upload_dir['basedir'] . '/' . $old_avatar );\n\t\t}\n",
"\t\t$new_avatar = preg_replace( '!^/!', '', $upload_dir['subdir'] ) . '/' . $newname;",
"\t\tupdate_user_meta( $user_id, '_lp_profile_picture', $new_avatar );",
"\t\tupdate_user_meta( $user_id, '_lp_profile_picture_changed', 'yes' );",
"\t\t$new_avatar = $upload_dir['baseurl'] . '/' . $new_avatar;\n\t}",
"\t@unlink( $path );",
"\treturn $new_avatar;\n}",
"// add_action( 'learn_press_update_user_profile_avatar', 'learn_press_update_user_profile_avatar' );",
"/**\n * Update user basic information.\n *\n * @param bool $wp_error - Optional. Return WP_Error object in case updating failed.\n *\n * @return bool|mixed|WP_Error\n */\nfunction learn_press_update_user_profile_basic_information( $wp_error = false ) {\n\t$user_id = get_current_user_id();",
"\tif ( ! $user_id ) {\n\t\treturn new WP_Error( 2, 'User is invalid!' );\n\t}",
"\t$update_data = array(\n\t\t'ID' => $user_id,\n\t\t'first_name' => filter_input( INPUT_POST, 'first_name', FILTER_SANITIZE_STRING ),\n\t\t'last_name' => filter_input( INPUT_POST, 'last_name', FILTER_SANITIZE_STRING ),\n\t\t'description' => filter_input( INPUT_POST, 'description', FILTER_SANITIZE_STRING ),\n\t\t'display_name' => filter_input( INPUT_POST, 'account_display_name', FILTER_SANITIZE_STRING ),\n\t\t'user_email' => filter_input( INPUT_POST, 'account_email', FILTER_SANITIZE_EMAIL ),\n\t);",
"\t$update_data = apply_filters( 'learn-press/update-profile-basic-information-data', $update_data );\n\t$update_meta = isset( $_POST['_lp_custom_register'] ) ? LP_Helper::sanitize_params_submitted( $_POST['_lp_custom_register'] ) : '';",
"\t$return = LP_Forms_Handler::update_user_data( $update_data, $update_meta );",
"\t// Update for social.\n\t$socials = LP_Request::get_array( 'user_profile_social' );\n\t$extra_data = get_user_meta( $user_id, '_lp_extra_info', true );",
"\tif ( ! empty( $extra_data ) ) {\n\t\t$socials = array_merge( $extra_data, $socials );\n\t}",
"\tupdate_user_meta( $user_id, '_lp_extra_info', $socials );",
"\tif ( is_wp_error( $return ) ) {\n\t\treturn $wp_error ? $return : false;\n\t}",
"\treturn $return;\n}",
"/**\n * Update new password.\n */\nfunction learn_press_update_user_profile_change_password( $wp_error = false ) {\n\t$user_id = get_current_user_id();",
"\tif ( ! $user_id ) {\n\t\treturn new WP_Error( 2, 'User is invalid!' );\n\t}",
"\t$old_pass = filter_input( INPUT_POST, 'pass0' );\n\t$check_old_pass = false;",
"\tif ( $old_pass ) {\n\t\t$user = wp_get_current_user();\n\t\trequire_once ABSPATH . 'wp-includes/class-phpass.php';\n\t\t$wp_hasher = new PasswordHash( 8, true );",
"\t\tif ( $wp_hasher->CheckPassword( $old_pass, $user->data->user_pass ) ) {\n\t\t\t$check_old_pass = true;\n\t\t}\n\t}",
"\ttry {\n\t\tif ( ! $check_old_pass ) {\n\t\t\tthrow new Exception( __( 'Old password incorrect!', 'learnpress' ) );\n\t\t} else {\n\t\t\t$new_pass = filter_input( INPUT_POST, 'pass1' );\n\t\t\t$new_pass2 = filter_input( INPUT_POST, 'pass2' );",
"\t\t\tif ( ! $new_pass || ! $new_pass2 || ( $new_pass != $new_pass2 ) ) {\n\t\t\t\tthrow new Exception( __( 'Confirmation password incorrect!', 'learnpress' ) );\n\t\t\t} else {\n\t\t\t\t$update_data = array(\n\t\t\t\t\t'user_pass' => $new_pass,\n\t\t\t\t\t'ID' => get_current_user_id(),\n\t\t\t\t);\n\t\t\t\t$return = wp_update_user( $update_data );",
"\t\t\t\tif ( is_wp_error( $return ) ) {\n\t\t\t\t\treturn $wp_error ? $return : false;\n\t\t\t\t}",
"\t\t\t\treturn $return;\n\t\t\t}\n\t\t}\n\t} catch ( Exception $ex ) {\n\t\treturn $wp_error ? new WP_Error( 'UPDATE_PROFILE_ERROR', $ex->getMessage() ) : false;\n\t}\n}",
"function learn_press_get_avatar_thumb_size() {\n\t$option = LP_Settings::get_option(\n\t\t'avatar_dimensions',\n\t\tarray(\n\t\t\t'width' => 250,\n\t\t\t'height' => 250,\n\t\t)\n\t);",
"\tif ( ! isset( $option['width'] ) || ! isset( $option['height'] ) ) {\n\t\t$option = array(\n\t\t\t'width' => 250,\n\t\t\t'height' => 250,\n\t\t);\n\t}",
"\treturn $option;\n}",
"function learn_press_get_course_thumbnail_dimensions() {\n\t$option = LP_Settings::get_option(\n\t\t'course_thumbnail_dimensions',\n\t\tarray(\n\t\t\t'width' => 500,\n\t\t\t'height' => 300,\n\t\t)\n\t);",
"\tif ( ! isset( $option['width'] ) || ! isset( $option['height'] ) ) {\n\t\t$option = array(\n\t\t\t'width' => 500,\n\t\t\t'height' => 300,\n\t\t);\n\t}",
"\treturn $option;\n}",
"/**\n * Set a fake cookie to\n */\nfunction learn_press_set_user_cookie_for_guest() {\n\tif ( ! is_admin() && ! headers_sent() ) {\n\t\t$guest_key = '_wordpress_lp_guest';",
"\t\tif ( is_user_logged_in() ) {\n\t\t\tif ( ! empty( $_COOKIE[ $guest_key ] ) ) {\n\t\t\t\tlearn_press_remove_cookie( $guest_key );\n\t\t\t}\n\t\t} else {\n\t\t\tif ( empty( $_COOKIE[ $guest_key ] ) ) {\n\t\t\t\tlearn_press_setcookie( $guest_key, md5( time() ), time() + 3600 );\n\t\t\t}\n\t\t}\n\t}\n}",
"add_action( 'wp', 'learn_press_set_user_cookie_for_guest' );",
"function learn_press_get_user_avatar( $user_id = 0, $size = '' ) {\n\t$user = learn_press_get_user( $user_id );",
"\treturn $user->get_profile_picture( '', $size );\n}",
"/**\n * Get profile instance for an user to view.\n *\n * @param int $for_user\n *\n * @return LP_Profile|WP_Error\n */\nfunction learn_press_get_profile( $for_user = 0 ) {\n\treturn LP_Profile::instance( $for_user );\n}",
"/**\n * Remove items from learnpress_user_items.\n *\n * @param int $user_id\n * @param int $item_id\n * @param int $course_id\n * @param bool $include_course - Optional. If TRUE then remove course and it's items\n */\nfunction learn_press_remove_user_items( $user_id, $item_id, $course_id, $include_course = false ) {\n\tglobal $wpdb;",
"\tsettype( $item_id, 'array' );",
"\t$format = array_fill( 0, sizeof( $item_id ), '%d' );\n\t$where = '';",
"\t$args = array( $user_id );\n\t$args = array_merge( $args, $item_id );",
"\tif ( $course_id ) {\n\t\t$args[] = $course_id;\n\t\t$where = 'AND ref_id = %d';\n\t}",
"\tif ( $include_course ) {\n\t\t$where .= ' OR ( item_id = %d AND item_type = %s )';\n\t\t$args[] = $course_id;\n\t\t$args[] = LP_COURSE_CPT;\n\t}",
"\t$query = $wpdb->prepare(\n\t\t\"\n DELETE\n FROM {$wpdb->learnpress_user_items}\n WHERE user_id = %d\n AND ( item_id IN(\" . join( ',', $format ) . \")\n $where )\n \",\n\t\t$args\n\t);\n}",
"/**\n * Get user profile link\n *\n * @param int $user_id\n * @param null $tab\n *\n * @return mixed|string\n */\nfunction learn_press_user_profile_link( $user_id = 0, $tab = null ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}\n\t$user = false;\n\t$deleted = in_array( $user_id, LP_User_Factory::$_deleted_users );\n\tif ( ! $deleted ) {\n\t\tif ( is_numeric( $user_id ) ) {\n\t\t\t$user = get_user_by( 'id', $user_id );\n\t\t} else {\n\t\t\t$user = get_user_by( 'login', urldecode( $user_id ) );\n\t\t}\n\t} else {\n\t\treturn '';\n\t}\n\tif ( ! $deleted && ! $user ) {\n\t\tLP_User_Factory::$_deleted_users[] = $user_id;\n\t}",
"\t$user = learn_press_get_user( $user_id );",
"\tif ( ! $user ) {\n\t\treturn '';\n\t}",
"\tglobal $wp_query;\n\t$args = array(\n\t\t'user' => $user->get_username(),\n\t);",
"\tif ( isset( $args['user'] ) ) {\n\t\tif ( '' === $tab ) {\n\t\t\t$tab = learn_press_get_current_profile_tab();\n\t\t}\n\t\tif ( $tab ) {\n\t\t\t$args['tab'] = $tab;\n\t\t}",
"\t\t/**\n\t\t * If no tab is selected in profile and is current user\n\t\t * then no need the username in profile link.\n\t\t */\n\t\tif ( ( $user_id == get_current_user_id() ) && ! isset( $args['tab'] ) ) {\n\t\t\tunset( $args['user'] );\n\t\t}\n\t}\n\t$args = array_map( '_learn_press_urlencode', $args );\n\t$profile_link = trailingslashit( learn_press_get_page_link( 'profile' ) );\n\tif ( $profile_link ) {\n\t\tif ( get_option( 'permalink_structure' ) /*&& learn_press_get_page_id( 'profile' )*/ ) {\n\t\t\t$url = trailingslashit( $profile_link . join( '/', array_values( $args ) ) );\n\t\t} else {\n\t\t\t$url = add_query_arg( $args, $profile_link );\n\t\t}\n\t} else {\n\t\t$url = get_author_posts_url( $user_id );\n\t}",
"\treturn apply_filters( 'learn_press_user_profile_link', $url, $user_id, $tab );\n}",
"/**********************************************/\n/* Functions are used for hooks */\n/**********************************************/",
"function learn_press_hk_before_start_quiz( $true, $quiz_id, $course_id, $user_id ) {\n\tif ( 'yes' !== get_post_meta( $quiz_id, '_lp_archive_history', true ) ) {\n\t\tlearn_press_remove_user_items( $user_id, $quiz_id, $course_id );\n\t}",
"\treturn $true;\n}",
"add_filter( 'learn-press/before-start-quiz', 'learn_press_hk_before_start_quiz', 10, 4 );",
"/*function learn_press_default_user_item_status( $item_id ) {\n\t$status = '';\n\tswitch ( learn_press_get_post_type( $item_id ) ) {\n\t\tcase LP_LESSON_CPT:\n\t\t\t$status = 'started';\n\t\t\tbreak;\n\t\tcase LP_QUIZ_CPT:\n\t\t\t$status = 'viewed';\n\t\t\tbreak;\n\t\tcase LP_COURSE_CPT:\n\t\t\t$status = 'enrolled';\n\t}",
"\treturn apply_filters( 'learn-press/default-user-item-status', $status, $item_id );\n}*/",
"/**\n * Get current state of distraction mode\n *\n * @return mixed\n * @since 3.1.0\n */\nfunction learn_press_get_user_distraction() {\n\tif ( is_user_logged_in() ) {\n\t\treturn get_user_option( 'distraction_mode', get_current_user_id() );\n\t} else {\n\t\treturn LP()->session->distraction_mode;\n\t}\n}",
"function learn_press_get_user_role( $user_id ) {\n\tif ( $user = learn_press_get_user( $user_id ) ) {\n\t\treturn $user->get_role();\n\t}",
"\treturn false;\n}",
"/**\n * @param array $args\n * @param bool $wp_error\n *\n * @return bool|int|LP_User_Item|mixed|WP_Error\n */\nfunction learn_press_create_user_item( $args = array(), $wp_error = false ) {\n\tglobal $wpdb;",
"\t$defaults = array(\n\t\t'user_id' => get_current_user_id(),\n\t\t'item_id' => '',\n\t\t'start_time' => current_time( 'mysql', true ),\n\t\t'end_time' => '',\n\t\t'graduation' => '',\n\t\t'item_type' => '',\n\t\t'status' => '',\n\t\t'ref_id' => 0,\n\t\t'ref_type' => 0,\n\t\t'parent_id' => 0,\n\t\t'create_meta' => array(),\n\t);",
"\t$item_data = wp_parse_args( $args, $defaults );",
"\t// Validate item_id and post type\n\tif ( empty( $item_data['item_id'] ) ) {\n\t\tif ( $wp_error ) {\n\t\t\treturn new WP_Error( 'invalid_item_id', __( 'Invalid item id.', 'learnpress' ) );\n\t\t}",
"\t\treturn 0;\n\t}",
"\tif ( empty( $item_data['item_type'] ) && $post_type = learn_press_get_post_type( $item_data['item_id'] ) ) {\n\t\t$item_data['item_type'] = $post_type;\n\t}",
"\t// Get id and type of ref if they are null\n\tif ( ! empty( $item_data['parent_id'] ) && ( empty( $item_data['ref_id'] ) || ( empty( $item_data['ref_type'] ) ) ) ) {\n\t\t$parent = $wpdb->get_row(\n\t\t\t$wpdb->prepare(\n\t\t\t\t\"SELECT * FROM {$wpdb->learnpress_user_items} WHERE %d\",\n\t\t\t\t$item_data['parent_id']\n\t\t\t)\n\t\t);",
"\t\tif ( $parent ) {\n\t\t\tif ( empty( $item_data['ref_id'] ) ) {\n\t\t\t\t$item_data['ref_id'] = $parent->item_id;\n\t\t\t}",
"\t\t\tif ( empty( $item_data['ref_type'] ) ) {\n\t\t\t\t$item_data['ref_type'] = $parent->item_type;\n\t\t\t}\n\t\t}\n\t}",
"\t// Filter\n\tif ( ! $item_data = apply_filters( 'learn-press/create-user-item-data', $item_data ) ) {\n\t\tif ( $wp_error ) {\n\t\t\treturn new WP_Error( 'invalid_item_data', __( 'Invalid item data.', 'learnpress' ) );\n\t\t}",
"\t\treturn 0;\n\t}",
"\tdo_action( 'learn-press/before-create-user-item', $item_data );",
"\t$create_meta = ! empty( $item_data['create_meta'] ) ? $item_data['create_meta'] : false;",
"\tif ( $create_meta ) {\n\t\tunset( $item_data['create_meta'] );\n\t}",
"\t$user_item = new LP_User_Item( $item_data );",
"\t$result = $user_item->update( true, false );",
"\tif ( ! $result || is_wp_error( $result ) ) {",
"\t\tif ( $wp_error && is_wp_error( $result ) ) {\n\t\t\treturn $result;\n\t\t}",
"\t\treturn 0;\n\t}",
"\tdo_action( 'learn-press/created-user-item', $user_item, $item_data );",
"\t$create_meta = apply_filters( 'learn-press/create-user-item-meta', $create_meta, $item_data );\n\tif ( ! $create_meta ) {\n\t\treturn $user_item;\n\t}",
"\tdo_action( 'learn-press/before-create-user-item-meta', $create_meta );",
"\tforeach ( $create_meta as $key => $value ) {\n\t\tlearn_press_update_user_item_meta( $user_item->get_user_item_id(), $key, $value );\n\t}",
"\tdo_action( 'learn-press/created-user-item-meta', $user_item, $create_meta );",
"\treturn $user_item;\n}",
"/**\n * @param array $args\n * @param bool $wp_error - Optional. TRUE will return WP_Error on fail.\n *\n * @return bool|array|LP_User_Item|WP_Error\n */\nfunction learn_press_create_user_item_for_quiz( $args = array(), $wp_error = false ) {\n\tglobal $wpdb;",
"\t$item_data = wp_parse_args(\n\t\t$args,\n\t\tarray(\n\t\t\t'item_type' => LP_QUIZ_CPT,\n\t\t\t'status' => LP_ITEM_STARTED,\n\t\t\t'graduation' => LP_COURSE_GRADUATION_IN_PROGRESS,\n\t\t\t'user_id' => get_current_user_id(),\n\t\t)\n\t);",
"\t$user_item = learn_press_create_user_item( $item_data, $wp_error );",
"\tif ( $user_item && ! is_wp_error( $user_item ) ) {\n\t\t$user_item = new LP_User_Item_Quiz( $user_item->get_data() );\n\t\t$user_item->update( true );\n\t}",
"\treturn $user_item;\n}",
"/**\n * Get list user_item_id for Quiz in table learnpress_user_items\n *\n * @param int $quiz_id\n * @param int $course_id\n * @return array || false\n */\nfunction learn_press_isset_user_item_for_quiz( $quiz_id, $course_id ) {\n\tglobal $wpdb;",
"\t$query = $wpdb->prepare( \"SELECT user_item_id FROM $wpdb->learnpress_user_items WHERE ref_id=%d AND item_id=%d\", $course_id, $quiz_id );\n\t$col = $wpdb->get_col( $query );",
"\tif ( ! empty( $col ) ) {\n\t\treturn $col;\n\t} else {\n\t\treturn false;\n\t}\n}",
"/**\n * Create new user item prepare for user starts a quiz\n * Update error retry course not work - Nhamdv.\n *\n * @param int $quiz_id\n * @param int $user_id\n * @param int $course_id\n * @param bool $wp_error\n *\n * @return array|bool|LP_User_Item|WP_Error\n * @since 4.0.0\n */\nfunction learn_press_user_start_quiz( $quiz_id, $user_id = 0, $course_id = 0, $wp_error = false ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}",
"\tglobal $wpdb;",
"\t$query = $wpdb->prepare(\n\t\t\"\n\t SELECT user_item_id, item_id id, item_type type\n\t FROM {$wpdb->learnpress_user_items}\n\t WHERE user_item_id = (SELECT max(user_item_id)\n\t FROM {$wpdb->learnpress_user_items}\n\t WHERE user_id = %d AND item_id = %d AND status IN ('enrolled', 'in-progress'))\n\t\",\n\t\t$user_id,\n\t\t$course_id\n\t);",
"\t$parent = $wpdb->get_row( $query );",
"\tdo_action( 'learn-press/before-user-start-quiz', $quiz_id, $user_id, $course_id );",
"\t$user = learn_press_get_user( $user_id );\n\t$course_data = $user->get_course_data( $course_id );\n\t$quiz_data = $course_data->get_item( $quiz_id );",
"\t$quiz = LP_Quiz::get_quiz( $quiz_id );\n\t$duration = $quiz->get_duration();\n\t$user_quiz = learn_press_create_user_item_for_quiz(\n\t\tarray(\n\t\t\t'user_item_id' => $quiz_data ? $quiz_data->get_user_item_id() : 0,\n\t\t\t'item_id' => $quiz->get_id(),\n\t\t\t'duration' => $duration ? $duration->get() : 0,\n\t\t\t'user_id' => $user_id,\n\t\t\t'parent_id' => $parent ? absint( $parent->user_item_id ) : 0,\n\t\t\t'ref_type' => $parent ? $parent->type : '',\n\t\t\t'ref_id' => $parent ? $parent->id : '',\n\t\t),\n\t\t$wp_error\n\t);",
"\tif ( $user_quiz && ! is_wp_error( $user_quiz ) ) {\n\t\tdo_action( 'learn-press/user-started-quiz', $user_quiz, $quiz_id, $user_id, $course_id );\n\t}",
"\t// Reset first cache\n\t$user_quiz->get_status( 'status', true );",
"\treturn $user_quiz;\n}",
"/**\n * Function retake quiz.\n *\n * @param [type] $quiz_id\n * @param integer $user_id\n * @param integer $course_id\n * @param boolean $wp_error\n *\n * @return void\n */\nfunction learn_press_user_retake_quiz( $quiz_id, $user_id = 0, $course_id = 0, $wp_error = false ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}",
"\tif ( ! $course_id ) {\n\t\treturn new WP_Error( 'invalid_course_id', esc_html__( 'Invalid Course ID.', 'learnpress' ) );\n\t}",
"\tglobal $wpdb;",
"\t$query = $wpdb->prepare(\n\t\t\"\n\t SELECT user_item_id, item_id id, item_type type\n\t FROM {$wpdb->learnpress_user_items}\n\t WHERE user_item_id = (SELECT max(user_item_id)\n\t FROM {$wpdb->learnpress_user_items}\n\t WHERE user_id = %d AND item_id = %d AND status IN ('enrolled', 'in-progress'))\n\t\t\",\n\t\t$user_id,\n\t\t$course_id\n\t);",
"\t$parent = $wpdb->get_row( $query );",
"\tif ( ! $parent ) {\n\t\treturn new WP_Error( 'invalid_user_item', esc_html__( 'Invalid Quiz', 'learnpress' ) );\n\t}",
"\t$data = learn_press_get_user_item(\n\t\tarray(\n\t\t\t'item_id' => $quiz_id,\n\t\t\t'user_id' => $user_id,\n\t\t\t'parent_id' => $parent ? absint( $parent->user_item_id ) : 0,\n\t\t\t'ref_type' => $parent ? $parent->type : LP_COURSE_CPT,\n\t\t\t'ref_id' => $parent ? $parent->id : '',\n\t\t)\n\t);",
"\t$user_item = new LP_User_Item_Quiz( $data );",
"\t$user_item->update_retake_count();",
"\t// Create new result in table learnpress_user_item_results.\n\tLP_User_Items_Result_DB::instance()->insert( $data->user_item_id );",
"\t// Remove user_item_meta.\n\tlearn_press_delete_user_item_meta( $data->user_item_id, '_lp_question_checked' );",
"\t$user_item->set_status( LP_ITEM_STARTED )\n\t\t\t\t->set_start_time( current_time( 'mysql', 1 ) ) // Error Retake when change timezone - Nhamdv\n\t\t\t\t->set_end_time( '' )\n\t\t\t\t->set_graduation( LP_COURSE_GRADUATION_IN_PROGRESS )\n\t\t\t\t->update();",
"\t// Reset first cache\n\t$user_item->get_status( 'status', true );",
"\t// Error Retake when change timezone - Nhamdv\n\t// learn_press_update_user_item_field(\n\t// array(\n\t// 'start_time' => current_time( 'mysql', true ),\n\t// ),\n\t// array(\n\t// 'user_item_id' => $data->user_item_id,\n\t// )\n\t// );",
"\treturn $user_item;\n}",
"\n/**\n * Prepares list of questions for rest api.\n *\n * @param int[] $question_ids\n * @param array $args\n *\n * @return array\n * @since 3.3.0\n */\nfunction learn_press_rest_prepare_user_questions( array $question_ids = array(), array $args = array() ) : array {\n\tif ( is_numeric( $args ) ) {",
"\t} else {\n\t\t$args = wp_parse_args(\n\t\t\t$args,\n\t\t\tarray(\n\t\t\t\t'instant_hint' => true,\n\t\t\t\t'instant_check' => true,\n\t\t\t\t'quiz_status' => '',\n\t\t\t\t'checked_questions' => array(),\n\t\t\t\t'hinted_questions' => array(),\n\t\t\t\t'answered' => array(),\n\t\t\t\t'show_correct_review' => true,\n\t\t\t)\n\t\t);\n\t}",
"\t$checkedQuestions = $args['checked_questions'];\n\t$hintedQuestions = $args['hinted_questions'];\n\t$instantHint = $args['instant_hint'];\n\t$instantCheck = $args['instant_check'];\n\t$quizStatus = $args['quiz_status'];\n\t$answered = $args['answered'];\n\t$status = $args['status'] ?? '';\n\t$questions = array();",
"\tif ( $question_ids ) {\n\t\tforeach ( $question_ids as $id ) {\n\t\t\t$question = learn_press_get_question( $id );\n\t\t\t$hasHint = false;\n\t\t\t$hasExplanation = false;\n\t\t\t$canCheck = false;\n\t\t\t$hinted = false;\n\t\t\t$checked = false;\n\t\t\t$theHint = $question->get_hint();\n\t\t\t$theExplanation = '';",
"\t\t\tif ( $instantCheck || $status == 'completed' ) {\n\t\t\t\t$theExplanation = $question->get_explanation();\n\t\t\t\t$checked = in_array( $id, $checkedQuestions );\n\t\t\t\t$hasExplanation = ! ! $theExplanation;\n\t\t\t}",
"\t\t\t $mark = $question->get_mark() ? $question->get_mark() : 1;",
"\t\t\t$questionData = array(\n\t\t\t\t'object' => $question,\n\t\t\t\t'id' => absint( $id ),\n\t\t\t\t'title' => $question->get_title(),\n\t\t\t\t'type' => $question->get_type(),\n\t\t\t\t'point' => $mark,\n\t\t\t);",
"\t\t\t$content = $question->get_content();\n\t\t\tif ( $content ) {\n\t\t\t\t$questionData['content'] = $content;\n\t\t\t}",
"\t\t\tif ( $theHint ) {\n\t\t\t\t$questionData['hint'] = $theHint;\n\t\t\t}",
"\t\t\tif ( $status == 'completed' || ( $checked && $theExplanation ) ) {\n\t\t\t\t$questionData['explanation'] = $theExplanation;\n\t\t\t}",
"\t\t\tif ( $hasExplanation ) {\n\t\t\t\t$questionData['has_explanation'] = $hasExplanation;",
"\t\t\t\tif ( $checked ) {\n\t\t\t\t\t$questionData['explanation'] = $theExplanation;\n\t\t\t\t}\n\t\t\t}",
"\t\t\t$with_true_or_false = ( $checked || ( $quizStatus == 'completed' && $args['show_correct_review'] ) );",
"\t\t\tif ( $question->is_support( 'answer-options' ) ) {\n\t\t\t\t$questionData['options'] = learn_press_get_question_options_for_js(\n\t\t\t\t\t$question,\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'include_is_true' => $with_true_or_false,\n\t\t\t\t\t\t'answer' => $answered[ $id ]['answered'] ?? '',\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}",
"\t\t\t$questions[] = $questionData;\n\t\t}",
"\t\t/**\n\t\t * Remove answered\n\t\t */\n\t\tif ( $quizStatus !== 'completed' ) {\n\t\t\tif ( $checkedQuestions && $quizStatus ) {",
"\t\t\t\t$omitIds = array_diff( $question_ids, $checkedQuestions );",
"\t\t\t\tif ( $omitIds ) {\n\t\t\t\t\tforeach ( $omitIds as $omitId ) {\n\t\t\t\t\t\tif ( ! empty( $answered[ $omitId ] ) ) {\n\t\t\t\t\t\t\tunset( $answered[ $omitId ] );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\treturn apply_filters( 'learn-press/list-questions-data', $questions );\n}",
"/**\n * Output html to show extra info of user in backend profile.\n *\n * @param WP_User $user\n *\n * @since 4.0.0\n */\n/*function learn_press_append_user_profile_fields( $user ) {\n\tif ( ! is_admin() ) {\n\t\treturn;\n\t}",
"\tlearn_press_admin_view( 'backend-user-profile', array( 'user' => $user ) );\n}*/",
"//add_action( 'show_user_profile', 'learn_press_append_user_profile_fields' );\n//add_action( 'edit_user_profile', 'learn_press_append_user_profile_fields' );",
"/**\n * Update extra profile data upon update user.\n *\n * @param int $user_id\n *\n * @since 4.0.0\n */\nfunction learn_press_update_extra_user_profile_fields( $user_id ) {\n\tif ( ! current_user_can( 'edit_user', $user_id ) ) {\n\t\treturn;\n\t}",
"\tif ( isset( $_POST['_lp_extra_info'] ) ) {\n\t\tupdate_user_meta( $user_id, '_lp_extra_info', $_POST['_lp_extra_info'] );\n\t}\n}",
"add_action( 'personal_options_update', 'learn_press_update_extra_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'learn_press_update_extra_user_profile_fields' );",
"/**\n * Get extra profile info data\n *\n * @param int $user_id\n *\n * @return array\n * @since 4.0.0\n */\nfunction learn_press_get_user_extra_profile_info( $user_id = 0 ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}",
"\t$extra_profile_info = get_the_author_meta( '_lp_extra_info', $user_id );\n\t$extra_fields = learn_press_get_user_extra_profile_fields();",
"\t$extra_profile_info = wp_parse_args(\n\t\t$extra_profile_info,\n\t\tarray_fill_keys( array_keys( $extra_fields ), '' )\n\t);",
"\treturn apply_filters( 'learn-press/user-extra-profile-info', $extra_profile_info, $user_id );\n}",
"function learn_press_social_profiles() {\n\treturn apply_filters(\n\t\t'learn-press/social-profiles',\n\t\tarray(\n\t\t\t'facebook',\n\t\t\t'twitter',\n\t\t\t'youtube',\n\t\t\t'linkedin',\n\t\t)\n\t);\n}",
"function lp_add_default_fields( $fields ) {\n\t$first_name = LP()->settings()->get( 'enable_register_first_name' );",
"\tif ( $first_name === 'yes' ) {\n\t\t?>\n\t\t<li class=\"form-field\">\n\t\t\t<label for=\"reg_first_name\"><?php esc_html_e( 'First name', 'learnpress' ); ?></label>\n\t\t\t<input id=\"reg_first_name\" name=\"reg_first_name\" type=\"text\"\n\t\t\t\t placeholder=\"<?php esc_attr_e( 'First name', 'learnpress' ); ?>\"\n\t\t\t\t value=\"<?php echo ( ! empty( $_POST['reg_first_name'] ) ) ? esc_attr( wp_unslash( $_POST['reg_first_name'] ) ) : ''; ?>\">\n\t\t</li>\n\t\t<?php\n\t}",
"\t$last_name = LP()->settings()->get( 'enable_register_last_name' );",
"\tif ( $last_name === 'yes' ) {\n\t\t?>\n\t\t<li class=\"form-field\">\n\t\t\t<label for=\"reg_last_name\"><?php esc_html_e( 'Last name', 'learnpress' ); ?></label>\n\t\t\t<input id=\"reg_last_name\" name=\"reg_last_name\" type=\"text\"\n\t\t\t\t placeholder=\"<?php esc_attr_e( 'Last name', 'learnpress' ); ?>\"\n\t\t\t\t value=\"<?php echo ( ! empty( $_POST['reg_last_name'] ) ) ? esc_attr( wp_unslash( $_POST['reg_last_name'] ) ) : ''; ?>\">\n\t\t</li>\n\t\t<?php\n\t}",
"\t$display_name = LP()->settings()->get( 'enable_register_display_name' );",
"\tif ( $display_name === 'yes' ) {\n\t\t?>\n\t\t<li class=\"form-field\">\n\t\t\t<label for=\"reg_display_name\"><?php esc_html_e( 'Display name', 'learnpress' ); ?></label>\n\t\t\t<input id=\"reg_display_name\" name=\"reg_display_name\" type=\"text\"\n\t\t\t\t placeholder=\"<?php esc_attr_e( 'Display name', 'learnpress' ); ?>\"\n\t\t\t\t value=\"<?php echo ( ! empty( $_POST['reg_display_name'] ) ) ? esc_attr( wp_unslash( $_POST['reg_display_name'] ) ) : ''; ?>\">\n\t\t</li>\n\t\t<?php\n\t}\n}",
"add_filter( 'learn-press/after-form-register-fields', 'lp_add_default_fields' );",
"function lp_custom_register_fields_display() {\n\t?>\n\t<?php $custom_fields = LP()->settings()->get( 'register_profile_fields' ); ?>",
"\t<?php if ( $custom_fields ) : ?>\n\t\t<?php foreach ( $custom_fields as $custom_field ) : ?>\n\t\t\t<?php\n\t\t\t$cf_class = '';\n\t\t\tif ( $custom_field['required'] == 'yes' ) {\n\t\t\t\t$cf_class = ' required';\n\t\t\t\t?>\n\t\t\t\t<style>\n\t\t\t\t\t.required label {\n\t\t\t\t\t\tfont-weight: bold;\n\t\t\t\t\t}\n\t\t\t\t\t.required label:after {\n\t\t\t\t\t\tcontent: ' *';\n\t\t\t\t\t\tdisplay:inline;\n\t\t\t\t\t}\n\t\t\t\t</style>\n\t\t\t\t<?php\n\t\t\t}",
"\t\t\tif ( isset( $custom_field['id'] ) ) {\n\t\t\t\t?>\n\t\t\t\t<?php $value = $custom_field['id']; ?>",
"\t\t\t\t<li class=\"form-field<?php echo esc_attr( $cf_class ); ?>\">\n\t\t\t\t\t<?php\n\t\t\t\t\tswitch ( $custom_field['type'] ) {\n\t\t\t\t\t\tcase 'text':\n\t\t\t\t\t\tcase 'number':\n\t\t\t\t\t\tcase 'email':\n\t\t\t\t\t\tcase 'url':\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t<label for=\"description\"><?php echo esc_html( $custom_field['name'] ); ?></label>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\tcase 'tel':\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t<input name=\"_lp_custom_register_form[<?php echo $value; ?>]\"\n\t\t\t\t\t\t\t\t type=\"<?php echo $custom_field['type']; ?>\" class=\"regular-text\"\n\t\t\t\t\t\t\t\t value=\"\">\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'textarea':\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t<label for=\"description\"><?php echo esc_html( $custom_field['name'] ); ?></label>\n\t\t\t\t\t\t\t<textarea name=\"_lp_custom_register_form[<?php echo $value; ?>]\"></textarea>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'checkbox':\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t<label>\n\t\t\t\t\t\t\t\t<input name=\"_lp_custom_register_form[<?php echo $value; ?>]\"\n\t\t\t\t\t\t\t\t\t type=\"<?php echo $custom_field['type']; ?>\" value=\"1\">\n\t\t\t\t\t\t\t\t<?php echo esc_html( $custom_field['name'] ); ?>\n\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t?>\n\t\t\t\t</li>\n\t\t\t<?php } ?>\n\t\t<?php endforeach; ?>\n\t<?php endif; ?>\n\t<?php\n}",
"add_action( 'learn-press/after-form-register-fields', 'lp_custom_register_fields_display' );",
"/**\n * Custom register fields\n *\n * @param [type] $user_id\n *\n * @return void\n */\nfunction lp_user_custom_register_fields( $user_id, $fields = array() ) {\n\tif ( ! empty( $fields ) ) {\n\t\tupdate_user_meta( $user_id, '_lp_custom_register', LP_Helper::sanitize_params_submitted( $fields ) );\n\t} elseif ( isset( $_POST['_lp_custom_register'] ) ) {\n\t\tupdate_user_meta( $user_id, '_lp_custom_register', LP_Helper::sanitize_params_submitted( $_POST['_lp_custom_register'] ) );\n\t}\n}",
"add_action( 'personal_options_update', 'lp_user_custom_register_fields' );\nadd_action( 'edit_user_profile_update', 'lp_user_custom_register_fields' );",
"function lp_get_user_custom_register_fields( $user_id = 0 ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}",
"\t$register_fields = get_the_author_meta( '_lp_custom_register', $user_id );\n\t$defaults = lp_get_user_custom_fields();",
"\t$extra_profile_info = wp_parse_args( $register_fields, $defaults );",
"\treturn apply_filters( 'lp/user-custom-register-fields', $register_fields, $user_id );\n}",
"function lp_get_user_custom_fields() {\n\t$custom_fields = LP()->settings()->get( 'register_profile_fields' );",
"\t$output = array();",
"\tif ( $custom_fields ) {\n\t\tforeach ( $custom_fields as $field ) {\n\t\t\t$output[ $field['id'] ] = '';\n\t\t}\n\t}",
"\treturn $output;\n}",
"/**\n * Check extra user data is a social profile.\n *\n * @param $key\n *\n * @return bool\n * @since 4.0.0\n */\nfunction learn_press_is_social_profile( $key ) {\n\t$is_socials = learn_press_social_profiles();",
"\treturn in_array( $key, $is_socials );\n}",
"function learn_press_social_profile_name( $key ) {\n\t$name = '';\n\tswitch ( $key ) {\n\t\tcase 'facebook':\n\t\t\t$name = esc_html__( 'Facebook Profile', 'learnpress' );\n\t\t\tbreak;\n\t\tcase 'twitter':\n\t\t\t$name = esc_html__( 'Twitter Profile', 'learnpress' );\n\t\t\tbreak;\n\t\tcase 'googleplus':\n\t\t\t$name = esc_html__( 'Google Profile', 'learnpress' );\n\t\t\tbreak;\n\t\tcase 'youtube':\n\t\t\t$name = esc_html__( 'Youtube Channel', 'learnpress' );\n\t\t\tbreak;\n\t\tcase 'linkedin':\n\t\t\t$name = esc_html__( 'Linkedin Profile', 'learnpress' );\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t$name = ucfirst( $key );\n\t}",
"\treturn apply_filters( 'learn-press/social-profile-name', $name, $key );\n}",
"/**\n * Get extra profile fields will be registered in backend profile.\n *\n * @return array\n * @since 4.0.0\n */\nfunction learn_press_get_user_extra_profile_fields() {\n\t$socials = learn_press_social_profiles();\n\t$fields = array();",
"\tforeach ( $socials as $social ) {\n\t\t$fields[ $social ] = learn_press_social_profile_name( $social );\n\t}",
"\treturn apply_filters( 'learn-press/user-extra-profile-fields', $fields );\n}",
"/**\n * Show courses user enrolled on backend\n *\n * @param $user\n *\n * @return void\n */\nfunction learn_press_user_profile_data( $user ) {\n\tif ( ! is_admin() ) {\n\t\treturn;\n\t}",
"\tlearn_press_admin_view( 'backend-user-profile', array( 'user' => $user ) );\n\tlearn_press_admin_view( 'user/courses.php', array( 'user_id' => $user->ID ) );\n}\n//add_action( 'show_user_profile', 'learn_press_user_profile_data', 1000 );\nadd_action( 'edit_user_profile', 'learn_press_user_profile_data', 1000 );",
"function learnpress_get_count_by_user( $user_id = '', $post_type = 'lp_course' ) {\n\tif ( empty( $user_id ) ) {\n\t\treturn false;\n\t}",
"\t$args = array(\n\t\t'author' => $user_id,\n\t\t'posts_per_page' => - 1,\n\t\t'post_type' => $post_type,\n\t\t'post_status' => 'any',\n\t);",
"\t$posts = get_posts( $args );",
"\t$output = array(\n\t\t'all' => count( $posts ),\n\t\t'publish' => array(),\n\t\t'pending' => array(),\n\t);",
"\t$pending = $public = array();",
"\tif ( ! empty( $posts ) ) {\n\t\tforeach ( $posts as $post ) {\n\t\t\tswitch ( $post->post_status ) {\n\t\t\t\tcase 'pending':\n\t\t\t\t\t$pending[] = $post;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'publish':\n\t\t\t\t\t$public[] = $post;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}",
"\treturn array(\n\t\t'all' => count( $posts ),\n\t\t'publish' => count( $public ),\n\t\t'pending' => count( $pending ),\n\t);",
"}",
"/*\nadd_action(\n\t'admin_init',\n\tfunction() {\n\t\t$custom_fields = LP()->settings()->get( 'register_profile_fields' );",
"\t\t$custom_fields = LP_Helper::sanitize_params_submitted( $custom_fields );",
"\t\tif ( ! empty( $custom_fields ) ) {\n\t\t\t$output = array();",
"\t\t\tforeach ( $custom_fields as $key => $field ) {\n\t\t\t\tif ( ! isset( $field['id'] ) ) {\n\t\t\t\t\t$output[ $key ] = array(\n\t\t\t\t\t\t'id' => $field['name'],\n\t\t\t\t\t\t'name' => $field['name'] ?? '',\n\t\t\t\t\t\t'type' => $field['type'] ?? '',\n\t\t\t\t\t\t'required' => $field['required'] ?? '',\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\t$output[ $key ] = $field;\n\t\t\t\t}\n\t\t\t}",
"\t\t\tupdate_option( 'learn_press_register_profile_fields', $output );\n\t\t}\n\t}\n);*/"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
1,
1,
1,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [61, 1262, 233, 1156], "buggy_code_start_loc": [27, 1198, 14, 1081], "filenames": ["assets/src/js/frontend/profile.js", "inc/admin/class-lp-admin-ajax.php", "inc/class-lp-ajax.php", "inc/user/lp-user-functions.php"], "fixing_code_end_loc": [71, 1364, 200, 1152], "fixing_code_start_loc": [27, 1199, 14, 1082], "message": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thimpress:learnpress:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "F74AC61D-6728-4759-B5A4-F03B9519485C", "versionEndExcluding": "4.1.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site."}, {"lang": "es", "value": "Los usuarios del plugin LearnPress de WordPress versiones anteriores a 4.1.5, pueden subir una imagen como avatar de perfil tras el registro. Tras este proceso, el usuario recorta y guarda la imagen. A continuaci\u00f3n, se env\u00eda al servidor una petici\u00f3n \"POST\" que contiene el nombre de la imagen suministrado por el usuario para cambiar el nombre y recortar la imagen. Como resultado de esta petici\u00f3n, el nombre de la imagen suministrada por el usuario es cambiada con un valor MD5. Este proceso s\u00f3lo puede llevarse a cabo cuando el tipo de la imagen es JPG o PNG. Un atacante puede usar esta vulnerabilidad para cambiar el nombre de un archivo de imagen arbitrario. Al hacer esto, podr\u00edan destruir el dise\u00f1o del sitio web."}], "evaluatorComment": null, "id": "CVE-2022-0377", "lastModified": "2022-03-08T16:39:46.640", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-28T09:15:09.093", "references": [{"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://bozogullarindan.com/en/2022/01/wordpress-learnpress-plugin-4.1.4.1-arbitrary-image-renaming/"}, {"source": "contact@wpscan.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, {"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://wpscan.com/vulnerability/0d95ada6-53e3-4a80-a395-eacd7b090f26"}], "sourceIdentifier": "contact@wpscan.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-610"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-73"}], "source": "contact@wpscan.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, "type": "CWE-610"}
| 263
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/**\n * Common functions to process actions about user\n *\n * @author ThimPress\n * @package LearnPress/Functions/User\n * @version 1.0\n */",
"function learn_press_get_user_profile_tabs() {\n\treturn LP_Profile::instance()->get_tabs();\n}",
"/**\n * Delete user data by user ID\n *\n * @param int $user_id\n * @param int $course_id\n */\nfunction learn_press_delete_user_data( $user_id, $course_id = 0 ) {\n\tglobal $wpdb;\n\t// TODO: Should be deleted user's order and order data???",
"\t$query_args = array( $user_id );",
"\tif ( $course_id ) {\n\t\t$query_args[] = $course_id;\n\t}",
"\t$query = $wpdb->prepare(\n\t\t\"\n SELECT user_item_id\n FROM {$wpdb->prefix}learnpress_user_items\n WHERE user_id = %d\n \" . ( $course_id ? ' AND item_id = %d' : '' ) . '\n ',\n\t\t$query_args\n\t);",
"\t// delete all courses user has enrolled\n\t$query = $wpdb->prepare(\n\t\t\"\n DELETE FROM {$wpdb->prefix}learnpress_user_items\n WHERE user_id = %d\n \" . ( $course_id ? ' AND item_id = %d' : '' ) . '\n ',\n\t\t$query_args\n\t);",
"\t@$wpdb->query( $query );\n}",
"/**\n * Get user_item_id field in table learnpress_user_items\n * with the user_id, item_id. If $course_id is not passed\n * then item_id is ID of a course. Otherwise, item_id is\n * ID of an item (like quiz/lesson).\n *\n * @param int $user_id\n * @param int $item_id\n * @param int $course_id\n *\n * @return bool\n * @editor tungnx\n * @reason this function only get cache, not handle get user_item_id\n */\nfunction learn_press_get_user_item_id( $user_id, $item_id, $course_id = 0 /* added 3.0.0 */ ) {\n\treturn false;\n}",
"/**\n * Get current user ID\n *\n * @return int\n */\nfunction learn_press_get_current_user_id() {\n\t$user = learn_press_get_current_user();",
"\treturn $user->get_id();\n}",
"/**\n * Get the user by $user_id passed. If $user_id is NULL, get current user.\n * If current user is not logged in, return a GUEST user\n *\n * @param bool $create_temp - Optional. Create temp user if user is not logged in.\n *\n * @return bool|LP_User|LP_User_Guest\n * @editor tungnx\n * @modify 4.1.4\n * @version 1.0.1\n */\nfunction learn_press_get_current_user( $create_temp = true ) {\n\t$user_id = get_current_user_id();",
"\tif ( $user_id ) {\n\t\treturn learn_press_get_user( $user_id );\n\t}",
"\t// Return LP_User_Guest\n\treturn learn_press_get_user( 0 );\n}",
"if ( ! function_exists( 'learn_press_get_user' ) ) {\n\t/**\n\t * Get user by ID. Return false if the user does not exists.\n\t *\n\t * @param int $user_id\n\t * @param bool $current\n\t *\n\t * @return LP_User|mixed\n\t * Todo: check this function - tungnx\n\t */\n\tfunction learn_press_get_user( $user_id, $current = false, $force_new = false ) {\n\t\t$is_guest = false;\n\t\tif ( $user_id != LP()->session->guest_user_id ) {\n\t\t\tif ( $current && ! get_user_by( 'id', $user_id ) ) {\n\t\t\t\t$user_id = get_current_user_id();\n\t\t\t}\n\t\t}",
"\t\tif ( ! $user_id && isset( LP()->session ) ) {\n\t\t\tif ( ! LP()->session->guest_user_id ) {\n\t\t\t\tLP()->session->set_customer_session_cookie( 1 );\n\t\t\t\tLP()->session->guest_user_id = time();\n\t\t\t}",
"\t\t\t$user_id = LP()->session->guest_user_id;\n\t\t\t$is_guest = true;\n\t\t}",
"\t\tif ( ! $user_id ) {\n\t\t\treturn false;\n\t\t}",
"\t\t$user_id = '' . $user_id;",
"\t\tif ( $force_new || ! array_key_exists( $user_id, LP_Global::$users ) ) {\n\t\t\t/**\n\t\t\t * LP Hook.\n\t\t\t *\n\t\t\t * Filter the default class name to get LP user.\n\t\t\t *\n\t\t\t * @since 3.3.0\n\t\t\t */\n\t\t\t$userClass = apply_filters( 'learn-press/user-class', $is_guest ? 'LP_User_Guest' : 'LP_User', $is_guest );",
"\t\t\tLP_Global::$users[ $user_id ] = new $userClass( $user_id );",
"\t\t\tdo_action( 'learn-press/get-user', LP_Global::$users[ $user_id ], $user_id );\n\t\t}",
"\t\treturn LP_Global::$users[ $user_id ];\n\t}\n}",
"/**\n * Add more 2 user roles teacher and student\n */\nfunction learn_press_add_user_roles() {",
"\t$settings = LP()->settings;",
"\t/* translators: user role */\n\t_x( 'LP Instructor', 'User role' );",
"\tadd_role(\n\t\tLP_TEACHER_ROLE,\n\t\t'LP Instructor',\n\t\tarray()\n\t);",
"\t$course_cap = LP_COURSE_CPT . 's';\n\t$lesson_cap = LP_LESSON_CPT . 's';\n\t$order_cap = LP_ORDER_CPT . 's';",
"\t$teacher = get_role( LP_TEACHER_ROLE );\n\tif ( $teacher ) {\n\t\t$teacher->add_cap( 'read_private_' . $course_cap );\n\t\t$teacher->add_cap( 'delete_published_' . $course_cap );\n\t\t$teacher->add_cap( 'edit_published_' . $course_cap );\n\t\t$teacher->add_cap( 'edit_' . $course_cap );\n\t\t$teacher->add_cap( 'delete_' . $course_cap );\n\t\t$teacher->add_cap( 'unfiltered_html' );",
"\t\t$settings->get( 'required_review' );",
"\t\tif ( $settings->get( 'required_review' ) == 'yes' ) {\n\t\t\t$teacher->remove_cap( 'publish_' . $course_cap );\n\t\t} else {\n\t\t\t$teacher->add_cap( 'publish_' . $course_cap );\n\t\t}",
"\t\t$teacher->add_cap( 'read_private_' . $lesson_cap );\n\t\t$teacher->add_cap( 'delete_published_' . $lesson_cap );\n\t\t$teacher->add_cap( 'edit_published_' . $lesson_cap );\n\t\t$teacher->add_cap( 'edit_' . $lesson_cap );\n\t\t$teacher->add_cap( 'delete_' . $lesson_cap );\n\t\t$teacher->add_cap( 'publish_' . $lesson_cap );\n\t\t$teacher->add_cap( 'upload_files' );\n\t\t$teacher->add_cap( 'read' );\n\t\t$teacher->add_cap( 'edit_posts' );\n\t}",
"\t// administrator\n\t$admin = get_role( 'administrator' );\n\tif ( $admin ) {\n\t\t$admin->add_cap( 'read_private_' . $course_cap );\n\t\t$admin->add_cap( 'delete_' . $course_cap );\n\t\t$admin->add_cap( 'delete_published_' . $course_cap );\n\t\t$admin->add_cap( 'edit_' . $course_cap );\n\t\t$admin->add_cap( 'edit_published_' . $course_cap );\n\t\t$admin->add_cap( 'publish_' . $course_cap );\n\t\t$admin->add_cap( 'delete_private_' . $course_cap );\n\t\t$admin->add_cap( 'edit_private_' . $course_cap );\n\t\t$admin->add_cap( 'delete_others_' . $course_cap );\n\t\t$admin->add_cap( 'edit_others_' . $course_cap );",
"\t\t$admin->add_cap( 'read_private_' . $lesson_cap );\n\t\t$admin->add_cap( 'delete_' . $lesson_cap );\n\t\t$admin->add_cap( 'delete_published_' . $lesson_cap );\n\t\t$admin->add_cap( 'edit_' . $lesson_cap );\n\t\t$admin->add_cap( 'edit_published_' . $lesson_cap );\n\t\t$admin->add_cap( 'publish_' . $lesson_cap );\n\t\t$admin->add_cap( 'delete_private_' . $lesson_cap );\n\t\t$admin->add_cap( 'edit_private_' . $lesson_cap );\n\t\t$admin->add_cap( 'delete_others_' . $lesson_cap );\n\t\t$admin->add_cap( 'edit_others_' . $lesson_cap );",
"\t\t$admin->add_cap( 'delete_' . $order_cap );\n\t\t$admin->add_cap( 'delete_published_' . $order_cap );\n\t\t$admin->add_cap( 'edit_' . $order_cap );\n\t\t$admin->add_cap( 'edit_published_' . $order_cap );\n\t\t$admin->add_cap( 'publish_' . $order_cap );\n\t\t$admin->add_cap( 'delete_private_' . $order_cap );\n\t\t$admin->add_cap( 'edit_private_' . $order_cap );\n\t\t$admin->add_cap( 'delete_others_' . $order_cap );\n\t\t$admin->add_cap( 'edit_others_' . $order_cap );\n\t}\n}",
"add_action( 'init', 'learn_press_add_user_roles' );",
"/**\n * @param null $user_id\n * @param array $args\n *\n * @return mixed\n */\nfunction learn_press_get_user_questions( $user_id = null, $args = array() ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}",
"\treturn learn_press_get_user( $user_id )->get_questions( $args );\n}",
"/**\n * Get the type of current user\n *\n * @param null $check_type\n *\n * @return bool|string\n */\nfunction learn_press_current_user_is( $check_type = null ) {\n\tglobal $current_user;\n\t$user_roles = $current_user->roles;\n\t$user_type = '';",
"\tif ( in_array( 'lpr_teacher', $user_roles ) ) {\n\t\t$user_type = 'instructor';\n\t} elseif ( in_array( 'lp_teacher', $user_roles ) ) {\n\t\t$user_type = 'instructor';\n\t} elseif ( in_array( 'administrator', $user_roles ) ) {\n\t\t$user_type = 'administrator';\n\t}",
"\treturn $check_type ? $check_type == $user_type : $user_type;\n}",
"function learn_press_user_has_roles( $roles, $user_id = null ) {\n\t$has_role = false;\n\tif ( ! $user_id ) {\n\t\t$user = wp_get_current_user();\n\t} else {\n\t\t$user = get_user_by( 'id', $user_id );\n\t}\n\t$available_roles = (array) $user->roles;\n\tif ( is_array( $roles ) ) {\n\t\tforeach ( $roles as $role ) {\n\t\t\tif ( in_array( $role, $available_roles ) ) {\n\t\t\t\t$has_role = true;\n\t\t\t\tbreak; // only need one of roles is in available\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif ( in_array( $roles, $available_roles ) ) {\n\t\t\t$has_role = true;\n\t\t}\n\t}",
"\treturn $has_role;\n}",
"/**\n * Add user profile link into admin bar\n */\nfunction learn_press_edit_admin_bar() {\n\tglobal $wp_admin_bar;",
"\t$profile = learn_press_get_page_id( 'profile' );",
"\tif ( $profile && learn_press_get_post_type( $profile ) == 'page' && get_post_status( $profile ) != 'trash' ) {\n\t\t$user_id = learn_press_get_current_user_id();",
"\t\t$wp_admin_bar->add_menu(\n\t\t\tarray(\n\t\t\t\t'id' => 'course_profile',\n\t\t\t\t'parent' => 'user-actions',\n\t\t\t\t'title' => get_the_title( $profile ),\n\t\t\t\t'href' => learn_press_user_profile_link( $user_id, false ),\n\t\t\t)\n\t\t);\n\t}",
"\t$current_user = wp_get_current_user();",
"\tif ( in_array( LP_TEACHER_ROLE, $current_user->roles ) || in_array( 'administrator', $current_user->roles ) ) {\n\t\treturn;\n\t}\n}",
"add_action( 'admin_bar_menu', 'learn_press_edit_admin_bar' );",
"function learn_press_current_user_can_view_profile_section( $section, $user ) {\n\t$current_user = wp_get_current_user();\n\t$view = true;\n\tif ( $user->get_data( 'user_login' ) != $current_user->user_login && $section == LP()->settings->get(\n\t\t'profile_endpoints.profile-orders',\n\t\t'profile-orders'\n\t) ) {\n\t\t$view = false;\n\t}",
"\treturn apply_filters( 'learn_press_current_user_can_view_profile_section', $view, $section, $user );\n}",
"function learn_press_profile_tab_courses_content( $current, $tab, $user ) {\n\tlearn_press_get_template(\n\t\t'profile/tabs/courses.php',\n\t\tarray(\n\t\t\t'user' => $user,\n\t\t\t'current' => $current,\n\t\t\t'tab' => $tab,\n\t\t)\n\t);\n}",
"function learn_press_profile_tab_quizzes_content( $current, $tab, $user ) {\n\tlearn_press_get_template(\n\t\t'profile/tabs/quizzes.php',\n\t\tarray(\n\t\t\t'user' => $user,\n\t\t\t'current' => $current,\n\t\t\t'tab' => $tab,\n\t\t)\n\t);\n}",
"function learn_press_profile_tab_orders_content( $current, $tab, $user ) {\n\tlearn_press_get_template(\n\t\t'profile/tabs/orders.php',\n\t\tarray(\n\t\t\t'user' => $user,\n\t\t\t'current' => $current,\n\t\t\t'tab' => $tab,\n\t\t)\n\t);\n}",
"/**\n * Get queried user in profile link\n *\n * @return false|WP_User\n * @since 3.0.0\n */\nfunction learn_press_get_profile_user() {\n\treturn LP_Profile::get_queried_user();\n}",
"\n/**\n * Add instructor registration button to register page and admin bar\n */\nfunction learn_press_user_become_teacher_registration_form() {\n\tif ( LP()->settings->get( 'instructor_registration' ) != 'yes' ) {\n\t\treturn;\n\t}\n\t?>\n\t<p>\n\t\t<label for=\"become_teacher\">\n\t\t\t<input type=\"checkbox\" name=\"become_teacher\" id=\"become_teacher\">\n\t\t\t<?php esc_html_e( 'Want to become an instructor?', 'learnpress' ); ?>\n\t\t</label>\n\t</p>\n\t<?php\n}",
"add_action( 'register_form', 'learn_press_user_become_teacher_registration_form' );",
"/**\n * Update data into table learnpress_user_items.\n *\n * @param array $fields - Fields and values to be updated.\n * Format: array(\n * field_name_1 => value 1,\n * field_name_2 => value 2,\n * ....\n * field_name_n => value n\n * )\n * @param mixed $where - Optional. Fields with values for conditional update with the same format of $fields.\n * @param bool $update_cache - Optional. Should be update to cache or not (since 3.0.0).\n * @param bool $update_extra_fields_as_meta - Optional. Update extra fields as item meta (since 3.1.0).\n *\n * @return mixed\n */\nfunction learn_press_update_user_item_field( $fields, $where = false, $update_cache = true, $update_extra_fields_as_meta = false ) {\n\tglobal $wpdb;",
"\t// Table fields\n\t$table_fields = array(\n\t\t'user_id' => '%d',\n\t\t'item_id' => '%d',\n\t\t'ref_id' => '%d',\n\t\t'start_time' => '%s',\n\t\t'end_time' => '%s',\n\t\t'access_level' => '%d',\n\t\t'graduation' => '%s',\n\t\t'item_type' => '%s',\n\t\t'status' => '%s',\n\t\t'ref_type' => '%s',\n\t\t'parent_id' => '%d',\n\t);",
"\t/**\n\t * Validate item status\n\t */\n\tif ( ! empty( $fields['item_id'] ) && ! empty( $fields['status'] ) ) {\n\t\t$item_type = learn_press_get_post_type( $fields['item_id'] );",
"\t\tif ( LP_COURSE_CPT === $item_type ) {\n\t\t\tif ( 'completed' === $fields['status'] ) {\n\t\t\t\t$fields['status'] = 'finished';\n\t\t\t}\n\t\t} else {\n\t\t\tif ( 'finished' === $fields['status'] ) {\n\t\t\t\t$fields['status'] = 'completed';\n\t\t\t}\n\t\t}\n\t}",
"\t$data = array();\n\t$data_format = array();\n\t$date_time_fields = array(\n\t\t'start_time',\n\t\t'end_time',\n\t);",
"\tforeach ( $fields as $field => $value ) {\n\t\tif ( ! empty( $table_fields[ $field ] ) ) {\n\t\t\t$data[ $field ] = $value;",
"\t\t\t// Do not format the date-time field if it's value is NULL\n\t\t\tif ( in_array( $field, $date_time_fields ) && ! $value ) {\n\t\t\t\t$data[ $field ] = null;\n\t\t\t\t$data_format[] = '';\n\t\t\t} else {\n\t\t\t\t$data_format[] = $table_fields[ $field ];\n\t\t\t}\n\t\t}\n\t}",
"\tif ( ! empty( $fields['user_item_id'] ) ) {\n\t\t$where = wp_parse_args(\n\t\t\t$where,\n\t\t\tarray( 'user_item_id' => $fields['user_item_id'] )\n\t\t);\n\t}",
"\tif ( $where && empty( $where['user_id'] ) ) {\n\t\t$where['user_id'] = ! empty( $fields['user_id'] ) ? $fields['user_id'] : learn_press_get_current_user_id();\n\t}",
"\t$where_format = array();",
"\t// Build where and where format\n\tif ( $where ) {\n\t\tforeach ( $where as $field => $value ) {\n\t\t\tif ( ! empty( $table_fields[ $field ] ) ) {\n\t\t\t\t$where_format[] = $table_fields[ $field ];\n\t\t\t}\n\t\t}\n\t}",
"\tif ( ! $data ) {\n\t\treturn false;\n\t}",
"\t$inserted = false;\n\t$updated = false;",
"\t// Ensure all fields are instance of LP_Datetime have to\n\t// convert to string of datetime.\n\tforeach ( $data as $k => $v ) {\n\t\tif ( $v instanceof LP_Datetime ) {\n\t\t\t$data[ $k ] = $v->toSql();\n\t\t}\n\t}",
"\t// If $where is not empty consider we are updating\n\tif ( $where ) {\n\t\t$updated = $wpdb->update(\n\t\t\t$wpdb->learnpress_user_items,\n\t\t\t$data,\n\t\t\t$where,\n\t\t\t$data_format,\n\t\t\t$where_format\n\t\t);\n\t} else {",
"\t\t// Otherwise, insert a new one\n\t\tif ( $wpdb->insert(\n\t\t\t$wpdb->learnpress_user_items,\n\t\t\t$data,\n\t\t\t$data_format\n\t\t)\n\t\t) {\n\t\t\t$inserted = $wpdb->insert_id;\n\t\t}\n\t}",
"\tif ( $updated && ! empty( $where['user_item_id'] ) ) {\n\t\t$inserted = $where['user_item_id'];\n\t}",
"\t/**\n\t * @var object|bool $updated_item\n\t */\n\t$updated_item = false;",
"\t// Get the item we just have updated or inserted.\n\tif ( $inserted ) {\n\t\t$updated_item = learn_press_get_user_item( $inserted );\n\t} elseif ( $updated ) {\n\t\t$updated_item = learn_press_get_user_item( $where );\n\t}",
"\t/**\n\t * If there is some fields does not contain in the main table\n\t * then consider update them as meta data.\n\t */\n\tif ( $updated_item && $update_extra_fields_as_meta ) {\n\t\t$extra_fields = array_diff_key( $fields, $table_fields );\n\t\tif ( $extra_fields ) {\n\t\t\tforeach ( $extra_fields as $meta_key => $meta_value ) {\n\t\t\t\tif ( $meta_value == 'user_item_id' ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}",
"\t\t\t\tif ( $meta_value === false ) {\n\t\t\t\t\tlearn_press_delete_user_item_meta( $updated_item->user_item_id, $meta_key );\n\t\t\t\t} else {",
"\t\t\t\t\tif ( empty( $meta_value ) ) {\n\t\t\t\t\t\t$meta_value = '';\n\t\t\t\t\t}\n\t\t\t\t\tlearn_press_update_user_item_meta( $updated_item->user_item_id, $meta_key, $meta_value );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\tdo_action( 'learn-press/updated-user-item-meta', $updated_item );",
"\treturn $updated_item;\n}",
"/**\n * Get user item row(s) from user items table by multiple WHERE conditional\n *\n * @param array|int $where\n * @param bool $single\n *\n * @return array\n */\nfunction learn_press_get_user_item( $where, $single = true ) {\n\tglobal $wpdb;",
"\t// Table fields\n\t$table_fields = array(\n\t\t'user_item_id' => '%d',\n\t\t'user_id' => '%d',\n\t\t'item_id' => '%d',\n\t\t'ref_id' => '%d',\n\t\t'start_time' => '%s',\n\t\t'end_time' => '%s',\n\t\t'item_type' => '%s',\n\t\t'status' => '%s',\n\t\t'ref_type' => '%s',\n\t\t'parent_id' => '%d',\n\t);",
"\t// If $where is a number consider we are searching the record with unique user_item_id\n\tif ( is_numeric( $where ) ) {\n\t\t$where = array( 'user_item_id' => $where );\n\t}",
"\t$where_str = array();\n\tforeach ( $where as $field => $value ) {\n\t\tif ( ! empty( $table_fields[ $field ] ) ) {\n\t\t\t$where_str[] = \"{$field} = \" . $table_fields[ $field ];\n\t\t}\n\t}\n\t$item = false;",
"\tif ( $where_str ) {\n\t\t$query = $wpdb->prepare(\n\t\t\t\"\n\t\t\tSELECT *\n\t\t\tFROM {$wpdb->prefix}learnpress_user_items\n\t\t\tWHERE \" . join( ' AND ', $where_str ) . '\n\t\t\tORDER BY user_item_id DESC\n\t\t',\n\t\t\t$where\n\t\t);\n\t\tif ( $single || ! empty( $where['user_item_id'] ) ) {\n\t\t\t$item = $wpdb->get_row( $query );\n\t\t} else {\n\t\t\t$item = $wpdb->get_results( $query );\n\t\t}\n\t}",
"\treturn $item;\n}",
"/**\n * Get user item meta from user_itemmeta table\n *\n * @param int $user_item_id .\n * @param string $meta_key .\n * @param bool $single .\n *\n * @return mixed\n */\nfunction learn_press_get_user_item_meta( $user_item_id = 0, $meta_key = '', $single = true ) {\n\t$meta = false;\n\tif ( metadata_exists( 'learnpress_user_item', $user_item_id, $meta_key ) ) {\n\t\t$meta = get_metadata( 'learnpress_user_item', $user_item_id, $meta_key, $single );\n\t}",
"\treturn $meta;\n}",
"/**\n * Add user item meta into table user_itemmeta\n *\n * @param int $user_item_id\n * @param string $meta_key\n * @param mixed $meta_value\n * @param string $prev_value\n *\n * @return false|int\n */\nfunction learn_press_add_user_item_meta( $user_item_id, $meta_key, $meta_value, $prev_value = '' ) {\n\treturn add_metadata( 'learnpress_user_item', $user_item_id, $meta_key, $meta_value, $prev_value );\n}",
"/**\n * Update user item meta to table user_itemmeta\n *\n * @param int $user_item_id\n * @param string $meta_key\n * @param mixed $meta_value\n * @param string $prev_value\n *\n * @return bool|int\n */\nfunction learn_press_update_user_item_meta( $user_item_id, $meta_key, $meta_value, $prev_value = '' ) {\n\treturn update_metadata( 'learnpress_user_item', $user_item_id, $meta_key, $meta_value, $prev_value );\n}",
"\n/**\n * Update user item meta to table user_itemmeta\n *\n * @param int $object_id\n * @param string $meta_key\n * @param mixed $meta_value\n * @param bool $delete_all\n *\n * @return bool|int\n */\nfunction learn_press_delete_user_item_meta( $object_id, $meta_key, $meta_value = '', $delete_all = false ) {\n\treturn delete_metadata( 'learnpress_user_item', $object_id, $meta_key, $meta_value, $delete_all );\n}",
"/**\n * Exclude the temp users from query.\n *\n * @param WP_User_Query $q\n */\nfunction learn_press_filter_temp_users( $q ) {\n\t// if ( $temp_users = learn_press_get_temp_users() ) {\n\t// $exclude = (array) $q->get( 'exclude' );\n\t// $exclude = array_merge( $exclude, $temp_users );\n\t// $q->set( 'exclude', $exclude );\n\t// }\n}",
"// add_action( 'pre_get_users', 'learn_press_filter_temp_users' );",
"/**\n * Get temp users.\n *\n * @return array\n */\nfunction learn_press_get_temp_users() {\n\treturn false;\n\tif ( false === ( $temp_users = LP_Object_Cache::get( 'learn-press/temp-users' ) ) ) {\n\t\tglobal $wpdb;\n\t\t$query = $wpdb->prepare(\n\t\t\t\"\n\t\t\tSELECT ID\n\t\t\tFROM {$wpdb->users} u\n\t\t\tINNER JOIN {$wpdb->usermeta} um ON u.ID = um.user_id AND um.meta_key = %s AND um.meta_value = %s\n\t\t\tLEFT JOIN {$wpdb->usermeta} um2 ON u.ID = um2.user_id AND um2.meta_key = %s\n\t\t\",\n\t\t\t'_lp_temp_user',\n\t\t\t'yes',\n\t\t\t'_lp_expiration'\n\t\t);",
"\t\t$temp_users = $wpdb->get_col( $query );",
"\t\tLP_Object_Cache::set( 'learn-press/temp-users', $temp_users );\n\t}",
"\treturn $temp_users;\n}",
"/**\n * Update field created_time after added user item meta\n *\n * @use updated_{meta_type}_meta hook\n *\n * @param $meta_id\n * @param $object_id\n * @param $meta_key\n * @param $_meta_value\n */\nfunction _learn_press_update_created_time_user_item_meta( $meta_id, $object_id, $meta_key, $_meta_value ) {\n\tglobal $wpdb;\n\t$wpdb->update(\n\t\t$wpdb->learnpress_user_itemmeta,\n\t\tarray( 'create_time' => current_time( 'mysql' ) ),\n\t\tarray( 'meta_id' => $meta_id ),\n\t\tarray( '%s' ),\n\t\tarray( '%d' )\n\t);\n}",
"// add_action( 'added_learnpress_user_item_meta', '_learn_press_update_created_time_user_item_meta', 10, 4 );",
"/**\n * Update field updated_time after updated user item meta\n *\n * @use updated_{meta_type}_meta hook\n *\n * @param $meta_id\n * @param $object_id\n * @param $meta_key\n * @param $_meta_value\n */\nfunction _learn_press_update_updated_time_user_item_meta( $meta_id, $object_id, $meta_key, $_meta_value ) {\n\tglobal $wpdb;\n\t$wpdb->update(\n\t\t$wpdb->learnpress_user_itemmeta,\n\t\tarray( 'update_time' => current_time( 'mysql' ) ),\n\t\tarray( 'meta_id' => $meta_id ),\n\t\tarray( '%s' ),\n\t\tarray( '%d' )\n\t);\n}",
"// add_action( 'updated_learnpress_user_item_meta', '_learn_press_update_updated_time_user_item_meta', 10, 4 );",
"/**\n * @param $status\n * @param int $quiz_id\n * @param int $user_id\n * @param int $course_id\n *\n * @return bool|mixed\n */\nfunction learn_press_user_has_quiz_status( $status, $quiz_id = 0, $user_id = 0, $course_id = 0 ) {\n\t$user = learn_press_get_user( $user_id );",
"\treturn $user->has_quiz_status( $status, $quiz_id, $course_id );\n}",
"if ( ! function_exists( 'learn_press_pre_get_avatar_callback' ) ) {\n\t/**\n\t * Filter the avatar\n\t *\n\t * @param string $avatar\n\t * @param string $id_or_email\n\t * @param array $size\n\t *\n\t * @return string\n\t */\n\tfunction learn_press_pre_get_avatar_callback( $avatar, $id_or_email = '', $size = array() ) {",
"\t\t$profile = LP_Profile::instance();",
"\t\tif ( ! $profile->is_enable_avatar() ) {\n\t\t\treturn $avatar;\n\t\t}",
"\t\tif ( ( isset( $size['gravatar'] ) && $size['gravatar'] ) || ( $size['default'] && $size['force_default'] ) ) {\n\t\t\treturn $avatar;\n\t\t}",
"\t\t$user_id = 0;",
"\t\t/**\n\t\t * Get the ID of user from $id_or_email\n\t\t */\n\t\tif ( ! is_numeric( $id_or_email ) && is_string( $id_or_email ) ) {\n\t\t\tif ( $user = get_user_by( 'email', $id_or_email ) ) {\n\t\t\t\t$user_id = $user->ID;\n\t\t\t}\n\t\t} elseif ( is_numeric( $id_or_email ) ) {\n\t\t\t$user_id = $id_or_email;\n\t\t} elseif ( is_object( $id_or_email ) && isset( $id_or_email->user_id ) && $id_or_email->user_id ) {\n\t\t\t$user_id = $id_or_email->user_id;\n\t\t} elseif ( is_object( $id_or_email ) && $id_or_email instanceof WP_Comment ) {\n\t\t\tif ( $user = get_user_by( 'email', $id_or_email->comment_author_email ) ) {\n\t\t\t\t$user_id = $user->ID;\n\t\t\t}\n\t\t}",
"\t\tif ( ! $user_id ) {\n\t\t\treturn $avatar;\n\t\t}",
"\t\t$user = LP_User_Factory::get_user( $user_id );",
"\t\t$profile_picture_src = $user->get_upload_profile_src();\n\t\tif ( $profile_picture_src ) {\n\t\t\t$setting_size = learn_press_get_avatar_thumb_size();\n\t\t\t$img_size = '';",
"\t\t\t// Get avatar size\n\t\t\tif ( ! is_array( $size ) ) {\n\t\t\t\tif ( $size === 'thumbnail' ) {\n\t\t\t\t\t$img_size = '';\n\t\t\t\t\t$height = $setting_size['height'];\n\t\t\t\t\t$width = $setting_size['width'];\n\t\t\t\t} else {\n\t\t\t\t\t$height = 250;\n\t\t\t\t\t$width = 250;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$img_size = $size['size'];\n\t\t\t\t$height = $size['height'];\n\t\t\t\t$width = $size['width'];\n\t\t\t}",
"\t\t\t$avatar = '<img alt=\"' . esc_attr( $user->get_data( 'display_name' ) ) . '\" src=\"' . esc_url( $profile_picture_src ) . '\" class=\"avatar avatar-' . $img_size . ' photo\" height=\"' . $height . '\" width=\"' . $width . '\" />';\n\t\t}",
"\t\treturn $avatar;\n\t}\n}\nadd_filter( 'pre_get_avatar', 'learn_press_pre_get_avatar_callback', 1, 5 );",
"\nfunction learn_press_user_profile_picture_upload_dir( $width_user = true ) {\n\tstatic $upload_dir;\n\tif ( ! $upload_dir ) {\n\t\t$upload_dir = wp_upload_dir();\n\t\t$subdir = apply_filters( 'learn_press_user_profile_folder', 'learn-press-profile', $width_user );\n\t\tif ( $width_user ) {\n\t\t\t$subdir .= '/' . get_current_user_id();\n\t\t}\n\t\t$subdir = '/' . $subdir;",
"\t\tif ( ! empty( $upload_dir['subdir'] ) ) {\n\t\t\t$u_subdir = str_replace( '\\\\', '/', $upload_dir['subdir'] );\n\t\t\t$u_path = str_replace( '\\\\', '/', $upload_dir['path'] );",
"\t\t\t$upload_dir['path'] = str_replace( $u_subdir, $subdir, $u_path );\n\t\t\t$upload_dir['url'] = str_replace( $u_subdir, $subdir, $upload_dir['url'] );\n\t\t} else {\n\t\t\t$upload_dir['path'] = $upload_dir['path'] . $subdir;\n\t\t\t$upload_dir['url'] = $upload_dir['url'] . $subdir;\n\t\t}",
"\t\t$upload_dir['subdir'] = $subdir;",
"\t\t// Point path/url to main site if we are in multisite\n\t\tif ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {\n\t\t\tforeach ( array( 'path', 'url', 'basedir', 'baseurl' ) as $v ) {\n\t\t\t\t$upload_dir[ $v ] = str_replace( '/sites/' . get_current_blog_id(), '', $upload_dir[ $v ] );\n\t\t\t}\n\t\t}\n\t}",
"\treturn $upload_dir;\n}",
"add_action( 'learn_press_before_purchase_course_handler', '_learn_press_before_purchase_course_handler', 10, 2 );\nfunction _learn_press_before_purchase_course_handler( $course_id, $cart ) {\n\t// Redirect to login page if user is not logged in\n\tif ( ! is_user_logged_in() ) {\n\t\t$return_url = add_query_arg( $_POST, get_the_permalink( $course_id ) );\n\t\t$return_url = apply_filters( 'learn_press_purchase_course_login_redirect_return_url', $return_url );\n\t\t$redirect = apply_filters(\n\t\t\t'learn_press_purchase_course_login_redirect',\n\t\t\tlearn_press_get_login_url( $return_url )\n\t\t);\n\t\tif ( $redirect !== false ) {\n\t\t\tlearn_press_add_message( __( 'Please login to enroll this course', 'learnpress' ) );",
"\t\t\tif ( learn_press_is_ajax() ) {\n\t\t\t\tlearn_press_send_json(\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'redirect' => $redirect,\n\t\t\t\t\t\t'result' => 'success',\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\twp_redirect( $redirect );\n\t\t\t\texit();\n\t\t\t}\n\t\t}\n\t} else {\n\t\t$user = learn_press_get_current_user();\n\t\t$redirect = false;\n\t\tif ( $user->has_finished_course( $course_id ) ) {\n\t\t\tlearn_press_add_message( __( 'You have already finished course', 'learnpress' ) );\n\t\t\t$redirect = true;\n\t\t} elseif ( $user->has_purchased_course( $course_id ) ) {\n\t\t\tlearn_press_add_message( __( 'You have already enrolled in this course', 'learnpress' ) );\n\t\t\t$redirect = true;\n\t\t}\n\t\tif ( $redirect ) {\n\t\t\twp_redirect( get_the_permalink( $course_id ) );\n\t\t\texit();\n\t\t}\n\t}\n}",
"function learn_press_user_is( $role, $user_id = 0 ) {\n\tif ( ! $user_id ) {\n\t\t$user = learn_press_get_current_user();\n\t} else {\n\t\t$user = learn_press_get_user( $user_id );\n\t}\n\tif ( $role == 'admin' ) {\n\t\treturn $user->is_admin();\n\t}\n\tif ( $role == 'instructor' ) {\n\t\treturn $user->is_instructor();\n\t}",
"\treturn $role;\n}",
"function learn_press_profile_tab_edit_content( $current, $tab, $user ) {\n\tlearn_press_get_template(\n\t\t'profile/tabs/edit.php',\n\t\tarray(\n\t\t\t'user' => $user,\n\t\t\t'current' => $current,\n\t\t\t'tab' => $tab,\n\t\t)\n\t);\n}",
"function learn_press_get_profile_endpoints() {\n\t$endpoints = (array) LP()->settings->get( 'profile_endpoints' );\n\tif ( $tabs = LP_Profile::instance()->get_tabs() ) {\n\t\tforeach ( $tabs as $slug => $info ) {\n\t\t\tif ( empty( $endpoints[ $slug ] ) ) {\n\t\t\t\t$endpoints[ $slug ] = $slug;\n\t\t\t}\n\t\t}\n\t}",
"\treturn apply_filters( 'learn_press_profile_tab_endpoints', $endpoints );\n}",
"\nfunction learn_press_update_user_option( $name, $value, $id = 0 ) {\n\tif ( ! $id ) {\n\t\t$id = get_current_user_id();\n\t}\n\t$key = 'learnpress_user_options';\n\t$options = get_user_option( $key, $id );\n\t$options[ $name ] = $value;\n\tupdate_user_option( $id, $key, $options, true );\n}",
"/**\n * @param $name\n * @param int $id\n *\n * @return bool\n */\nfunction learn_press_delete_user_option( $name, $id = 0 ) {\n\tif ( ! $id ) {\n\t\t$id = get_current_user_id();\n\t}\n\t$key = 'learnpress_user_options';\n\t$options = get_user_option( $key, $id );\n\tif ( is_array( $options ) && array_key_exists( $name, $options ) ) {\n\t\tunset( $options[ $name ] );\n\t\tupdate_user_option( $id, $key, $options, true );",
"\t\treturn true;\n\t}",
"\treturn false;\n}",
"/**\n * @param $name\n * @param int $id\n *\n * @return bool\n */\nfunction learn_press_get_user_option( $name, $id = 0 ) {\n\tif ( ! $id ) {\n\t\t$id = get_current_user_id();\n\t}\n\t$key = 'learnpress_user_options';\n\t$options = get_user_option( $key, $id );\n\tif ( is_array( $options ) && array_key_exists( $name, $options ) ) {\n\t\treturn $options[ $name ];\n\t}",
"\treturn false;\n}",
"/**\n * Check and update user information from request in user profile page\n */\nfunction learn_press_update_user_profile() {",
"\tif ( ! LP()->is_request( 'post' ) ) {\n\t\treturn;\n\t}\n\t$nonce = learn_press_get_request( 'profile-nonce' );",
"\tif ( ! wp_verify_nonce( $nonce, 'learn-press-update-user-profile-' . get_current_user_id() ) ) {\n\t\treturn;\n\t}\n\t$section = learn_press_get_request( 'lp-profile-section' );",
"\tdo_action( 'learn_press_update_user_profile_' . $section );\n\tdo_action( 'learn_press_update_user_profile', $section );\n}",
"// add_action( 'init', 'learn_press_update_user_profile' );",
"/**\n * Update user avatar\n */\nfunction learn_press_update_user_profile_avatar() {\n\t$user_id = get_current_user_id();",
"\t$data = learn_press_get_request( 'lp-user-avatar-crop' );",
"\n\tif ( ! $user_id ) {\n\t\treturn new WP_Error( 2, 'User is invalid!' );\n\t}",
"\t$upload_dir = learn_press_user_profile_picture_upload_dir();",
"\tif ( learn_press_get_request( 'lp-user-avatar-custom' ) != 'yes' ) {\n\t\tdelete_user_meta( get_current_user_id(), '_lp_profile_picture' );",
"\t\treturn false;\n\t}\n",
"\t$path_img = get_user_meta( $user_id, '_lp_profile_picture', true );",
"\t$path = $upload_dir['basedir'] . $path_img;",
"\tif ( ! file_exists( $path ) ) {",
"\t\treturn false;\n\t}",
"\t$filetype = wp_check_filetype( $path );",
"\tif ( 'jpg' == $filetype['ext'] ) {\n\t\t$im = imagecreatefromjpeg( $path );\n\t} elseif ( 'png' == $filetype['ext'] ) {\n\t\t$im = imagecreatefrompng( $path );\n\t}",
"\tif ( ! isset( $im ) ) {\n\t\treturn false;\n\t}",
"\t$points = explode( ',', $data['points'] );\n\t$im_crop = imagecreatetruecolor( $data['width'], $data['height'] );",
"\tif ( ! $im ) {\n\t\treturn false;\n\t}",
"\t$dst_x = 0;\n\t$dst_y = 0;\n\t$dst_w = $data['width'];\n\t$dst_h = $data['height'];\n\t$src_x = $points[0];\n\t$src_y = $points[1];\n\t$src_w = $points[2] - $points[0];\n\t$src_h = $points[3] - $points[1];",
"\timagecopyresampled( $im_crop, $im, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );",
"\t$newname = md5( $user_id . microtime( true ) );\n\t$output = dirname( $path );",
"\tif ( 'jpg' == $filetype['ext'] ) {\n\t\t$newname .= '.jpg';\n\t\t$output .= '/' . $newname;\n\t\timagejpeg( $im_crop, $output );\n\t} elseif ( 'png' == $filetype['ext'] ) {\n\t\t$newname .= '.png';\n\t\t$output .= '/' . $newname;\n\t\timagepng( $im_crop, $output );\n\t}",
"\t$new_avatar = false;",
"\tif ( file_exists( $output ) ) {",
"",
"\t\t$new_avatar = preg_replace( '!^/!', '', $upload_dir['subdir'] ) . '/' . $newname;",
"\t\tupdate_user_meta( $user_id, '_lp_profile_picture', '/' . $new_avatar );",
"\t\tupdate_user_meta( $user_id, '_lp_profile_picture_changed', 'yes' );",
"\t\t$new_avatar = $upload_dir['baseurl'] . '/' . $new_avatar;\n\t}",
"\t@unlink( $path );",
"\treturn $new_avatar;\n}",
"// add_action( 'learn_press_update_user_profile_avatar', 'learn_press_update_user_profile_avatar' );",
"/**\n * Update user basic information.\n *\n * @param bool $wp_error - Optional. Return WP_Error object in case updating failed.\n *\n * @return bool|mixed|WP_Error\n */\nfunction learn_press_update_user_profile_basic_information( $wp_error = false ) {\n\t$user_id = get_current_user_id();",
"\tif ( ! $user_id ) {\n\t\treturn new WP_Error( 2, 'User is invalid!' );\n\t}",
"\t$update_data = array(\n\t\t'ID' => $user_id,\n\t\t'first_name' => filter_input( INPUT_POST, 'first_name', FILTER_SANITIZE_STRING ),\n\t\t'last_name' => filter_input( INPUT_POST, 'last_name', FILTER_SANITIZE_STRING ),\n\t\t'description' => filter_input( INPUT_POST, 'description', FILTER_SANITIZE_STRING ),\n\t\t'display_name' => filter_input( INPUT_POST, 'account_display_name', FILTER_SANITIZE_STRING ),\n\t\t'user_email' => filter_input( INPUT_POST, 'account_email', FILTER_SANITIZE_EMAIL ),\n\t);",
"\t$update_data = apply_filters( 'learn-press/update-profile-basic-information-data', $update_data );\n\t$update_meta = isset( $_POST['_lp_custom_register'] ) ? LP_Helper::sanitize_params_submitted( $_POST['_lp_custom_register'] ) : '';",
"\t$return = LP_Forms_Handler::update_user_data( $update_data, $update_meta );",
"\t// Update for social.\n\t$socials = LP_Request::get_array( 'user_profile_social' );\n\t$extra_data = get_user_meta( $user_id, '_lp_extra_info', true );",
"\tif ( ! empty( $extra_data ) ) {\n\t\t$socials = array_merge( $extra_data, $socials );\n\t}",
"\tupdate_user_meta( $user_id, '_lp_extra_info', $socials );",
"\tif ( is_wp_error( $return ) ) {\n\t\treturn $wp_error ? $return : false;\n\t}",
"\treturn $return;\n}",
"/**\n * Update new password.\n */\nfunction learn_press_update_user_profile_change_password( $wp_error = false ) {\n\t$user_id = get_current_user_id();",
"\tif ( ! $user_id ) {\n\t\treturn new WP_Error( 2, 'User is invalid!' );\n\t}",
"\t$old_pass = filter_input( INPUT_POST, 'pass0' );\n\t$check_old_pass = false;",
"\tif ( $old_pass ) {\n\t\t$user = wp_get_current_user();\n\t\trequire_once ABSPATH . 'wp-includes/class-phpass.php';\n\t\t$wp_hasher = new PasswordHash( 8, true );",
"\t\tif ( $wp_hasher->CheckPassword( $old_pass, $user->data->user_pass ) ) {\n\t\t\t$check_old_pass = true;\n\t\t}\n\t}",
"\ttry {\n\t\tif ( ! $check_old_pass ) {\n\t\t\tthrow new Exception( __( 'Old password incorrect!', 'learnpress' ) );\n\t\t} else {\n\t\t\t$new_pass = filter_input( INPUT_POST, 'pass1' );\n\t\t\t$new_pass2 = filter_input( INPUT_POST, 'pass2' );",
"\t\t\tif ( ! $new_pass || ! $new_pass2 || ( $new_pass != $new_pass2 ) ) {\n\t\t\t\tthrow new Exception( __( 'Confirmation password incorrect!', 'learnpress' ) );\n\t\t\t} else {\n\t\t\t\t$update_data = array(\n\t\t\t\t\t'user_pass' => $new_pass,\n\t\t\t\t\t'ID' => get_current_user_id(),\n\t\t\t\t);\n\t\t\t\t$return = wp_update_user( $update_data );",
"\t\t\t\tif ( is_wp_error( $return ) ) {\n\t\t\t\t\treturn $wp_error ? $return : false;\n\t\t\t\t}",
"\t\t\t\treturn $return;\n\t\t\t}\n\t\t}\n\t} catch ( Exception $ex ) {\n\t\treturn $wp_error ? new WP_Error( 'UPDATE_PROFILE_ERROR', $ex->getMessage() ) : false;\n\t}\n}",
"function learn_press_get_avatar_thumb_size() {\n\t$option = LP_Settings::get_option(\n\t\t'avatar_dimensions',\n\t\tarray(\n\t\t\t'width' => 250,\n\t\t\t'height' => 250,\n\t\t)\n\t);",
"\tif ( ! isset( $option['width'] ) || ! isset( $option['height'] ) ) {\n\t\t$option = array(\n\t\t\t'width' => 250,\n\t\t\t'height' => 250,\n\t\t);\n\t}",
"\treturn $option;\n}",
"function learn_press_get_course_thumbnail_dimensions() {\n\t$option = LP_Settings::get_option(\n\t\t'course_thumbnail_dimensions',\n\t\tarray(\n\t\t\t'width' => 500,\n\t\t\t'height' => 300,\n\t\t)\n\t);",
"\tif ( ! isset( $option['width'] ) || ! isset( $option['height'] ) ) {\n\t\t$option = array(\n\t\t\t'width' => 500,\n\t\t\t'height' => 300,\n\t\t);\n\t}",
"\treturn $option;\n}",
"/**\n * Set a fake cookie to\n */\nfunction learn_press_set_user_cookie_for_guest() {\n\tif ( ! is_admin() && ! headers_sent() ) {\n\t\t$guest_key = '_wordpress_lp_guest';",
"\t\tif ( is_user_logged_in() ) {\n\t\t\tif ( ! empty( $_COOKIE[ $guest_key ] ) ) {\n\t\t\t\tlearn_press_remove_cookie( $guest_key );\n\t\t\t}\n\t\t} else {\n\t\t\tif ( empty( $_COOKIE[ $guest_key ] ) ) {\n\t\t\t\tlearn_press_setcookie( $guest_key, md5( time() ), time() + 3600 );\n\t\t\t}\n\t\t}\n\t}\n}",
"add_action( 'wp', 'learn_press_set_user_cookie_for_guest' );",
"function learn_press_get_user_avatar( $user_id = 0, $size = '' ) {\n\t$user = learn_press_get_user( $user_id );",
"\treturn $user->get_profile_picture( '', $size );\n}",
"/**\n * Get profile instance for an user to view.\n *\n * @param int $for_user\n *\n * @return LP_Profile|WP_Error\n */\nfunction learn_press_get_profile( $for_user = 0 ) {\n\treturn LP_Profile::instance( $for_user );\n}",
"/**\n * Remove items from learnpress_user_items.\n *\n * @param int $user_id\n * @param int $item_id\n * @param int $course_id\n * @param bool $include_course - Optional. If TRUE then remove course and it's items\n */\nfunction learn_press_remove_user_items( $user_id, $item_id, $course_id, $include_course = false ) {\n\tglobal $wpdb;",
"\tsettype( $item_id, 'array' );",
"\t$format = array_fill( 0, sizeof( $item_id ), '%d' );\n\t$where = '';",
"\t$args = array( $user_id );\n\t$args = array_merge( $args, $item_id );",
"\tif ( $course_id ) {\n\t\t$args[] = $course_id;\n\t\t$where = 'AND ref_id = %d';\n\t}",
"\tif ( $include_course ) {\n\t\t$where .= ' OR ( item_id = %d AND item_type = %s )';\n\t\t$args[] = $course_id;\n\t\t$args[] = LP_COURSE_CPT;\n\t}",
"\t$query = $wpdb->prepare(\n\t\t\"\n DELETE\n FROM {$wpdb->learnpress_user_items}\n WHERE user_id = %d\n AND ( item_id IN(\" . join( ',', $format ) . \")\n $where )\n \",\n\t\t$args\n\t);\n}",
"/**\n * Get user profile link\n *\n * @param int $user_id\n * @param null $tab\n *\n * @return mixed|string\n */\nfunction learn_press_user_profile_link( $user_id = 0, $tab = null ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}\n\t$user = false;\n\t$deleted = in_array( $user_id, LP_User_Factory::$_deleted_users );\n\tif ( ! $deleted ) {\n\t\tif ( is_numeric( $user_id ) ) {\n\t\t\t$user = get_user_by( 'id', $user_id );\n\t\t} else {\n\t\t\t$user = get_user_by( 'login', urldecode( $user_id ) );\n\t\t}\n\t} else {\n\t\treturn '';\n\t}\n\tif ( ! $deleted && ! $user ) {\n\t\tLP_User_Factory::$_deleted_users[] = $user_id;\n\t}",
"\t$user = learn_press_get_user( $user_id );",
"\tif ( ! $user ) {\n\t\treturn '';\n\t}",
"\tglobal $wp_query;\n\t$args = array(\n\t\t'user' => $user->get_username(),\n\t);",
"\tif ( isset( $args['user'] ) ) {\n\t\tif ( '' === $tab ) {\n\t\t\t$tab = learn_press_get_current_profile_tab();\n\t\t}\n\t\tif ( $tab ) {\n\t\t\t$args['tab'] = $tab;\n\t\t}",
"\t\t/**\n\t\t * If no tab is selected in profile and is current user\n\t\t * then no need the username in profile link.\n\t\t */\n\t\tif ( ( $user_id == get_current_user_id() ) && ! isset( $args['tab'] ) ) {\n\t\t\tunset( $args['user'] );\n\t\t}\n\t}\n\t$args = array_map( '_learn_press_urlencode', $args );\n\t$profile_link = trailingslashit( learn_press_get_page_link( 'profile' ) );\n\tif ( $profile_link ) {\n\t\tif ( get_option( 'permalink_structure' ) /*&& learn_press_get_page_id( 'profile' )*/ ) {\n\t\t\t$url = trailingslashit( $profile_link . join( '/', array_values( $args ) ) );\n\t\t} else {\n\t\t\t$url = add_query_arg( $args, $profile_link );\n\t\t}\n\t} else {\n\t\t$url = get_author_posts_url( $user_id );\n\t}",
"\treturn apply_filters( 'learn_press_user_profile_link', $url, $user_id, $tab );\n}",
"/**********************************************/\n/* Functions are used for hooks */\n/**********************************************/",
"function learn_press_hk_before_start_quiz( $true, $quiz_id, $course_id, $user_id ) {\n\tif ( 'yes' !== get_post_meta( $quiz_id, '_lp_archive_history', true ) ) {\n\t\tlearn_press_remove_user_items( $user_id, $quiz_id, $course_id );\n\t}",
"\treturn $true;\n}",
"add_filter( 'learn-press/before-start-quiz', 'learn_press_hk_before_start_quiz', 10, 4 );",
"/*function learn_press_default_user_item_status( $item_id ) {\n\t$status = '';\n\tswitch ( learn_press_get_post_type( $item_id ) ) {\n\t\tcase LP_LESSON_CPT:\n\t\t\t$status = 'started';\n\t\t\tbreak;\n\t\tcase LP_QUIZ_CPT:\n\t\t\t$status = 'viewed';\n\t\t\tbreak;\n\t\tcase LP_COURSE_CPT:\n\t\t\t$status = 'enrolled';\n\t}",
"\treturn apply_filters( 'learn-press/default-user-item-status', $status, $item_id );\n}*/",
"/**\n * Get current state of distraction mode\n *\n * @return mixed\n * @since 3.1.0\n */\nfunction learn_press_get_user_distraction() {\n\tif ( is_user_logged_in() ) {\n\t\treturn get_user_option( 'distraction_mode', get_current_user_id() );\n\t} else {\n\t\treturn LP()->session->distraction_mode;\n\t}\n}",
"function learn_press_get_user_role( $user_id ) {\n\tif ( $user = learn_press_get_user( $user_id ) ) {\n\t\treturn $user->get_role();\n\t}",
"\treturn false;\n}",
"/**\n * @param array $args\n * @param bool $wp_error\n *\n * @return bool|int|LP_User_Item|mixed|WP_Error\n */\nfunction learn_press_create_user_item( $args = array(), $wp_error = false ) {\n\tglobal $wpdb;",
"\t$defaults = array(\n\t\t'user_id' => get_current_user_id(),\n\t\t'item_id' => '',\n\t\t'start_time' => current_time( 'mysql', true ),\n\t\t'end_time' => '',\n\t\t'graduation' => '',\n\t\t'item_type' => '',\n\t\t'status' => '',\n\t\t'ref_id' => 0,\n\t\t'ref_type' => 0,\n\t\t'parent_id' => 0,\n\t\t'create_meta' => array(),\n\t);",
"\t$item_data = wp_parse_args( $args, $defaults );",
"\t// Validate item_id and post type\n\tif ( empty( $item_data['item_id'] ) ) {\n\t\tif ( $wp_error ) {\n\t\t\treturn new WP_Error( 'invalid_item_id', __( 'Invalid item id.', 'learnpress' ) );\n\t\t}",
"\t\treturn 0;\n\t}",
"\tif ( empty( $item_data['item_type'] ) && $post_type = learn_press_get_post_type( $item_data['item_id'] ) ) {\n\t\t$item_data['item_type'] = $post_type;\n\t}",
"\t// Get id and type of ref if they are null\n\tif ( ! empty( $item_data['parent_id'] ) && ( empty( $item_data['ref_id'] ) || ( empty( $item_data['ref_type'] ) ) ) ) {\n\t\t$parent = $wpdb->get_row(\n\t\t\t$wpdb->prepare(\n\t\t\t\t\"SELECT * FROM {$wpdb->learnpress_user_items} WHERE %d\",\n\t\t\t\t$item_data['parent_id']\n\t\t\t)\n\t\t);",
"\t\tif ( $parent ) {\n\t\t\tif ( empty( $item_data['ref_id'] ) ) {\n\t\t\t\t$item_data['ref_id'] = $parent->item_id;\n\t\t\t}",
"\t\t\tif ( empty( $item_data['ref_type'] ) ) {\n\t\t\t\t$item_data['ref_type'] = $parent->item_type;\n\t\t\t}\n\t\t}\n\t}",
"\t// Filter\n\tif ( ! $item_data = apply_filters( 'learn-press/create-user-item-data', $item_data ) ) {\n\t\tif ( $wp_error ) {\n\t\t\treturn new WP_Error( 'invalid_item_data', __( 'Invalid item data.', 'learnpress' ) );\n\t\t}",
"\t\treturn 0;\n\t}",
"\tdo_action( 'learn-press/before-create-user-item', $item_data );",
"\t$create_meta = ! empty( $item_data['create_meta'] ) ? $item_data['create_meta'] : false;",
"\tif ( $create_meta ) {\n\t\tunset( $item_data['create_meta'] );\n\t}",
"\t$user_item = new LP_User_Item( $item_data );",
"\t$result = $user_item->update( true, false );",
"\tif ( ! $result || is_wp_error( $result ) ) {",
"\t\tif ( $wp_error && is_wp_error( $result ) ) {\n\t\t\treturn $result;\n\t\t}",
"\t\treturn 0;\n\t}",
"\tdo_action( 'learn-press/created-user-item', $user_item, $item_data );",
"\t$create_meta = apply_filters( 'learn-press/create-user-item-meta', $create_meta, $item_data );\n\tif ( ! $create_meta ) {\n\t\treturn $user_item;\n\t}",
"\tdo_action( 'learn-press/before-create-user-item-meta', $create_meta );",
"\tforeach ( $create_meta as $key => $value ) {\n\t\tlearn_press_update_user_item_meta( $user_item->get_user_item_id(), $key, $value );\n\t}",
"\tdo_action( 'learn-press/created-user-item-meta', $user_item, $create_meta );",
"\treturn $user_item;\n}",
"/**\n * @param array $args\n * @param bool $wp_error - Optional. TRUE will return WP_Error on fail.\n *\n * @return bool|array|LP_User_Item|WP_Error\n */\nfunction learn_press_create_user_item_for_quiz( $args = array(), $wp_error = false ) {\n\tglobal $wpdb;",
"\t$item_data = wp_parse_args(\n\t\t$args,\n\t\tarray(\n\t\t\t'item_type' => LP_QUIZ_CPT,\n\t\t\t'status' => LP_ITEM_STARTED,\n\t\t\t'graduation' => LP_COURSE_GRADUATION_IN_PROGRESS,\n\t\t\t'user_id' => get_current_user_id(),\n\t\t)\n\t);",
"\t$user_item = learn_press_create_user_item( $item_data, $wp_error );",
"\tif ( $user_item && ! is_wp_error( $user_item ) ) {\n\t\t$user_item = new LP_User_Item_Quiz( $user_item->get_data() );\n\t\t$user_item->update( true );\n\t}",
"\treturn $user_item;\n}",
"/**\n * Get list user_item_id for Quiz in table learnpress_user_items\n *\n * @param int $quiz_id\n * @param int $course_id\n * @return array || false\n */\nfunction learn_press_isset_user_item_for_quiz( $quiz_id, $course_id ) {\n\tglobal $wpdb;",
"\t$query = $wpdb->prepare( \"SELECT user_item_id FROM $wpdb->learnpress_user_items WHERE ref_id=%d AND item_id=%d\", $course_id, $quiz_id );\n\t$col = $wpdb->get_col( $query );",
"\tif ( ! empty( $col ) ) {\n\t\treturn $col;\n\t} else {\n\t\treturn false;\n\t}\n}",
"/**\n * Create new user item prepare for user starts a quiz\n * Update error retry course not work - Nhamdv.\n *\n * @param int $quiz_id\n * @param int $user_id\n * @param int $course_id\n * @param bool $wp_error\n *\n * @return array|bool|LP_User_Item|WP_Error\n * @since 4.0.0\n */\nfunction learn_press_user_start_quiz( $quiz_id, $user_id = 0, $course_id = 0, $wp_error = false ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}",
"\tglobal $wpdb;",
"\t$query = $wpdb->prepare(\n\t\t\"\n\t SELECT user_item_id, item_id id, item_type type\n\t FROM {$wpdb->learnpress_user_items}\n\t WHERE user_item_id = (SELECT max(user_item_id)\n\t FROM {$wpdb->learnpress_user_items}\n\t WHERE user_id = %d AND item_id = %d AND status IN ('enrolled', 'in-progress'))\n\t\",\n\t\t$user_id,\n\t\t$course_id\n\t);",
"\t$parent = $wpdb->get_row( $query );",
"\tdo_action( 'learn-press/before-user-start-quiz', $quiz_id, $user_id, $course_id );",
"\t$user = learn_press_get_user( $user_id );\n\t$course_data = $user->get_course_data( $course_id );\n\t$quiz_data = $course_data->get_item( $quiz_id );",
"\t$quiz = LP_Quiz::get_quiz( $quiz_id );\n\t$duration = $quiz->get_duration();\n\t$user_quiz = learn_press_create_user_item_for_quiz(\n\t\tarray(\n\t\t\t'user_item_id' => $quiz_data ? $quiz_data->get_user_item_id() : 0,\n\t\t\t'item_id' => $quiz->get_id(),\n\t\t\t'duration' => $duration ? $duration->get() : 0,\n\t\t\t'user_id' => $user_id,\n\t\t\t'parent_id' => $parent ? absint( $parent->user_item_id ) : 0,\n\t\t\t'ref_type' => $parent ? $parent->type : '',\n\t\t\t'ref_id' => $parent ? $parent->id : '',\n\t\t),\n\t\t$wp_error\n\t);",
"\tif ( $user_quiz && ! is_wp_error( $user_quiz ) ) {\n\t\tdo_action( 'learn-press/user-started-quiz', $user_quiz, $quiz_id, $user_id, $course_id );\n\t}",
"\t// Reset first cache\n\t$user_quiz->get_status( 'status', true );",
"\treturn $user_quiz;\n}",
"/**\n * Function retake quiz.\n *\n * @param [type] $quiz_id\n * @param integer $user_id\n * @param integer $course_id\n * @param boolean $wp_error\n *\n * @return void\n */\nfunction learn_press_user_retake_quiz( $quiz_id, $user_id = 0, $course_id = 0, $wp_error = false ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}",
"\tif ( ! $course_id ) {\n\t\treturn new WP_Error( 'invalid_course_id', esc_html__( 'Invalid Course ID.', 'learnpress' ) );\n\t}",
"\tglobal $wpdb;",
"\t$query = $wpdb->prepare(\n\t\t\"\n\t SELECT user_item_id, item_id id, item_type type\n\t FROM {$wpdb->learnpress_user_items}\n\t WHERE user_item_id = (SELECT max(user_item_id)\n\t FROM {$wpdb->learnpress_user_items}\n\t WHERE user_id = %d AND item_id = %d AND status IN ('enrolled', 'in-progress'))\n\t\t\",\n\t\t$user_id,\n\t\t$course_id\n\t);",
"\t$parent = $wpdb->get_row( $query );",
"\tif ( ! $parent ) {\n\t\treturn new WP_Error( 'invalid_user_item', esc_html__( 'Invalid Quiz', 'learnpress' ) );\n\t}",
"\t$data = learn_press_get_user_item(\n\t\tarray(\n\t\t\t'item_id' => $quiz_id,\n\t\t\t'user_id' => $user_id,\n\t\t\t'parent_id' => $parent ? absint( $parent->user_item_id ) : 0,\n\t\t\t'ref_type' => $parent ? $parent->type : LP_COURSE_CPT,\n\t\t\t'ref_id' => $parent ? $parent->id : '',\n\t\t)\n\t);",
"\t$user_item = new LP_User_Item_Quiz( $data );",
"\t$user_item->update_retake_count();",
"\t// Create new result in table learnpress_user_item_results.\n\tLP_User_Items_Result_DB::instance()->insert( $data->user_item_id );",
"\t// Remove user_item_meta.\n\tlearn_press_delete_user_item_meta( $data->user_item_id, '_lp_question_checked' );",
"\t$user_item->set_status( LP_ITEM_STARTED )\n\t\t\t\t->set_start_time( current_time( 'mysql', 1 ) ) // Error Retake when change timezone - Nhamdv\n\t\t\t\t->set_end_time( '' )\n\t\t\t\t->set_graduation( LP_COURSE_GRADUATION_IN_PROGRESS )\n\t\t\t\t->update();",
"\t// Reset first cache\n\t$user_item->get_status( 'status', true );",
"\t// Error Retake when change timezone - Nhamdv\n\t// learn_press_update_user_item_field(\n\t// array(\n\t// 'start_time' => current_time( 'mysql', true ),\n\t// ),\n\t// array(\n\t// 'user_item_id' => $data->user_item_id,\n\t// )\n\t// );",
"\treturn $user_item;\n}",
"\n/**\n * Prepares list of questions for rest api.\n *\n * @param int[] $question_ids\n * @param array $args\n *\n * @return array\n * @since 3.3.0\n */\nfunction learn_press_rest_prepare_user_questions( array $question_ids = array(), array $args = array() ) : array {\n\tif ( is_numeric( $args ) ) {",
"\t} else {\n\t\t$args = wp_parse_args(\n\t\t\t$args,\n\t\t\tarray(\n\t\t\t\t'instant_hint' => true,\n\t\t\t\t'instant_check' => true,\n\t\t\t\t'quiz_status' => '',\n\t\t\t\t'checked_questions' => array(),\n\t\t\t\t'hinted_questions' => array(),\n\t\t\t\t'answered' => array(),\n\t\t\t\t'show_correct_review' => true,\n\t\t\t)\n\t\t);\n\t}",
"\t$checkedQuestions = $args['checked_questions'];\n\t$hintedQuestions = $args['hinted_questions'];\n\t$instantHint = $args['instant_hint'];\n\t$instantCheck = $args['instant_check'];\n\t$quizStatus = $args['quiz_status'];\n\t$answered = $args['answered'];\n\t$status = $args['status'] ?? '';\n\t$questions = array();",
"\tif ( $question_ids ) {\n\t\tforeach ( $question_ids as $id ) {\n\t\t\t$question = learn_press_get_question( $id );\n\t\t\t$hasHint = false;\n\t\t\t$hasExplanation = false;\n\t\t\t$canCheck = false;\n\t\t\t$hinted = false;\n\t\t\t$checked = false;\n\t\t\t$theHint = $question->get_hint();\n\t\t\t$theExplanation = '';",
"\t\t\tif ( $instantCheck || $status == 'completed' ) {\n\t\t\t\t$theExplanation = $question->get_explanation();\n\t\t\t\t$checked = in_array( $id, $checkedQuestions );\n\t\t\t\t$hasExplanation = ! ! $theExplanation;\n\t\t\t}",
"\t\t\t $mark = $question->get_mark() ? $question->get_mark() : 1;",
"\t\t\t$questionData = array(\n\t\t\t\t'object' => $question,\n\t\t\t\t'id' => absint( $id ),\n\t\t\t\t'title' => $question->get_title(),\n\t\t\t\t'type' => $question->get_type(),\n\t\t\t\t'point' => $mark,\n\t\t\t);",
"\t\t\t$content = $question->get_content();\n\t\t\tif ( $content ) {\n\t\t\t\t$questionData['content'] = $content;\n\t\t\t}",
"\t\t\tif ( $theHint ) {\n\t\t\t\t$questionData['hint'] = $theHint;\n\t\t\t}",
"\t\t\tif ( $status == 'completed' || ( $checked && $theExplanation ) ) {\n\t\t\t\t$questionData['explanation'] = $theExplanation;\n\t\t\t}",
"\t\t\tif ( $hasExplanation ) {\n\t\t\t\t$questionData['has_explanation'] = $hasExplanation;",
"\t\t\t\tif ( $checked ) {\n\t\t\t\t\t$questionData['explanation'] = $theExplanation;\n\t\t\t\t}\n\t\t\t}",
"\t\t\t$with_true_or_false = ( $checked || ( $quizStatus == 'completed' && $args['show_correct_review'] ) );",
"\t\t\tif ( $question->is_support( 'answer-options' ) ) {\n\t\t\t\t$questionData['options'] = learn_press_get_question_options_for_js(\n\t\t\t\t\t$question,\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'include_is_true' => $with_true_or_false,\n\t\t\t\t\t\t'answer' => $answered[ $id ]['answered'] ?? '',\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}",
"\t\t\t$questions[] = $questionData;\n\t\t}",
"\t\t/**\n\t\t * Remove answered\n\t\t */\n\t\tif ( $quizStatus !== 'completed' ) {\n\t\t\tif ( $checkedQuestions && $quizStatus ) {",
"\t\t\t\t$omitIds = array_diff( $question_ids, $checkedQuestions );",
"\t\t\t\tif ( $omitIds ) {\n\t\t\t\t\tforeach ( $omitIds as $omitId ) {\n\t\t\t\t\t\tif ( ! empty( $answered[ $omitId ] ) ) {\n\t\t\t\t\t\t\tunset( $answered[ $omitId ] );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"\treturn apply_filters( 'learn-press/list-questions-data', $questions );\n}",
"/**\n * Output html to show extra info of user in backend profile.\n *\n * @param WP_User $user\n *\n * @since 4.0.0\n */\n/*function learn_press_append_user_profile_fields( $user ) {\n\tif ( ! is_admin() ) {\n\t\treturn;\n\t}",
"\tlearn_press_admin_view( 'backend-user-profile', array( 'user' => $user ) );\n}*/",
"//add_action( 'show_user_profile', 'learn_press_append_user_profile_fields' );\n//add_action( 'edit_user_profile', 'learn_press_append_user_profile_fields' );",
"/**\n * Update extra profile data upon update user.\n *\n * @param int $user_id\n *\n * @since 4.0.0\n */\nfunction learn_press_update_extra_user_profile_fields( $user_id ) {\n\tif ( ! current_user_can( 'edit_user', $user_id ) ) {\n\t\treturn;\n\t}",
"\tif ( isset( $_POST['_lp_extra_info'] ) ) {\n\t\tupdate_user_meta( $user_id, '_lp_extra_info', $_POST['_lp_extra_info'] );\n\t}\n}",
"add_action( 'personal_options_update', 'learn_press_update_extra_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'learn_press_update_extra_user_profile_fields' );",
"/**\n * Get extra profile info data\n *\n * @param int $user_id\n *\n * @return array\n * @since 4.0.0\n */\nfunction learn_press_get_user_extra_profile_info( $user_id = 0 ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}",
"\t$extra_profile_info = get_the_author_meta( '_lp_extra_info', $user_id );\n\t$extra_fields = learn_press_get_user_extra_profile_fields();",
"\t$extra_profile_info = wp_parse_args(\n\t\t$extra_profile_info,\n\t\tarray_fill_keys( array_keys( $extra_fields ), '' )\n\t);",
"\treturn apply_filters( 'learn-press/user-extra-profile-info', $extra_profile_info, $user_id );\n}",
"function learn_press_social_profiles() {\n\treturn apply_filters(\n\t\t'learn-press/social-profiles',\n\t\tarray(\n\t\t\t'facebook',\n\t\t\t'twitter',\n\t\t\t'youtube',\n\t\t\t'linkedin',\n\t\t)\n\t);\n}",
"function lp_add_default_fields( $fields ) {\n\t$first_name = LP()->settings()->get( 'enable_register_first_name' );",
"\tif ( $first_name === 'yes' ) {\n\t\t?>\n\t\t<li class=\"form-field\">\n\t\t\t<label for=\"reg_first_name\"><?php esc_html_e( 'First name', 'learnpress' ); ?></label>\n\t\t\t<input id=\"reg_first_name\" name=\"reg_first_name\" type=\"text\"\n\t\t\t\t placeholder=\"<?php esc_attr_e( 'First name', 'learnpress' ); ?>\"\n\t\t\t\t value=\"<?php echo ( ! empty( $_POST['reg_first_name'] ) ) ? esc_attr( wp_unslash( $_POST['reg_first_name'] ) ) : ''; ?>\">\n\t\t</li>\n\t\t<?php\n\t}",
"\t$last_name = LP()->settings()->get( 'enable_register_last_name' );",
"\tif ( $last_name === 'yes' ) {\n\t\t?>\n\t\t<li class=\"form-field\">\n\t\t\t<label for=\"reg_last_name\"><?php esc_html_e( 'Last name', 'learnpress' ); ?></label>\n\t\t\t<input id=\"reg_last_name\" name=\"reg_last_name\" type=\"text\"\n\t\t\t\t placeholder=\"<?php esc_attr_e( 'Last name', 'learnpress' ); ?>\"\n\t\t\t\t value=\"<?php echo ( ! empty( $_POST['reg_last_name'] ) ) ? esc_attr( wp_unslash( $_POST['reg_last_name'] ) ) : ''; ?>\">\n\t\t</li>\n\t\t<?php\n\t}",
"\t$display_name = LP()->settings()->get( 'enable_register_display_name' );",
"\tif ( $display_name === 'yes' ) {\n\t\t?>\n\t\t<li class=\"form-field\">\n\t\t\t<label for=\"reg_display_name\"><?php esc_html_e( 'Display name', 'learnpress' ); ?></label>\n\t\t\t<input id=\"reg_display_name\" name=\"reg_display_name\" type=\"text\"\n\t\t\t\t placeholder=\"<?php esc_attr_e( 'Display name', 'learnpress' ); ?>\"\n\t\t\t\t value=\"<?php echo ( ! empty( $_POST['reg_display_name'] ) ) ? esc_attr( wp_unslash( $_POST['reg_display_name'] ) ) : ''; ?>\">\n\t\t</li>\n\t\t<?php\n\t}\n}",
"add_filter( 'learn-press/after-form-register-fields', 'lp_add_default_fields' );",
"function lp_custom_register_fields_display() {\n\t?>\n\t<?php $custom_fields = LP()->settings()->get( 'register_profile_fields' ); ?>",
"\t<?php if ( $custom_fields ) : ?>\n\t\t<?php foreach ( $custom_fields as $custom_field ) : ?>\n\t\t\t<?php\n\t\t\t$cf_class = '';\n\t\t\tif ( $custom_field['required'] == 'yes' ) {\n\t\t\t\t$cf_class = ' required';\n\t\t\t\t?>\n\t\t\t\t<style>\n\t\t\t\t\t.required label {\n\t\t\t\t\t\tfont-weight: bold;\n\t\t\t\t\t}\n\t\t\t\t\t.required label:after {\n\t\t\t\t\t\tcontent: ' *';\n\t\t\t\t\t\tdisplay:inline;\n\t\t\t\t\t}\n\t\t\t\t</style>\n\t\t\t\t<?php\n\t\t\t}",
"\t\t\tif ( isset( $custom_field['id'] ) ) {\n\t\t\t\t?>\n\t\t\t\t<?php $value = $custom_field['id']; ?>",
"\t\t\t\t<li class=\"form-field<?php echo esc_attr( $cf_class ); ?>\">\n\t\t\t\t\t<?php\n\t\t\t\t\tswitch ( $custom_field['type'] ) {\n\t\t\t\t\t\tcase 'text':\n\t\t\t\t\t\tcase 'number':\n\t\t\t\t\t\tcase 'email':\n\t\t\t\t\t\tcase 'url':\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t<label for=\"description\"><?php echo esc_html( $custom_field['name'] ); ?></label>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\tcase 'tel':\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t<input name=\"_lp_custom_register_form[<?php echo $value; ?>]\"\n\t\t\t\t\t\t\t\t type=\"<?php echo $custom_field['type']; ?>\" class=\"regular-text\"\n\t\t\t\t\t\t\t\t value=\"\">\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'textarea':\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t<label for=\"description\"><?php echo esc_html( $custom_field['name'] ); ?></label>\n\t\t\t\t\t\t\t<textarea name=\"_lp_custom_register_form[<?php echo $value; ?>]\"></textarea>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'checkbox':\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t<label>\n\t\t\t\t\t\t\t\t<input name=\"_lp_custom_register_form[<?php echo $value; ?>]\"\n\t\t\t\t\t\t\t\t\t type=\"<?php echo $custom_field['type']; ?>\" value=\"1\">\n\t\t\t\t\t\t\t\t<?php echo esc_html( $custom_field['name'] ); ?>\n\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t?>\n\t\t\t\t</li>\n\t\t\t<?php } ?>\n\t\t<?php endforeach; ?>\n\t<?php endif; ?>\n\t<?php\n}",
"add_action( 'learn-press/after-form-register-fields', 'lp_custom_register_fields_display' );",
"/**\n * Custom register fields\n *\n * @param [type] $user_id\n *\n * @return void\n */\nfunction lp_user_custom_register_fields( $user_id, $fields = array() ) {\n\tif ( ! empty( $fields ) ) {\n\t\tupdate_user_meta( $user_id, '_lp_custom_register', LP_Helper::sanitize_params_submitted( $fields ) );\n\t} elseif ( isset( $_POST['_lp_custom_register'] ) ) {\n\t\tupdate_user_meta( $user_id, '_lp_custom_register', LP_Helper::sanitize_params_submitted( $_POST['_lp_custom_register'] ) );\n\t}\n}",
"add_action( 'personal_options_update', 'lp_user_custom_register_fields' );\nadd_action( 'edit_user_profile_update', 'lp_user_custom_register_fields' );",
"function lp_get_user_custom_register_fields( $user_id = 0 ) {\n\tif ( ! $user_id ) {\n\t\t$user_id = get_current_user_id();\n\t}",
"\t$register_fields = get_the_author_meta( '_lp_custom_register', $user_id );\n\t$defaults = lp_get_user_custom_fields();",
"\t$extra_profile_info = wp_parse_args( $register_fields, $defaults );",
"\treturn apply_filters( 'lp/user-custom-register-fields', $register_fields, $user_id );\n}",
"function lp_get_user_custom_fields() {\n\t$custom_fields = LP()->settings()->get( 'register_profile_fields' );",
"\t$output = array();",
"\tif ( $custom_fields ) {\n\t\tforeach ( $custom_fields as $field ) {\n\t\t\t$output[ $field['id'] ] = '';\n\t\t}\n\t}",
"\treturn $output;\n}",
"/**\n * Check extra user data is a social profile.\n *\n * @param $key\n *\n * @return bool\n * @since 4.0.0\n */\nfunction learn_press_is_social_profile( $key ) {\n\t$is_socials = learn_press_social_profiles();",
"\treturn in_array( $key, $is_socials );\n}",
"function learn_press_social_profile_name( $key ) {\n\t$name = '';\n\tswitch ( $key ) {\n\t\tcase 'facebook':\n\t\t\t$name = esc_html__( 'Facebook Profile', 'learnpress' );\n\t\t\tbreak;\n\t\tcase 'twitter':\n\t\t\t$name = esc_html__( 'Twitter Profile', 'learnpress' );\n\t\t\tbreak;\n\t\tcase 'googleplus':\n\t\t\t$name = esc_html__( 'Google Profile', 'learnpress' );\n\t\t\tbreak;\n\t\tcase 'youtube':\n\t\t\t$name = esc_html__( 'Youtube Channel', 'learnpress' );\n\t\t\tbreak;\n\t\tcase 'linkedin':\n\t\t\t$name = esc_html__( 'Linkedin Profile', 'learnpress' );\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t$name = ucfirst( $key );\n\t}",
"\treturn apply_filters( 'learn-press/social-profile-name', $name, $key );\n}",
"/**\n * Get extra profile fields will be registered in backend profile.\n *\n * @return array\n * @since 4.0.0\n */\nfunction learn_press_get_user_extra_profile_fields() {\n\t$socials = learn_press_social_profiles();\n\t$fields = array();",
"\tforeach ( $socials as $social ) {\n\t\t$fields[ $social ] = learn_press_social_profile_name( $social );\n\t}",
"\treturn apply_filters( 'learn-press/user-extra-profile-fields', $fields );\n}",
"/**\n * Show courses user enrolled on backend\n *\n * @param $user\n *\n * @return void\n */\nfunction learn_press_user_profile_data( $user ) {\n\tif ( ! is_admin() ) {\n\t\treturn;\n\t}",
"\tlearn_press_admin_view( 'backend-user-profile', array( 'user' => $user ) );\n\tlearn_press_admin_view( 'user/courses.php', array( 'user_id' => $user->ID ) );\n}\n//add_action( 'show_user_profile', 'learn_press_user_profile_data', 1000 );\nadd_action( 'edit_user_profile', 'learn_press_user_profile_data', 1000 );",
"function learnpress_get_count_by_user( $user_id = '', $post_type = 'lp_course' ) {\n\tif ( empty( $user_id ) ) {\n\t\treturn false;\n\t}",
"\t$args = array(\n\t\t'author' => $user_id,\n\t\t'posts_per_page' => - 1,\n\t\t'post_type' => $post_type,\n\t\t'post_status' => 'any',\n\t);",
"\t$posts = get_posts( $args );",
"\t$output = array(\n\t\t'all' => count( $posts ),\n\t\t'publish' => array(),\n\t\t'pending' => array(),\n\t);",
"\t$pending = $public = array();",
"\tif ( ! empty( $posts ) ) {\n\t\tforeach ( $posts as $post ) {\n\t\t\tswitch ( $post->post_status ) {\n\t\t\t\tcase 'pending':\n\t\t\t\t\t$pending[] = $post;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'publish':\n\t\t\t\t\t$public[] = $post;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}",
"\treturn array(\n\t\t'all' => count( $posts ),\n\t\t'publish' => count( $public ),\n\t\t'pending' => count( $pending ),\n\t);",
"}",
"/*\nadd_action(\n\t'admin_init',\n\tfunction() {\n\t\t$custom_fields = LP()->settings()->get( 'register_profile_fields' );",
"\t\t$custom_fields = LP_Helper::sanitize_params_submitted( $custom_fields );",
"\t\tif ( ! empty( $custom_fields ) ) {\n\t\t\t$output = array();",
"\t\t\tforeach ( $custom_fields as $key => $field ) {\n\t\t\t\tif ( ! isset( $field['id'] ) ) {\n\t\t\t\t\t$output[ $key ] = array(\n\t\t\t\t\t\t'id' => $field['name'],\n\t\t\t\t\t\t'name' => $field['name'] ?? '',\n\t\t\t\t\t\t'type' => $field['type'] ?? '',\n\t\t\t\t\t\t'required' => $field['required'] ?? '',\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\t$output[ $key ] = $field;\n\t\t\t\t}\n\t\t\t}",
"\t\t\tupdate_option( 'learn_press_register_profile_fields', $output );\n\t\t}\n\t}\n);*/"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [61, 1262, 233, 1156], "buggy_code_start_loc": [27, 1198, 14, 1081], "filenames": ["assets/src/js/frontend/profile.js", "inc/admin/class-lp-admin-ajax.php", "inc/class-lp-ajax.php", "inc/user/lp-user-functions.php"], "fixing_code_end_loc": [71, 1364, 200, 1152], "fixing_code_start_loc": [27, 1199, 14, 1082], "message": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thimpress:learnpress:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "F74AC61D-6728-4759-B5A4-F03B9519485C", "versionEndExcluding": "4.1.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Users of the LearnPress WordPress plugin before 4.1.5 can upload an image as a profile avatar after the registration. After this process the user crops and saves the image. Then a \"POST\" request that contains user supplied name of the image is sent to the server for renaming and cropping of the image. As a result of this request, the name of the user-supplied image is changed with a MD5 value. This process can be conducted only when type of the image is JPG or PNG. An attacker can use this vulnerability in order to rename an arbitrary image file. By doing this, they could destroy the design of the web site."}, {"lang": "es", "value": "Los usuarios del plugin LearnPress de WordPress versiones anteriores a 4.1.5, pueden subir una imagen como avatar de perfil tras el registro. Tras este proceso, el usuario recorta y guarda la imagen. A continuaci\u00f3n, se env\u00eda al servidor una petici\u00f3n \"POST\" que contiene el nombre de la imagen suministrado por el usuario para cambiar el nombre y recortar la imagen. Como resultado de esta petici\u00f3n, el nombre de la imagen suministrada por el usuario es cambiada con un valor MD5. Este proceso s\u00f3lo puede llevarse a cabo cuando el tipo de la imagen es JPG o PNG. Un atacante puede usar esta vulnerabilidad para cambiar el nombre de un archivo de imagen arbitrario. Al hacer esto, podr\u00edan destruir el dise\u00f1o del sitio web."}], "evaluatorComment": null, "id": "CVE-2022-0377", "lastModified": "2022-03-08T16:39:46.640", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-28T09:15:09.093", "references": [{"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://bozogullarindan.com/en/2022/01/wordpress-learnpress-plugin-4.1.4.1-arbitrary-image-renaming/"}, {"source": "contact@wpscan.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, {"source": "contact@wpscan.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://wpscan.com/vulnerability/0d95ada6-53e3-4a80-a395-eacd7b090f26"}], "sourceIdentifier": "contact@wpscan.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-610"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-73"}], "source": "contact@wpscan.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/LearnPress/learnpress/commit/d1dc4af7ef2950f1000abc21bd9520fb3eb98faf"}, "type": "CWE-610"}
| 263
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*if ($_SERVER['SERVER_ADDR'] == \"127.0.0.1\")\n $root = $_SERVER['DOCUMENT_ROOT'].\"/sigeprosi\";\n else\n $root = \"/home/ps6116-02/public_html/sigeprosi\";\n*/\n$root = $_SERVER['DOCUMENT_ROOT'].\"/sigeprosi\";\ninclude_once $root.\"/class/class.Usuario.php\";\ninclude_once $root.\"/snippets/generarSal.php\";\ninclude_once $root.\"/class/class.Encrypter.php\";\ninclude_once $root.\"/class/class.fachadainterfaz.php\";",
"",
"if (isset($_POST[\"user\"])) {\n\t$user = $_POST[\"user\"];\n\tif (strpos($user, '@') === false) $user = $user.'@usb.ve';\n\techo 'Usuario: '.$user;\n $enc = new Encrypter($_POST[\"pass\"], generarSal($user));\n $codigo = $enc->toMD5();\n\t$u = new Usuario(null,null,$user,$codigo,null,null,null,null);\n if ($u->autocompletar() != 0)\theader(\"Location: ../principal.php?content=inicio&error=noRegistrado\");\n\telse if ($u->get('password') != $codigo)\theader(\"Location: ../principal.php?content=inicio&error=errorPass\");\n\telse if ($u->get('activo')!=1) header(\"Location: ../principal.php?content=inicio&error=noActivo\");\n\telse {\n\t\tsession_start();\n\t\t$_SESSION[\"correoUSB\"]=$u->get(\"correoUSB\");\n\t\t$_SESSION[\"nombre\"] = $u->get(\"nombre\");\n\t\t$_SESSION[\"apellido\"] = $u->get(\"apellido\");\n\t\t$_SESSION[\"admin\"] = (($u->get(\"rol\")) == 0) || (($u->get(\"rol\")) == 1);\n\t\t$_SESSION[\"profesor\"] = (($u->get(\"rol\")) == 2) || (($u->get(\"rol\")) == 1);\n\t\t$_SESSION[\"estudiante\"] = (($u->get(\"rol\")) == 3) || (($u->get(\"rol\")) == 5);\n\t\t$_SESSION[\"coordinador\"] = (($u->get(\"rol\")) == 5);\n\t\tif ($_SESSION[\"coordinador\"]){\n\t\t\t$fachada = fachadaInterfaz::getInstance();\n\t\t\t$_SESSION[\"Equipo\"]=$fachada->buscarEquipoDeEstudiante($_SESSION[\"correoUSB\"]);\n\t\t}\n\t\t$_SESSION[\"cliente\"] = (($u->get(\"rol\")) == 4);\n\t\t$_SESSION['autenticado'] = true;\n\t\theader(\"Location: ../principal.php?content=inicio\");\n\t}\n}\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*if ($_SERVER['SERVER_ADDR'] == \"127.0.0.1\")\n $root = $_SERVER['DOCUMENT_ROOT'].\"/sigeprosi\";\n else\n $root = \"/home/ps6116-02/public_html/sigeprosi\";\n*/\n$root = $_SERVER['DOCUMENT_ROOT'].\"/sigeprosi\";\ninclude_once $root.\"/class/class.Usuario.php\";\ninclude_once $root.\"/snippets/generarSal.php\";\ninclude_once $root.\"/class/class.Encrypter.php\";\ninclude_once $root.\"/class/class.fachadainterfaz.php\";",
"require_once \"../aspectos/Seguridad.php\";\n$seguridad = Seguridad::getInstance();\n$seguridad->escapeSQL($_POST);",
"if (isset($_POST[\"user\"])) {\n\t$user = $_POST[\"user\"];\n\tif (strpos($user, '@') === false) $user = $user.'@usb.ve';\n\techo 'Usuario: '.$user;\n $enc = new Encrypter($_POST[\"pass\"], generarSal($user));\n $codigo = $enc->toMD5();\n\t$u = new Usuario(null,null,$user,$codigo,null,null,null,null);\n if ($u->autocompletar() != 0)\theader(\"Location: ../principal.php?content=inicio&error=noRegistrado\");\n\telse if ($u->get('password') != $codigo)\theader(\"Location: ../principal.php?content=inicio&error=errorPass\");\n\telse if ($u->get('activo')!=1) header(\"Location: ../principal.php?content=inicio&error=noActivo\");\n\telse {\n\t\tsession_start();\n\t\t$_SESSION[\"correoUSB\"]=$u->get(\"correoUSB\");\n\t\t$_SESSION[\"nombre\"] = $u->get(\"nombre\");\n\t\t$_SESSION[\"apellido\"] = $u->get(\"apellido\");\n\t\t$_SESSION[\"admin\"] = (($u->get(\"rol\")) == 0) || (($u->get(\"rol\")) == 1);\n\t\t$_SESSION[\"profesor\"] = (($u->get(\"rol\")) == 2) || (($u->get(\"rol\")) == 1);\n\t\t$_SESSION[\"estudiante\"] = (($u->get(\"rol\")) == 3) || (($u->get(\"rol\")) == 5);\n\t\t$_SESSION[\"coordinador\"] = (($u->get(\"rol\")) == 5);\n\t\tif ($_SESSION[\"coordinador\"]){\n\t\t\t$fachada = fachadaInterfaz::getInstance();\n\t\t\t$_SESSION[\"Equipo\"]=$fachada->buscarEquipoDeEstudiante($_SESSION[\"correoUSB\"]);\n\t\t}\n\t\t$_SESSION[\"cliente\"] = (($u->get(\"rol\")) == 4);\n\t\t$_SESSION['autenticado'] = true;\n\t\theader(\"Location: ../principal.php?content=inicio\");\n\t}\n}\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nombre\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaEquipo.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseEtapa = new listaEquipo();\n $result = $baseEtapa->cargar($sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$row['nombre'].\"'>\";\n echo \"<cell>\".$row['nombre'].\"</cell>\";\n if ($row['estado'] == 1)\n echo \"<cell><![CDATA[Activo]]></cell>\";\n else\n echo \"<cell><![CDATA[Inactivo]]></cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
" require_once \"../aspectos/Seguridad.php\";\n $seguridad = Seguridad::getInstance();\n $seguridad->escapeSQL($_GET);",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nombre\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaEquipo.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseEtapa = new listaEquipo();\n $result = $baseEtapa->cargar($sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$row['nombre'].\"'>\";\n echo \"<cell>\".$row['nombre'].\"</cell>\";\n if ($row['estado'] == 1)\n echo \"<cell><![CDATA[Activo]]></cell>\";\n else\n echo \"<cell><![CDATA[Inactivo]]></cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nombre\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaEtapa.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseEtapa = new listaEtapa();\n $result = $baseEtapa->cargar($sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$row['id'].\"'>\";\n echo \"<cell>\".$row['id'].\"</cell>\";\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\n echo \"<cell>\".$row['numero'].\"</cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
" require_once \"../aspectos/Seguridad.php\";\n $seguridad = Seguridad::getInstance();\n $seguridad->escapeSQL($_GET);",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nombre\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaEtapa.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseEtapa = new listaEtapa();\n $result = $baseEtapa->cargar($sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$row['id'].\"'>\";\n echo \"<cell>\".$row['id'].\"</cell>\";\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\n echo \"<cell>\".$row['numero'].\"</cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP\r",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\r\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\r\n $equipo = $_GET[\"equipo\"];\r\n $page = $_GET['page'];\r\n $limit = $_GET['rows'];\r\n $sidx = $_GET['sidx'];\r\n if ($sidx == \"invid\")\r\n $sidx = \"nombre\";\r\n $sord = $_GET['sord'];\r\n require_once \"../class/class.listaIteracion.php\";\r\n $total_pages = 1;\r\n $start = ($page - 1)*$limit;\r\n $baseAct = new listaIteracion();\r\n $result = $baseAct->cargar($equipo,$sord,$sidx,$start,$limit);\r\n $N = sizeof($result);\r\n $count = $N;\r\n echo \"<rows>\";\r\n echo \"<page>\".$page.\"</page>\";\r\n echo \"<total>\".$total_pages.\"</total>\";\r\n echo \"<records>\".$count.\"</records>\";\r\n for ($i=0; $i<$N; $i++)\r\n {\r\n $row = $result[$i];\r\n echo \"<row id='\".$row['id'].\"'>\";\r\n echo \"<cell>\".$row['id'].\"</cell>\";\r\n echo \"<cell>\".$row['nombre'].\"</cell>\";\r\n echo \"<cell>\".$row['tipo'].\"</cell>\";\r\n // echo \"<cell>\";\r\n // switch ($row['tipo']) {\r\n // case 0: \r\n // echo \"Iniciación\";\r\n // break;\r\n // case 1:\r\n // echo \"Elaboración\";\r\n // break;\r\n // case 2:\r\n // echo \"Construcción\";\r\n // break;\r\n // case 3:\r\n // echo \"Transición\";\r\n // break;\r\n // default:\r\n // echo \"Desconocido\";\r\n // break;\r\n // }\r\n // echo \"</cell>\";\r\n echo \"<cell>\";\r\n switch ($row['estado']) {\r\n case 0: \r\n echo \"Planificada\";\r\n break;\r\n case 1:\r\n echo \"Aprobada\";\r\n break;\r\n case 2:\r\n echo \"Iniciada\";\r\n break;\r\n case 3:\r\n echo \"Finalizada\";\r\n break;\r\n default:\r\n echo \"Desconocido\";\r\n break;\r\n }\r\n echo \"</cell>\";\r\n echo \"</row>\";\r\n }\r\n echo \"</rows>\";\r\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP\r",
" require_once \"../aspectos/Seguridad.php\";\r\n $seguridad = Seguridad::getInstance();\r\n $seguridad->escapeSQL($_GET);\r",
" header(\"Content-type: text/xml;charset=utf-8\");\r\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\r\n $equipo = $_GET[\"equipo\"];\r\n $page = $_GET['page'];\r\n $limit = $_GET['rows'];\r\n $sidx = $_GET['sidx'];\r\n if ($sidx == \"invid\")\r\n $sidx = \"nombre\";\r\n $sord = $_GET['sord'];\r\n require_once \"../class/class.listaIteracion.php\";\r\n $total_pages = 1;\r\n $start = ($page - 1)*$limit;\r\n $baseAct = new listaIteracion();\r\n $result = $baseAct->cargar($equipo,$sord,$sidx,$start,$limit);\r\n $N = sizeof($result);\r\n $count = $N;\r\n echo \"<rows>\";\r\n echo \"<page>\".$page.\"</page>\";\r\n echo \"<total>\".$total_pages.\"</total>\";\r\n echo \"<records>\".$count.\"</records>\";\r\n for ($i=0; $i<$N; $i++)\r\n {\r\n $row = $result[$i];\r\n echo \"<row id='\".$row['id'].\"'>\";\r\n echo \"<cell>\".$row['id'].\"</cell>\";\r\n echo \"<cell>\".$row['nombre'].\"</cell>\";\r\n echo \"<cell>\".$row['tipo'].\"</cell>\";\r\n // echo \"<cell>\";\r\n // switch ($row['tipo']) {\r\n // case 0: \r\n // echo \"Iniciación\";\r\n // break;\r\n // case 1:\r\n // echo \"Elaboración\";\r\n // break;\r\n // case 2:\r\n // echo \"Construcción\";\r\n // break;\r\n // case 3:\r\n // echo \"Transición\";\r\n // break;\r\n // default:\r\n // echo \"Desconocido\";\r\n // break;\r\n // }\r\n // echo \"</cell>\";\r\n echo \"<cell>\";\r\n switch ($row['estado']) {\r\n case 0: \r\n echo \"Planificada\";\r\n break;\r\n case 1:\r\n echo \"Aprobada\";\r\n break;\r\n case 2:\r\n echo \"Iniciada\";\r\n break;\r\n case 3:\r\n echo \"Finalizada\";\r\n break;\r\n default:\r\n echo \"Desconocido\";\r\n break;\r\n }\r\n echo \"</cell>\";\r\n echo \"</row>\";\r\n }\r\n echo \"</rows>\";\r\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP\r",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\r\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\r\n $page = $_GET['page'];\r\n $limit = $_GET['rows'];\r\n $sidx = $_GET['sidx'];\r\n if ($sidx == \"invid\")\r\n $sidx = \"correoUSB\";\r\n $sord = $_GET['sord'];\r\n $equipo = $_GET['equipo'];\r\n require_once \"../class/class.listaUsuarios.php\";\r\n $total_pages = 1;\r\n $start = ($page - 1)*$limit;\r\n $baseUsuarios = new listaUsuarios();\r\n $result = $baseUsuarios->cargarMiembros($equipo,$sord,$sidx,$start,$limit);\r\n $N = sizeof($result);\r\n $count = $N;\r\n echo \"<rows>\";\r\n echo \"<page>\".$page.\"</page>\";\r\n echo \"<total>\".$total_pages.\"</total>\";\r\n echo \"<records>\".$count.\"</records>\";\r\n for ($i=0; $i<$N; $i++)\r\n {\r\n $row = $result[$i];\r\n echo \"<row id='\".$i.\"'>\";\r\n echo \"<cell>\". $row['correoUSB'].\"</cell>\";\r\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\r\n echo \"<cell><![CDATA[\". $row['apellido'].\"]]></cell>\";\r\n echo \"</row>\";\r\n }\r\n echo \"</rows>\";\r\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP\r",
" require_once \"../aspectos/Seguridad.php\";\r\n $seguridad = Seguridad::getInstance();\r\n $seguridad->escapeSQL($_GET);\r",
" header(\"Content-type: text/xml;charset=utf-8\");\r\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\r\n $page = $_GET['page'];\r\n $limit = $_GET['rows'];\r\n $sidx = $_GET['sidx'];\r\n if ($sidx == \"invid\")\r\n $sidx = \"correoUSB\";\r\n $sord = $_GET['sord'];\r\n $equipo = $_GET['equipo'];\r\n require_once \"../class/class.listaUsuarios.php\";\r\n $total_pages = 1;\r\n $start = ($page - 1)*$limit;\r\n $baseUsuarios = new listaUsuarios();\r\n $result = $baseUsuarios->cargarMiembros($equipo,$sord,$sidx,$start,$limit);\r\n $N = sizeof($result);\r\n $count = $N;\r\n echo \"<rows>\";\r\n echo \"<page>\".$page.\"</page>\";\r\n echo \"<total>\".$total_pages.\"</total>\";\r\n echo \"<records>\".$count.\"</records>\";\r\n for ($i=0; $i<$N; $i++)\r\n {\r\n $row = $result[$i];\r\n echo \"<row id='\".$i.\"'>\";\r\n echo \"<cell>\". $row['correoUSB'].\"</cell>\";\r\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\r\n echo \"<cell><![CDATA[\". $row['apellido'].\"]]></cell>\";\r\n echo \"</row>\";\r\n }\r\n echo \"</rows>\";\r\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP\r",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\r\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\r\n $page = $_GET['page'];\r\n $limit = $_GET['rows'];\r\n $sidx = $_GET['sidx'];\r\n if ($sidx == \"invid\")\r\n $sidx = \"correoUSB\";\r\n $sord = $_GET['sord'];\r\n $equipo = $_GET['equipo'];\r\n require_once \"../class/class.listaUsuarios.php\";\r\n $total_pages = 1;\r\n $start = ($page - 1)*$limit;\r\n $baseUsuarios = new listaUsuarios();\r\n $result = $baseUsuarios->cargarMiembros($equipo,$sord,$sidx,$start,$limit);\r\n $N = sizeof($result);\r\n $count = $N;\r\n echo \"<rows>\";\r\n echo \"<page>\".$page.\"</page>\";\r\n echo \"<total>\".$total_pages.\"</total>\";\r\n echo \"<records>\".$count.\"</records>\";\r\n for ($i=0; $i<$N; $i++)\r\n {\r\n $row = $result[$i];\r\n echo \"<row id='\".$i.\"'>\";\r\n echo \"<cell>\". $row['correoUSB'].\"</cell>\";\r\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\r\n echo \"<cell><![CDATA[\". $row['apellido'].\"]]></cell>\";\r\n\t\techo \"<cell>No</cell>\";\r\n echo \"</row>\";\r\n }\r\n echo \"</rows>\";\r\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP\r",
" require_once \"../aspectos/Seguridad.php\";\r\n $seguridad = Seguridad::getInstance();\r\n $seguridad->escapeSQL($_GET);\r",
" header(\"Content-type: text/xml;charset=utf-8\");\r\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\r\n $page = $_GET['page'];\r\n $limit = $_GET['rows'];\r\n $sidx = $_GET['sidx'];\r\n if ($sidx == \"invid\")\r\n $sidx = \"correoUSB\";\r\n $sord = $_GET['sord'];\r\n $equipo = $_GET['equipo'];\r\n require_once \"../class/class.listaUsuarios.php\";\r\n $total_pages = 1;\r\n $start = ($page - 1)*$limit;\r\n $baseUsuarios = new listaUsuarios();\r\n $result = $baseUsuarios->cargarMiembros($equipo,$sord,$sidx,$start,$limit);\r\n $N = sizeof($result);\r\n $count = $N;\r\n echo \"<rows>\";\r\n echo \"<page>\".$page.\"</page>\";\r\n echo \"<total>\".$total_pages.\"</total>\";\r\n echo \"<records>\".$count.\"</records>\";\r\n for ($i=0; $i<$N; $i++)\r\n {\r\n $row = $result[$i];\r\n echo \"<row id='\".$i.\"'>\";\r\n echo \"<cell>\". $row['correoUSB'].\"</cell>\";\r\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\r\n echo \"<cell><![CDATA[\". $row['apellido'].\"]]></cell>\";\r\n\t\techo \"<cell>No</cell>\";\r\n echo \"</row>\";\r\n }\r\n echo \"</rows>\";\r\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $id = $_GET['id'];\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nombre\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaProductosIteracion.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseAct = new listaProductosIteracion();\n $result = $baseAct->cargar($id,$sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$row['id'].\"'>\";\n echo \"<cell>\".$row['id'].\"</cell>\";\n echo \"<cell><![CDATA[\".$row['nombre'].\"]]></cell>\";\n echo \"<cell><![CDATA[\".$row['descripcion'].\"]]></cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
" require_once \"../aspectos/Seguridad.php\";\n $seguridad = Seguridad::getInstance();\n $seguridad->escapeSQL($_GET);",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $id = $_GET['id'];\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nombre\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaProductosIteracion.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseAct = new listaProductosIteracion();\n $result = $baseAct->cargar($id,$sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$row['id'].\"'>\";\n echo \"<cell>\".$row['id'].\"</cell>\";\n echo \"<cell><![CDATA[\".$row['nombre'].\"]]></cell>\";\n echo \"<cell><![CDATA[\".$row['descripcion'].\"]]></cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nombre\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaProyecto.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseProy = new listaProyecto();\n $result = $baseProy->cargar($sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$i.\"'>\";\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\n echo \"<cell><![CDATA[\". $row['numeroSolicitud'].\"]]></cell>\";\n echo \"<cell>\";\n if ($row['estado'] == 0)\n echo \"Inactivo\";\n else if ($row['estado'] == 1)\n echo \"Activo\";\n else if ($row['estado'] == 2)\n echo \"Finalizado\";\n else\n echo \"Implantado\";\n echo \"</cell>\";\n echo \"<cell><![CDATA[\". $row['etapaNombre'].\"]]></cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
" require_once \"../aspectos/Seguridad.php\";\n $seguridad = Seguridad::getInstance();\n $seguridad->escapeSQL($_GET);",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nombre\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaProyecto.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseProy = new listaProyecto();\n $result = $baseProy->cargar($sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$i.\"'>\";\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\n echo \"<cell><![CDATA[\". $row['numeroSolicitud'].\"]]></cell>\";\n echo \"<cell>\";\n if ($row['estado'] == 0)\n echo \"Inactivo\";\n else if ($row['estado'] == 1)\n echo \"Activo\";\n else if ($row['estado'] == 2)\n echo \"Finalizado\";\n else\n echo \"Implantado\";\n echo \"</cell>\";\n echo \"<cell><![CDATA[\". $row['etapaNombre'].\"]]></cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $id = $_GET['id'];\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nombre\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaRecursos.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseAct = new listaRecursos();\n $result = $baseAct->cargar($id,$sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$i.\"'>\";\n echo \"<cell><![CDATA[\".$row['correoUSB'].\"]]></cell>\";\n echo \"<cell><![CDATA[\".$row['nombre'].\"]]></cell>\";\n echo \"<cell><![CDATA[\".$row['apellido'].\"]]></cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
" require_once \"../aspectos/Seguridad.php\";\n $seguridad = Seguridad::getInstance();\n $seguridad->escapeSQL($_GET);",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $id = $_GET['id'];\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nombre\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaRecursos.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseAct = new listaRecursos();\n $result = $baseAct->cargar($id,$sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$i.\"'>\";\n echo \"<cell><![CDATA[\".$row['correoUSB'].\"]]></cell>\";\n echo \"<cell><![CDATA[\".$row['nombre'].\"]]></cell>\";\n echo \"<cell><![CDATA[\".$row['apellido'].\"]]></cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nro\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaSolicitud.php\";\n $start = ($page - 1)*$limit;\n $baseSolicitudes = new listaSolicitud();\n $result = $baseSolicitudes->buscarTodas($sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n $total_pages = ceil($N/$limit) + 1;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$row['nro'].\"'>\";\n echo \"<cell>\". $row['nro'].\"</cell>\";\n echo \"<cell><![CDATA[\". $row['nombreUnidadAdministrativa'].\"]]></cell>\";\n echo \"<cell>\". $row['email'].\"</cell>\";\n $estado = $row['estado'];\n echo \"<cell>\";\n if ($estado == 0)\n echo \"Pendiente\";\n else if ($estado == 1)\n echo \"Aceptada\";\n else if ($estado == 2)\n echo \"Aprobada\";\n else\n echo \"Rechazada\";\n echo \"</cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
" require_once \"../aspectos/Seguridad.php\";\n $seguridad = Seguridad::getInstance();\n $seguridad->escapeSQL($_GET);",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"nro\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaSolicitud.php\";\n $start = ($page - 1)*$limit;\n $baseSolicitudes = new listaSolicitud();\n $result = $baseSolicitudes->buscarTodas($sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n $total_pages = ceil($N/$limit) + 1;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$row['nro'].\"'>\";\n echo \"<cell>\". $row['nro'].\"</cell>\";\n echo \"<cell><![CDATA[\". $row['nombreUnidadAdministrativa'].\"]]></cell>\";\n echo \"<cell>\". $row['email'].\"</cell>\";\n $estado = $row['estado'];\n echo \"<cell>\";\n if ($estado == 0)\n echo \"Pendiente\";\n else if ($estado == 1)\n echo \"Aceptada\";\n else if ($estado == 2)\n echo \"Aprobada\";\n else\n echo \"Rechazada\";\n echo \"</cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"correoUSB\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaUsuarios.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseUsuarios = new listaUsuarios();\n $result = $baseUsuarios->buscar(null,null,$sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$i.\"'>\";\n echo \"<cell>\". $row['correoUSB'].\"</cell>\";\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\n echo \"<cell><![CDATA[\". $row['apellido'].\"]]></cell>\";\n echo \"<cell>\";\n if ($row['activo'] == 0)\n echo \"Inactivo\";\n else \n echo \"Activo\";\n echo \"</cell>\";\n echo \"<cell>\";\n if ($row['rol'] == 0)\n echo \"Administrador\";\n else if ($row['rol'] == 2)\n echo \"Profesor\";\n else if ($row['rol'] == 4)\n echo \"Cliente\";\n\t\telse if ($row['rol'] == 5)\n echo \"Estudiante/Coordinador\";\n else if ($row['rol'] == 3)\n echo \"Estudiante\";\n\t\t\telse if ($row['rol'] == 1)\n echo \"Administrador/Profesor\";\n echo \"</cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP",
" require_once \"../aspectos/Seguridad.php\";\n $seguridad = Seguridad::getInstance();\n $seguridad->escapeSQL($_GET);",
" header(\"Content-type: text/xml;charset=utf-8\");\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\n $page = $_GET['page'];\n $limit = $_GET['rows'];\n $sidx = $_GET['sidx'];\n if ($sidx == \"invid\")\n $sidx = \"correoUSB\";\n $sord = $_GET['sord'];\n require_once \"../class/class.listaUsuarios.php\";\n $total_pages = 1;\n $start = ($page - 1)*$limit;\n $baseUsuarios = new listaUsuarios();\n $result = $baseUsuarios->buscar(null,null,$sord,$sidx,$start,$limit);\n $N = sizeof($result);\n $count = $N;\n echo \"<rows>\";\n echo \"<page>\".$page.\"</page>\";\n echo \"<total>\".$total_pages.\"</total>\";\n echo \"<records>\".$count.\"</records>\";\n for ($i=0; $i<$N; $i++)\n {\n $row = $result[$i];\n echo \"<row id='\".$i.\"'>\";\n echo \"<cell>\". $row['correoUSB'].\"</cell>\";\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\n echo \"<cell><![CDATA[\". $row['apellido'].\"]]></cell>\";\n echo \"<cell>\";\n if ($row['activo'] == 0)\n echo \"Inactivo\";\n else \n echo \"Activo\";\n echo \"</cell>\";\n echo \"<cell>\";\n if ($row['rol'] == 0)\n echo \"Administrador\";\n else if ($row['rol'] == 2)\n echo \"Profesor\";\n else if ($row['rol'] == 4)\n echo \"Cliente\";\n\t\telse if ($row['rol'] == 5)\n echo \"Estudiante/Coordinador\";\n else if ($row['rol'] == 3)\n echo \"Estudiante\";\n\t\t\telse if ($row['rol'] == 1)\n echo \"Administrador/Profesor\";\n echo \"</cell>\";\n echo \"</row>\";\n }\n echo \"</rows>\";\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP\r",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\r\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\r\n\tinclude_once \"../class/class.fachadainterfaz.php\";\r\n\t$fachada = fachadaInterfaz::getInstance();\r\n $result = $fachada->buscarClientes($_GET['nombreProyecto']);\r\n $N = sizeof($result);\r\n $count = $N;\r\n echo \"<rows>\";\r\n echo \"<page>1</page>\";\r\n echo \"<total>1</total>\";\r\n echo \"<records>\".$count.\"</records>\";\r\n for ($i=0; $i<$N; $i++){ \r\n\t\t$row = $result[$i];\r\n echo \"<row id='\".$i.\"'>\";\r\n echo \"<cell>\". $row['correoUSB'].\"</cell>\";\r\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\r\n echo \"<cell><![CDATA[\". $row['apellido'].\"]]></cell>\";\r\n echo \"</row>\";\r\n }\r\n echo \"</rows>\";\r\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP\r",
" require_once \"../aspectos/Seguridad.php\";\r\n $seguridad = Seguridad::getInstance();\r\n $seguridad->escapeSQL($_GET);\r",
" header(\"Content-type: text/xml;charset=utf-8\");\r\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\r\n\tinclude_once \"../class/class.fachadainterfaz.php\";\r\n\t$fachada = fachadaInterfaz::getInstance();\r\n $result = $fachada->buscarClientes($_GET['nombreProyecto']);\r\n $N = sizeof($result);\r\n $count = $N;\r\n echo \"<rows>\";\r\n echo \"<page>1</page>\";\r\n echo \"<total>1</total>\";\r\n echo \"<records>\".$count.\"</records>\";\r\n for ($i=0; $i<$N; $i++){ \r\n\t\t$row = $result[$i];\r\n echo \"<row id='\".$i.\"'>\";\r\n echo \"<cell>\". $row['correoUSB'].\"</cell>\";\r\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\r\n echo \"<cell><![CDATA[\". $row['apellido'].\"]]></cell>\";\r\n echo \"</row>\";\r\n }\r\n echo \"</rows>\";\r\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP\r",
"",
" header(\"Content-type: text/xml;charset=utf-8\");\r\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\r\n $page = $_GET['page'];\r\n $limit = $_GET['rows'];\r\n $sidx = $_GET['sidx'];\r\n if ($sidx == \"invid\")\r\n $sidx = \"correoUSB\";\r\n $sord = $_GET['sord'];\r\n require_once \"../class/class.listaUsuarios.php\";\r\n $total_pages = 1;\r\n $start = ($page - 1)*$limit;\r\n $baseUsuarios = new listaUsuarios();\r\n\t$p=array();\r\n\t$p[0]=\"rol\";\r\n\t//$p[1]=\"rol\";\r\n\t$v=array();\r\n\t$v[0]=3;\r\n\t//$v[0]=5;\r\n $result = $baseUsuarios->buscar($p,$v,$sord,$sidx,$start,$limit);\r\n $N = sizeof($result);\r\n $count = $N;\r\n echo \"<rows>\";\r\n echo \"<page>\".$page.\"</page>\";\r\n echo \"<total>\".$total_pages.\"</total>\";\r\n echo \"<records>\".$count.\"</records>\";\r\n for ($i=0; $i<$N; $i++)\r\n {\r\n $row = $result[$i];\r\n echo \"<row id='\".$i.\"'>\";\r\n echo \"<cell>\". $row['correoUSB'].\"</cell>\";\r\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\r\n echo \"<cell><![CDATA[\". $row['apellido'].\"]]></cell>\";\r\n echo \"<cell>No</cell>\";\r\n echo \"</row>\";\r\n }\r\n echo \"</rows>\";\r\n?>"
] |
[
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?PHP\r",
" require_once \"../aspectos/Seguridad.php\";\r\n $seguridad = Seguridad::getInstance();\r\n $seguridad->escapeSQL($_GET);\r",
" header(\"Content-type: text/xml;charset=utf-8\");\r\n echo \"<?xml version='1.0' encoding='utf-8' ?>\";\r\n $page = $_GET['page'];\r\n $limit = $_GET['rows'];\r\n $sidx = $_GET['sidx'];\r\n if ($sidx == \"invid\")\r\n $sidx = \"correoUSB\";\r\n $sord = $_GET['sord'];\r\n require_once \"../class/class.listaUsuarios.php\";\r\n $total_pages = 1;\r\n $start = ($page - 1)*$limit;\r\n $baseUsuarios = new listaUsuarios();\r\n\t$p=array();\r\n\t$p[0]=\"rol\";\r\n\t//$p[1]=\"rol\";\r\n\t$v=array();\r\n\t$v[0]=3;\r\n\t//$v[0]=5;\r\n $result = $baseUsuarios->buscar($p,$v,$sord,$sidx,$start,$limit);\r\n $N = sizeof($result);\r\n $count = $N;\r\n echo \"<rows>\";\r\n echo \"<page>\".$page.\"</page>\";\r\n echo \"<total>\".$total_pages.\"</total>\";\r\n echo \"<records>\".$count.\"</records>\";\r\n for ($i=0; $i<$N; $i++)\r\n {\r\n $row = $result[$i];\r\n echo \"<row id='\".$i.\"'>\";\r\n echo \"<cell>\". $row['correoUSB'].\"</cell>\";\r\n echo \"<cell><![CDATA[\". $row['nombre'].\"]]></cell>\";\r\n echo \"<cell><![CDATA[\". $row['apellido'].\"]]></cell>\";\r\n echo \"<cell>No</cell>\";\r\n echo \"</row>\";\r\n }\r\n echo \"</rows>\";\r\n?>"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 8, 8, 1, 2, 2, 3, 1, 10, 2, 3, 8, 3, 9, 2, 2, 10, 5, 2, 16, 10], "buggy_code_start_loc": [11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 8, 8, 1, 2, 1, 2, 1, 10, 2, 2, 8, 2, 9, 2, 2, 10, 4, 2, 16, 10], "filenames": ["acciones/IniciarSesion.php", "acciones/cargarEquipos.php", "acciones/cargarEtapas.php", "acciones/cargarIteracion.php", "acciones/cargarMiembros.php", "acciones/cargarMiembrosC.php", "acciones/cargarProductosIteracion.php", "acciones/cargarProyectos.php", "acciones/cargarRecursos.php", "acciones/cargarSolicitudes.php", "acciones/cargarUsuarios.php", "acciones/cargarUsuariosCA.php", "acciones/cargarUsuariosEstudiantes.php", "acciones/cargarUsuariosEstudiantesEquipo.php", "acciones/cargarUsuariosPE.php", "acciones/cargarUsuariosProfesores.php", "acciones/consultarSolicitud.php", "acciones/consultarSolicitud2.php", "acciones/editaProyecto.php", "acciones/editaSolicitud.php", "acciones/editaUsuario.php", "acciones/editarCasoUso.php", "acciones/editarElemento.php", "acciones/editarEntregas.php", "acciones/editarIteracion.php", "acciones/editarPlanificacion.php", "acciones/editarProyecto.php", "acciones/editarSolicitud.php", "acciones/eliminarElemento.php", "acciones/registrarCasoUso.php", "acciones/registrarCoordinador.php", "acciones/registrarEquipo.php", "acciones/registrarIteracion.php", "acciones/registrarPlanificacion.php", "acciones/registrarProyecto.php", "acciones/registrarSolicitud.php", "acciones/registroUsuario.php"], "fixing_code_end_loc": [15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 12, 12, 5, 6, 6, 6, 5, 14, 6, 6, 12, 6, 13, 6, 6, 14, 7, 6, 20, 14], "fixing_code_start_loc": [12, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 9, 9, 2, 3, 1, 2, 2, 11, 3, 2, 9, 2, 10, 3, 3, 11, 4, 3, 17, 11], "message": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sigeprosi_project:sigeprosi:*:*:*:*:*:*:*:*", "matchCriteriaId": "4FBFC89E-AE06-4CFA-B110-E51285334095", "versionEndExcluding": "2012-05-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in ale7714 sigeprosi. This affects an unknown part. The manipulation leads to sql injection. The name of the patch is 5291886f6c992316407c376145d331169c55f25b. It is recommended to apply a patch to fix this issue. The identifier VDB-218493 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2012-10006", "lastModified": "2023-01-25T18:59:39.217", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-18T16:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.218493"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.218493"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ale7714/sigeprosi/commit/5291886f6c992316407c376145d331169c55f25b"}, "type": "CWE-89"}
| 264
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.