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.
[ "<!-- This will be the view for all courses...eventually a search should go here..http://stackoverflow.com/questions/14206259/backbone-structure-for-search-form-and-results", "all this will be is organized links-->", "<form class = \"course-find\">\n\t<label> Find Course\n\t<input type=\"text\" class=\"course-find-input\">\n\t</label>\n\t<input type=\"submit\" value=\"Search\">\n</form>", "<section class=\"course-results\">", "", "</section>" ]
[ 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "<!-- This will be the view for all courses...eventually a search should go here..http://stackoverflow.com/questions/14206259/backbone-structure-for-search-form-and-results", "all this will be is organized links-->", "<form class = \"course-find\">\n\t<label> Find Course\n\t<input type=\"text\" class=\"course-find-input\">\n\t</label>\n\t<input type=\"submit\" value=\"Search\">\n</form>", "<section class=\"course-results\">", "", "</section>" ]
[ 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "<% courses.each( function (course) { %>", "\t<li><a href=\"#\" data-id=\"<%=course.id%>\"><%= course.escape(\"name\") %></a></li>", "<% })%>" ]
[ 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "<% courses.each( function (course) { %>", "\t<li><a href=\"<%= '#course/' + course.id + '/enroll'%>\"><%= course.escape(\"name\") %></a></li>", "<% })%>" ]
[ 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "<h1>Grades for <%=grades.escape('fname') + \" \" + grades.escape('lname')%></h1>", "\n<section class=\"grade-errors\"></section>", "<% grades.each(function (grade) { %>", " <h4> grade.escape('assignment_title') </h4>\n <p> grade.escape('description')</p>", " Grade: <strong class=\"grade-number\" data-id=\"<%= grade.id %>\"><%= grade.get('grade')%></strong>\n <br>\n<% }) %>", "\n//I think all I'll do is just pretend like nothing happened if the entry is invalid" ]
[ 0, 1, 1, 0, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "<h1>Grades for <%= student.escape('fname') + \" \" + student.escape('lname')%></h1>", "\n<section class=\"grade-errors\"></section>", "<% grades.each(function (grade) { %>", " <h4> Assignment name:<%= grade.escape('title') %></h4>\n <p> description: <%= grade.escape('description') %></p>", " Grade: <strong class=\"grade-number\" data-id=\"<%= grade.id %>\"><%= grade.get('grade')%></strong>\n <br>\n<% }) %>", "" ]
[ 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "class Api::GradesController < Api::ApiController", " before_action(except: [:index]) {admins_only(params[\"course_id\"])} #wil always need to pass this in on every fetch", " before_action :is_user_or_instructor?, only: [:index]", " def index\n #I may want an internal control here instead of using the before_action...\n @grades = Grade.includes(:assignment,:course,:user).where(\"user_id = ?\", params[\"user_id\"])\n @student = @grades.first.user", "", " @grades = @grades.select {|grade| grade.course.id == params[\"course_id\"].to_i}\n end\n", " def destroy\n @grade = Grade.find(params[:id])\n @grade.destroy\n render json: {}\n end", "", "", " # def create\n # @grade = Grade.new(grade_params)\n #\n # if @grade.save\n # render json: @grade\n # else\n # render json: @grade.errors.full_messages, status: 422\n # end\n # end\n", "", " def update\n @grade = Grade.find(params[:id])\n", " if @grade.save", " render json: @grades\n else\n render json: @grade.errors.full_messages, status: 422\n end\n end", " private", " def is_user_or_instructor?\n return if current_user.id == params[\"user_id\"].to_i\n admins_only(params[\"course_id\"])\n end", " def grade_params", " params.require(:grade).permit(:grade, :assignment_id, :user_id)", " end", " ", "end" ]
[ 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "class Api::GradesController < Api::ApiController", " before_action(only: [:update, :show]) {admins_only(params[\"course_id\"])}", " before_action :is_user_or_instructor?, only: [:index]", " def index\n #I may want an internal control here instead of using the before_action...\n @grades = Grade.includes(:assignment,:course,:user).where(\"user_id = ?\", params[\"user_id\"])\n @student = @grades.first.user", " @course_id = params[\"course_id\"].to_i\n", " @grades = @grades.select {|grade| grade.course.id == params[\"course_id\"].to_i}\n end\n", " #Neither of these may be needed because they should only be created/destroyed depending on the assignment", "", " # def destroy\n # @grade = Grade.find(params[:id])\n # @grade.destroy\n # render json: {}\n # end", " # def create\n # @grade = Grade.new(grade_params)\n #\n # if @grade.save\n # render json: @grade\n # else\n # render json: @grade.errors.full_messages, status: 422\n # end\n # end\n", " def show\n @grade = Grade.find(params[:id])\n render json: @grade\n end\n #will need to create unique validator to ensure congruency between course auth and resource id course....", " def update\n @grade = Grade.find(params[:id])\n", " if @grade.update(grade_params)", " render json: @grades\n else\n render json: @grade.errors.full_messages, status: 422\n end\n end", " private", " def is_user_or_instructor?\n return if current_user.id == params[\"user_id\"].to_i\n admins_only(params[\"course_id\"])\n end", " def grade_params", " params.permit(:grade, :assignment_id, :user_id) #need to change grade column - it confuses params_wrapper", " end", "", "end" ]
[ 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": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "json.grades @grades do |grade_obj|", "", " json.grade grade_obj.grade", " json.assignment_id grade_obj.assignment_id", " json.user_id grade_obj.user_id", " json.assignment_title grade_obj.assignment.title\n json.assignment_description grade_obj.assignment.description", "end", "json.student_fname @student.fname\njson.student_lname @student.lname", "json.course_id @student.course.id", "\n#remember then that for a single model, only top-level attrs will be assigned\n# for a collection, each entry in the array should be top-level attrs (or wrapped in only a single object wrapper)\n# but the array itself must be top-level\n# weird: Cannot mix json.array! with other top-level attrs" ]
[ 1, 0, 1, 0, 1, 0, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "json.grades @grades do |grade_obj|", " json.id grade_obj.id", " json.grade grade_obj.grade", " json.id grade_obj.assignment_id", " json.user_id grade_obj.user_id", " json.title grade_obj.assignment.title\n json.description grade_obj.assignment.description", "end", "json.student_fname @student.fname\njson.student_lname @student.lname", "json.course_id @course_id", "\n#remember then that for a single model, only top-level attrs will be assigned\n# for a collection, each entry in the array should be top-level attrs (or wrapped in only a single object wrapper)\n# but the array itself must be top-level\n# weird: Cannot mix json.array! with other top-level attrs" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "Rails.application.routes.draw do\n resources :resources", "\troot to: \"static_pages#root\"", " \tresources :users, only: [:new, :create, :show]\n\tresource :session, only: [:new, :create, :destroy]\n# resources :coursesinstructors, only: [:create, :destroy]\n# \tresources :coursesstudents, only: [:create, :destroy], controller: \"courses_students\"\n# resources :courses, only: [:create, :index, :destroy, :new, :show]", " namespace :api, defaults: { format: :json } do\n resources :coursesinstructors, only: [:create, :destroy]\n resources :coursesstudents, only: [:create, :destroy], controller: \"courses_students\"\n resources :announcements #might have to \"member do\" for easy-access custom routes from a particular course\n resources :assignments\n resources :resources", "", " resources :courses do\n get \"course_search\", on: :collection\n end\n resources :users, only: [:show, :index] do\n get \"users_search\", on: :collection\n resources :grades, only: [:index]\n end\n end", "end" ]
[ 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "Rails.application.routes.draw do\n resources :resources", "\troot to: \"static_pages#root\"", " \tresources :users, only: [:new, :create, :show]\n\tresource :session, only: [:new, :create, :destroy]\n# resources :coursesinstructors, only: [:create, :destroy]\n# \tresources :coursesstudents, only: [:create, :destroy], controller: \"courses_students\"\n# resources :courses, only: [:create, :index, :destroy, :new, :show]", " namespace :api, defaults: { format: :json } do\n resources :coursesinstructors, only: [:create, :destroy]\n resources :coursesstudents, only: [:create, :destroy], controller: \"courses_students\"\n resources :announcements #might have to \"member do\" for easy-access custom routes from a particular course\n resources :assignments\n resources :resources", " resources :grades, only: [:update, :show]", " resources :courses do\n get \"course_search\", on: :collection\n end\n resources :users, only: [:show, :index] do\n get \"users_search\", on: :collection\n resources :grades, only: [:index]\n end\n end", "end" ]
[ 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "# This file should contain all the record creation needed to seed the database with its default values.\n# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).\n#\n# Examples:\n#\n# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])\n# Mayor.create(name: 'Emanuel', city: cities.first)", "#should create master user that has most functionality available to it.", "User.create(fname:\"Jonathan\", lname: \"Lee\", email: \"l33.jonathan@gmail.com\", password: \"testing\")", "", "\n(1..10).each do |user_no|\n User.create(\n fname: Faker::Name.first_name,\n lname: Faker::Name.last_name,\n email: Faker::Internet.email,\n password: Faker::Internet.password(8),\n )\nend", "weekdays = [\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\"]", "(1..5).each do |course_no|\n time_string = \"12:0\" + course_no.to_s\n end_time_string = \"12:0\" + (course_no+2).to_s", " Course.create(\n name: Faker::Lorem.word,\n location: Faker::Address.street_address,\n day: weekdays[rand(5)],\n description: Faker::Lorem.sentence,\n start_time: time_string,\n end_time: end_time_string\n )\nend", "\n#enrollment\n[1,3].each do |odd|\n CoursesStudents.create(user_id: 1, course_id: odd)\nend", "2.times{\n (2..11).each do |enroll|\n course_no = (rand(5)+1)\n student_no = enroll", " CoursesStudents.create( #to make this less haphazard, I could just iterate over the courses and users and match up it to avoid collisions.\n user_id: student_no,\n course_id: course_no\n )\n end\n}", "[2,4].each do |even|\n CoursesInstructors.create(user_id: 1, course_id: even)\nend", "(2..11).each do |teacher| #not getting hit enough times, need to rejigger to avoid conflicts or just increase number to increase chances of seeding database\n course_no = (rand(5)+1)\n instructor_no = (rand(11)+1)", " CoursesInstructors.create(\n user_id: instructor_no,\n course_id: course_no\n )\nend", "#for announcements and assignments, need to set up inverse relationship... maybe. Will need to think about it for a bit", "CoursesInstructors.all.each do |admin_link|\n course_no = admin_link.course_id\n admin_id = admin_link.user_id", " 3.times {\n Announcement.create(\n title: Faker::Lorem.word.capitalize,\n body: Faker::Lorem.paragraph,\n user_id: admin_id,\n course_id: course_no,\n )\n }", "end", "Course.all.each do |course|\n 2.times {\n Assignment.create(\n title: Faker::Lorem.word.capitalize,\n description: Faker::Lorem.sentence,\n due_date: Faker::Date.forward(10), #should find someway to exclude weekends\n course_id: course.id\n )\n }\nend", "#grades", "CoursesStudents.all.each do |student_link|\n course_id = student_link.course_id\n user_id = student_link.user_id", " course = Course.find(course_id)", " course.assignments.each do |assignment|\n Grade.create(user_id: user_id, assignment_id: assignment.id, grade: rand(101))\n end\n # A note- creating entries haphazardly like this may cause there to be an grade for an class assignment that user doesn't even attend - in this particular case it can't happen, but its in the realm of possibility\nend" ]
[ 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": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "# This file should contain all the record creation needed to seed the database with its default values.\n# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).\n#\n# Examples:\n#\n# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])\n# Mayor.create(name: 'Emanuel', city: cities.first)", "#should create master user that has most functionality available to it.", "User.create(fname:\"Jonathan\", lname: \"Lee\", email: \"l33.jonathan@gmail.com\", password: \"testing\")", "User.create(fname:\"John\", lname: \"Doe\", email: \"johndoe@gmail.com\",\npassword: \"testing\")", "\n(1..10).each do |user_no|\n User.create(\n fname: Faker::Name.first_name,\n lname: Faker::Name.last_name,\n email: Faker::Internet.email,\n password: Faker::Internet.password(8),\n )\nend", "weekdays = [\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\"]", "(1..5).each do |course_no|\n time_string = \"12:0\" + course_no.to_s\n end_time_string = \"12:0\" + (course_no+2).to_s", " Course.create(\n name: Faker::Lorem.word,\n location: Faker::Address.street_address,\n day: weekdays[rand(5)],\n description: Faker::Lorem.sentence,\n start_time: time_string,\n end_time: end_time_string\n )\nend", "\n#enrollment\n[1,3].each do |odd|\n CoursesStudents.create(user_id: 1, course_id: odd)\nend", "2.times{\n (2..11).each do |enroll|\n course_no = (rand(5)+1)\n student_no = enroll", " CoursesStudents.create( #to make this less haphazard, I could just iterate over the courses and users and match up it to avoid collisions.\n user_id: student_no,\n course_id: course_no\n )\n end\n}", "[2,4].each do |even|\n CoursesInstructors.create(user_id: 1, course_id: even)\nend", "(2..11).each do |teacher| #not getting hit enough times, need to rejigger to avoid conflicts or just increase number to increase chances of seeding database\n course_no = (rand(5)+1)\n instructor_no = (rand(11)+1)", " CoursesInstructors.create(\n user_id: instructor_no,\n course_id: course_no\n )\nend", "#for announcements and assignments, need to set up inverse relationship... maybe. Will need to think about it for a bit", "CoursesInstructors.all.each do |admin_link|\n course_no = admin_link.course_id\n admin_id = admin_link.user_id", " 3.times {\n Announcement.create(\n title: Faker::Lorem.word.capitalize,\n body: Faker::Lorem.paragraph,\n user_id: admin_id,\n course_id: course_no,\n )\n }", "end", "Course.all.each do |course|\n 2.times {\n Assignment.create(\n title: Faker::Lorem.word.capitalize,\n description: Faker::Lorem.sentence,\n due_date: Faker::Date.forward(10), #should find someway to exclude weekends\n course_id: course.id\n )\n }\nend", "#grades", "CoursesStudents.all.each do |student_link|\n course_id = student_link.course_id\n user_id = student_link.user_id", " course = Course.find(course_id)", " course.assignments.each do |assignment|\n Grade.create(user_id: user_id, assignment_id: assignment.id, grade: rand(101))\n end\n # A note- creating entries haphazardly like this may cause there to be an grade for an class assignment that user doesn't even attend - in this particular case it can't happen, but its in the realm of possibility\nend" ]
[ 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": [43, 5, 156, 27, 6, 46, 30, 7, 56, 14, 4, 13, 49, 17, 17, 11], "buggy_code_start_loc": [10, 4, 35, 26, 3, 3, 3, 1, 4, 13, 2, 1, 2, 1, 17, 11], "filenames": ["app/assets/javascripts/collections/grades.js", "app/assets/javascripts/models/grade.js", "app/assets/javascripts/routers/router.js", "app/assets/javascripts/views/courses/course-form.js", "app/assets/javascripts/views/courses/course-list.js", "app/assets/javascripts/views/courses/course_search.js", "app/assets/javascripts/views/courses/courses_enroll.js", "app/assets/javascripts/views/grades/grade-search-student.js", "app/assets/javascripts/views/grades/grades-student.js", "app/assets/templates/courses/coursesearch.jst.ejs", "app/assets/templates/courses/list.jst.ejs", "app/assets/templates/grades/grades-student-list.jst.ejs", "app/controllers/api/grades_controller.rb", "app/views/api/grades/index.json.jbuilder", "config/routes.rb", "db/seeds.rb"], "fixing_code_end_loc": [54, 5, 158, 27, 4, 37, 17, 7, 54, 12, 4, 10, 57, 18, 19, 14], "fixing_code_start_loc": [10, 4, 35, 26, 3, 2, 3, 1, 4, 12, 2, 1, 2, 2, 18, 12], "message": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:merlinsboard_project:merlinsboard:*:*:*:*:*:*:*:*", "matchCriteriaId": "9414ED47-1FC1-4072-BDB9-DF7C47A53F84", "versionEndExcluding": "2015-03-19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as problematic, was found in jvvlee MerlinsBoard. This affects an unknown part of the component Grade Handler. The manipulation leads to improper authorization. The name of the patch is 134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5. It is recommended to apply a patch to fix this issue. The identifier VDB-217713 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2015-10033", "lastModified": "2023-01-13T18:21:16.730", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "MULTIPLE", "availabilityImpact": "PARTIAL", "baseScore": 3.7, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:M/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.1, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:H/UI:N/S:U/C:N/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-09T21:15:10.210", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217713"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217713"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jvvlee/MerlinsBoard/commit/134f5481e2914b7f096cd92a22b1e6bcb8e6dfe5"}, "type": "CWE-863"}
227
Determine whether the {function_name} code is vulnerable or not.
[ "module Sns::LoginFilter\n extend ActiveSupport::Concern", " included do\n protect_from_forgery except: :remote_login\n skip_before_action :verify_authenticity_token unless SS.config.env.protect_csrf\n prepend_view_path \"app/views/sns/login\"\n layout \"ss/login\"\n navi_view nil\n end", " private", " def remote_login?\n SS::config.sns.remote_login\n end", " def default_logged_in_path\n SS.config.sns.logged_in_page\n end", " def login_success\n if params[:ref].blank?\n redirect_to default_logged_in_path", " elsif params[:ref] =~ /^\\//", " redirect_to params[:ref]\n else\n render \"sns/login/redirect\"\n end\n end", " def render_login(user, email_or_uid, opts = {})\n alert = opts.delete(:alert).presence || t(\"sns.errors.invalid_login\")", " if user\n opts[:session] ||= true\n set_user user, opts", " respond_to do |format|\n format.html { login_success }\n format.json { head :no_content }\n end\n else\n @item = user_class.new\n @item.email = email_or_uid if email_or_uid.present?\n respond_to do |format|\n flash[:alert] = alert\n format.html { render file: :login }\n format.json { render json: alert, status: :unprocessable_entity }\n end\n end\n end", " public", " def logout\n put_history_log\n # discard all session info\n reset_session\n respond_to do |format|\n format.html { redirect_to login_path_by_cookie }\n format.json { head :no_content }\n end\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [26], "buggy_code_start_loc": [25], "filenames": ["app/controllers/concerns/sns/login_filter.rb"], "fixing_code_end_loc": [26], "fixing_code_start_loc": [25], "message": "Open redirect vulnerability in SHIRASAGI v1.7.0 and earlier allows remote attackers to redirect users to arbitrary web sites and conduct phishing attacks via unspecified vectors.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ss-proj:shirasagi:*:*:*:*:*:*:*:*", "matchCriteriaId": "DFB71EFD-877E-4767-B3DB-BF8172B08D0B", "versionEndExcluding": null, "versionEndIncluding": "1.7.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Open redirect vulnerability in SHIRASAGI v1.7.0 and earlier allows remote attackers to redirect users to arbitrary web sites and conduct phishing attacks via unspecified vectors."}, {"lang": "es", "value": "Una vulnerabilidad de redireccionamiento abierto en SHIRASAGI versi\u00f3n v1.7.0 y anteriores, permite a atacantes remotos redireccionar a los usuarios a sitios web arbitrarios y realizar ataques de phishing por medio de vectores no especificados."}], "evaluatorComment": null, "id": "CVE-2019-6009", "lastModified": "2019-09-13T13:35:15.567", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "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"}]}, "published": "2019-09-12T17:15:14.623", "references": [{"source": "vultures@jpcert.or.jp", "tags": ["Third Party Advisory"], "url": "http://jvn.jp/en/jp/JVN74699196/index.html"}, {"source": "vultures@jpcert.or.jp", "tags": ["Third Party Advisory"], "url": "https://github.com/shirasagi/shirasagi"}, {"source": "vultures@jpcert.or.jp", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/shirasagi/shirasagi/commit/6016948ea535e51b16535888af13df064a1a15d3"}, {"source": "vultures@jpcert.or.jp", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/shirasagi/shirasagi/commit/6016948ea535e51b16535888af13df064a1a15d3.patch"}, {"source": "vultures@jpcert.or.jp", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.ss-proj.org/"}], "sourceIdentifier": "vultures@jpcert.or.jp", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-601"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/shirasagi/shirasagi/commit/6016948ea535e51b16535888af13df064a1a15d3"}, "type": "CWE-601"}
228
Determine whether the {function_name} code is vulnerable or not.
[ "module Sns::LoginFilter\n extend ActiveSupport::Concern", " included do\n protect_from_forgery except: :remote_login\n skip_before_action :verify_authenticity_token unless SS.config.env.protect_csrf\n prepend_view_path \"app/views/sns/login\"\n layout \"ss/login\"\n navi_view nil\n end", " private", " def remote_login?\n SS::config.sns.remote_login\n end", " def default_logged_in_path\n SS.config.sns.logged_in_page\n end", " def login_success\n if params[:ref].blank?\n redirect_to default_logged_in_path", " elsif params[:ref] =~ /^\\/[^\\/]/", " redirect_to params[:ref]\n else\n render \"sns/login/redirect\"\n end\n end", " def render_login(user, email_or_uid, opts = {})\n alert = opts.delete(:alert).presence || t(\"sns.errors.invalid_login\")", " if user\n opts[:session] ||= true\n set_user user, opts", " respond_to do |format|\n format.html { login_success }\n format.json { head :no_content }\n end\n else\n @item = user_class.new\n @item.email = email_or_uid if email_or_uid.present?\n respond_to do |format|\n flash[:alert] = alert\n format.html { render file: :login }\n format.json { render json: alert, status: :unprocessable_entity }\n end\n end\n end", " public", " def logout\n put_history_log\n # discard all session info\n reset_session\n respond_to do |format|\n format.html { redirect_to login_path_by_cookie }\n format.json { head :no_content }\n end\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [26], "buggy_code_start_loc": [25], "filenames": ["app/controllers/concerns/sns/login_filter.rb"], "fixing_code_end_loc": [26], "fixing_code_start_loc": [25], "message": "Open redirect vulnerability in SHIRASAGI v1.7.0 and earlier allows remote attackers to redirect users to arbitrary web sites and conduct phishing attacks via unspecified vectors.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ss-proj:shirasagi:*:*:*:*:*:*:*:*", "matchCriteriaId": "DFB71EFD-877E-4767-B3DB-BF8172B08D0B", "versionEndExcluding": null, "versionEndIncluding": "1.7.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Open redirect vulnerability in SHIRASAGI v1.7.0 and earlier allows remote attackers to redirect users to arbitrary web sites and conduct phishing attacks via unspecified vectors."}, {"lang": "es", "value": "Una vulnerabilidad de redireccionamiento abierto en SHIRASAGI versi\u00f3n v1.7.0 y anteriores, permite a atacantes remotos redireccionar a los usuarios a sitios web arbitrarios y realizar ataques de phishing por medio de vectores no especificados."}], "evaluatorComment": null, "id": "CVE-2019-6009", "lastModified": "2019-09-13T13:35:15.567", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "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"}]}, "published": "2019-09-12T17:15:14.623", "references": [{"source": "vultures@jpcert.or.jp", "tags": ["Third Party Advisory"], "url": "http://jvn.jp/en/jp/JVN74699196/index.html"}, {"source": "vultures@jpcert.or.jp", "tags": ["Third Party Advisory"], "url": "https://github.com/shirasagi/shirasagi"}, {"source": "vultures@jpcert.or.jp", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/shirasagi/shirasagi/commit/6016948ea535e51b16535888af13df064a1a15d3"}, {"source": "vultures@jpcert.or.jp", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/shirasagi/shirasagi/commit/6016948ea535e51b16535888af13df064a1a15d3.patch"}, {"source": "vultures@jpcert.or.jp", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.ss-proj.org/"}], "sourceIdentifier": "vultures@jpcert.or.jp", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-601"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/shirasagi/shirasagi/commit/6016948ea535e51b16535888af13df064a1a15d3"}, "type": "CWE-601"}
228
Determine whether the {function_name} code is vulnerable or not.
[ "", "Version 2.0.4 (September 26th, 2016)\n------------------------------------------------------------------------", " * [Security] Prevent moving files by using their directory name.\n [Security] Possible SQL injection for entry category assignment\n [Security] Possible SQL injection for removing&adding a plugin", " All issues require a valid backend login.\n Thanks to Hendrik Buchwald for finding this via their\n RIPS source code analyzer (www.ripstech.com)", " * [Security] Add new configuration option to enable fetching \n local files for the media uploader. By default this is now\n disabled to prevent Server Side Request Forgery (SSRF).\n Thanks to Xu Yue for pointing this out!", "\nVersion 2.0.3 (January 4th, 2016)\n------------------------------------------------------------------------", " * Fix XSS in backend comment editing form for logged-in authors,\n thanks to Onur Yilmaz and Robert Abela from Netsparker.com", " * Fix some backend entry form related event messages", "\nVersion 2.0.2 (Jul 24th, 2015)\n------------------------------------------------------------------------", " * Fix security issues reported by Tim Coen of Curesec.com:", " - Forbid uploading files with PHP contents and possible\n PHP execution by authenticated users (critical if\n you have possible untrustworthy authors)\n - Add proper escaping for comment approval tokens to prevent\n SQL injection (authenticated authors only)\n - Add proper escaping of comment's author names in the\n comment reply form to prevent XSS (2k11 template, javascript\n based)", " * Minor layout fixes for media DB media filters", " * Backported some Importer db bugfixes", " * CKEDITOR bugfix releases to 4.4.8 - please read the changelog.\n Includes widget, lineutils, fakeobjects Plugins and S9y added\n cheatsheet and procurator Plugins.\n Changed config.autoParagraph set to false, to prevent wrapping\n p tags around extraAllowedContent tags.", " * Smarty bugfix upgrades to 3.1.27 - please read the changelog.\n Compilation time was vastly improved.\n New Features in NEW_FEATURES.txt.", " * It is now possible to switch to a theme's admin theme if it has\n been selected as a frontend theme first", " * Syndication Plugin Issue #285:\n - Add \"none\" as possible value for the xml-icon in the\n syndication plugin, to enable plain links\n - Reset subtome full icon path to support\n serendipity_getTemplateFile()\n - Link creation fixes for Bulletproof coloured style (eg blue)", " * Fix auto include of a User theme /admin/user.css backend file.", " PLEASE NOTE:", " 2.0.1 brought in an automatted include of a themes \"user.css\"\n file. If you don't want to use such file any more (and you have\n one), you will have to delete or rename it by hand!", " Also please note, that user stylesheet selectors like", " .selector {\n background-image: url(img/example.jpg);\n }", " now need to use the {TEMPLATE_PATH} like", " .selector {\n background-image: url({TEMPLATE_PATH}img/example.jpg);\n }", " Content of a user.css will always be put LAST into the combined\n CSS, this means it will override any possible plugin output.\n If a user.css file does not exist in your own template directory,\n but inside the default 2k11 template directory, this will always\n be used (this behaviour is called \"default fallback chain\").", " * Use https URLs for Atom feed, if called through HTTPS (hboeck)", " * Restore the \"Show toolbar within media selector popup?\" option,\n it was ignored before.", " * Fix Issue #321, negative offset for LIMIT SQL statements when\n using stable archive sorting and plugins like history.", " * Templatechooser will not apply theme in backend admin.", " * Use \"secure\" flag for (session) cookies sent over SSL, thanks to\n dayton967", " * Make preview_iframe.tpl template files load the proper frontend\n CSS file, including cache-busting version string when changing\n themes", " * Implement patch to properly initiate templates_c on installation\n for shared installs (thanks to fugue88)", " * Allow templatechooser plugin to read a custom \"blacklist.txt\"\n within its directory, that can blacklist certain themes from\n being selected.", " * Allow serendipity_setCookie() function to set custom expiry.", " * Adapt .htaccess profile of \"mod_rewrite for 1&1 and problematic\n servers\" to not include the \"Options -MultiViews\" option, since\n this is often blocked", " * Fix initializing smarty framework in the preview/saving iframe,\n so that a template's config.inc.php is always loaded.", " * Show debugging .tpl file information with relative directory only", " * fix wrong upgrade removal of dead files with 2.0.1 update", "\nVersion 2.0.1 (March 12th, 2015)\n------------------------------------------------------------------------", " * Fix missing escaping (possible XSS) of category names in the\n Backend Entry Admin, which would allow editors that create a\n forged category name to attack other editors in the backend\n (privileged access to the backend required). Thanks a lot to Edric\n Teo for reporting this issue.", " * Improved detection for possible upgrade/plugin/PHP errors. A\n warning will be emitted on the dashboard, when the Serendipity\n JavaScript library could not be loaded.", " * syndication fix: use absolute urls for subtome", " * Issue 306: localStorage may be deactivated by setting a config\n option or using security-related extensions at least in some\n browsers, which might (at least in FF) break backend JS\n functionality. Added extra tests to 2k11 backend JS.", " If you use localStorage, please test if it is actually available\n by testing if localStorage !== null in JS.", " * Issue 280: Allow every theme to utilize a \"user.css\" file that\n gets loaded on top of the frontend (or backend, if in admin/\n subdirectory) theme. This file can be used for customized CSS of\n a blog-admin which carries over to future Serendipity updates", " * Issue 299: Do not display dashboard for users with no permission\n to perform actions in the backend (frontend-users)", " * Make \"rewriteURL\" smarty modifier available to do a\n {$CONST.PATH_ARCHIVE|rewriteURL} within a smarty template file.", " * Add a generic odd/even for backend dashboard widgets to align\n properly. Future dashboard widgets need to get the new extra\n class dashboard widget on the section element they create.", " * Fix event emoticate plugin to reflect proper call usage of\n serendipity_getTemplateFile(), if a theme uses custom emoticons.\n UPDATE your themes emoticons.inc.php file, if have. See example\n file in plugin dir.", " * Change 2k11 config.inc.php to reflect proper\n serendipity_getTemplateFile() when frontend files shall be\n referenced within the backend.", " * Fixed missing file message for deleted media items", " * Fixed entry editor JS not emitting a 'No tags' msg in taxonomy\n quick view. Improved serendipity.tagsList exit if freetag plugin\n is not installed.", " * Minor backend UI fixes (taxonomy quick view in entry editor,\n 'Done' msg emitted by Bayes plugin)", " * Clearer language constants for entries in dashboard, labelled\n \"In progress\"", "\nVersion 2.0 (January 23rd, 2015)\n------------------------------------------------------------------------", " * Smarty fix for purging compiled files", " * Fix wrong search page ordering when stable archive was active", " * Prevent entryproperties from saving/displaying a browser-side\n stored password that was actually not set.", " * Stronger check for existing logger interface to prevent errors\n when it is not actively used.", " * Fix entryproperties being removed when publishing an article\n from the dashboard and by specific plugins (freetag, trackback)\n that modify entry data.", " * Fix deleting comments when user is not an admin, but the entry\n belongs to him. Thanks to berberic.", " * Patch PEAR.php to use \"static\" isError declaration to prevent\n PHP error messages", " * Change order of IF-statements in entries.tpl to check for\n comment_moderate/comment_added, to properly emit the message\n whether a comment is being moderated.", " * Fix searching for entries in the admin panel with database\n types other than \"mysql\"", " * Change entry editor's category assignment to toggle between\n a hierarchical and a plain list (good for many categories)", " * Fix date formatting in entry editor to not use ISO year\n but the calendar year", " * Fix autoupdate version read and transmit", "\nVersion 2.0-rc2 (December 23rd, 2014)\n------------------------------------------------------------------------", " * Fixes escaping of comments in the new backend pane to prevent\n XSS. Thanks to Steffen Röemann for reporting!", " * Fix wrong parameter count in serendipity_entity_decode", "\nVersion 2.0-rc1 (includes beta4/5/6) (December 19th, 2014)\n------------------------------------------------------------------------", " * entryproperties plugin will now automatically disable nl2br\n markup, when the WYSIWYG editor is used to create en entry", " * PHP Requirement now is at: PHP 5.3+", " * Fix for syndication subtome onclick handler", " * Fix problematic preview stylesheet reference", " * Optimized clearing smarty template files on upgrading", " * Properly reset the \"disable markup\" feature of entryproperties\n plugin when none selected", " * PHP 5.4+ fix to properly call htmlspecialchars() / htmlentities() /\n html_entity_decode() with a charset option, that has been\n set to to default to UTF-8 and will yield empty strings when\n being used in NON-UTF-8 environments. Now we utilize a\n serendipity_specialchars() wrapper call.", " * Added SQLite3 OO database layer for PHP 5.4+", " * New personal preference to choose CKEditor toolbar presets.\n Presets can be overwritte through a\n templates/xxx/admin/ckeditor_custom_config.js if needed.\n See htmlarea/ckeditor_s9y_config.js for details.", " * Proof of concept templates \"default-php\" and \"default-xml\" have\n been moved to Siber...Spartacus. They would need adapting to\n Serendipity 2.0 (simple methods like getConfigDir() et al),\n but since those Template APIs have virtually zero usage scenario,\n they remain experimental.", " * Added new PAT_JS mod_rewrite rule to .htaccess files", " * Removed experimental support for PHP/SMARTY IN-MEMORY caching\n added in 2.0-beta3, since this could not work.", " * Smarty 3.1.21 upgrade (see changelog)", " * Fix ImageMagick new sizing issues while forcing image geometry\n exactly to given sizes with imageselectorplus", " * Fix issue #220 with pdf directory moving rename() error", " * Fix bug in entry listing, which showed wrong categories for\n entries (Issue #201)", " * Improve RegExp for Feed-URL matching, thanks to fugue88", " * Proper SQLite PDO filenames in shared installations (Issue #214)", " * ImageMagick now can get parameters to generate thumbnails,\n see serendipity_config.inc.php for example values", " * Allow to enable/disable the new autosave feature in personal\n preferences (Issue #213)", " * Re-added installer test for writable serendipity base directory", "\nVersion 2.0-beta3 (July 25th, 2014)\n------------------------------------------------------------------------", " * Move admin/media_showitem.tpl to theme's directory in 2k11. With\n an adaptation in serendipity_admin_image_selector.php, this now is\n a \"true\" frontend template which uses the styles of the frontend\n theme. Theme authors might want to adapt it to their themes.", " * Moved general syndication plugin option into the core", " * Smarty 3.1.19 upgrade (see changelog)", " * Fixed thumbnail recreation, Issue #134", " * Merged external JS libraries into a central \"plugins.js\" of the 2k11\n backend template, can be updated through\n templates/2k11/admin/js/gruntipity.php helper script.", " * Adapted database table structure change for statistics, shoutbox,\n karma and spamblock plugin (for new field definition of \"ip\" field)\n Thanks to rohdef!", " * Added new option \"enabledBackendPopups\" that allow to specify\n if inline modal dialogs or popups are used in the backend for\n e.g. the category selectory and media library", " * added experimental support for PHP/SMARTY IN MEMORY caching\n Enabled by default, if classes found loaded.\n Disable with\n $serendipity['disable_apc'] = true;\n and\n $serendipity['disable_memcache'] = true;", " * Support added in serendipity_db_schema_import for sqlite\n autoincrement", " * Remove Google Reader button from syndication plugin options", " * Add subToMe-button to syndication plugin and change its defaults", " * Use Browsercache to save cache and restore entries", " * Improved installer to forbid using database table prefixes with\n special characters", " * Themes using Engines are now able to use the parent's\n configuration", " * Prevent \"new\" plugin api to install double instances of plugins\n that are not stackable (issue #45)", " * Back button in plugin-config", " * Adapted serendipity_editor.js to provide more global (though\n deprecated) API access methods for plugins like amazonchooser\n and linktrimmer, to perform insertion. Also fixed the\n insertion of text when the ID of the element is not prefixed", " * Move sort by name to simple filter in ML, replace file extension", " * Remember selected media library folder", " * Show upload-success or error with the ajax image uploader", " * Fix preview entry exception (issue #119)", " * Add serendipity.toggle_collapsible as a reusable JS function\n for the core backend and backend sections emitted by plugins as\n an easy way to provide show/hide functionality. (yellowled)", " * Fixed media insert target bug (issued by #143, #145, #121)", " * Fixed publish drafted-entries via dashboard (issue #160)", " * All frontend themes that rely on the bundled Core jQuery library\n are currently using the jquery.noConflict-mode for compatibility\n to older plugins.\n This mode is now considered deprecated and will be removed in\n future releases. A new variable:\n $serendipity['capabilities']['jquery-noconflict'] = false;\n in your theme's config.inc.php file can now turn of that\n noConflict-mode.", " * Due to distinction of backend and frontend themes, each theme\n that provides a custom jquery.js now only does so for the\n frontend. The backend now listens to a:", " $serendipity['capabilities']['jquery_backend'] = false;", " variable, and the file needs to be jquery_backend.js that\n a backend theme would reference to.", " * Changed 2k11's config.inc.php file to provide a more stable\n call of event hooks so that other themes can also hook\n their own events.", " * Changed JS for category filtering and its reset button to be a\n reusable function, which is now also used in the list of\n installable plugins.", " * Fixed wrong local documentation URL in plugin configuration", " * Added new \"backend_dashboard\" event-hook for plugins to use\n within dashboard.", " * Backend and Frontend themes can now be set independently from\n each other. New backend themes now need to set:", " Backend: Yes", " in their info.txt file. If you adapt a custom admin theme,\n ensure that it is compatible to the new \"2k11\" backend to\n ensure proper future usage within Serendipity. The bulletproof\n backend will now no longer be recognized as a backend theme\n option, but can be selected as a new frontend theme, while\n using 2k11 (=default) in the backend.", " * Include klogger, call it as $serendipity['logger']->debug/error.\n The log-level can be set in the general configuration and is\n disabled by default.", " * Fixed missing s9ymdb ID", " * Add HTTP_Request2 and dependencies as bundled libraries and\n update PEAR library to version 1.9.4", " * Implemented AJAX uploadResize option to allow resizing an image\n before upload (onli)", " * Improved file/directory removal code to (hopefully) fail more\n gracefully", " * Change \"default\" admin backend template fallback chain so that\n old admin themes can theoretically be shown with the \"old\"\n admin interface. This however in many themes breaks the\n Serendipity workflow. In other words, currently old custom backend\n themes are deprecated. We are still working on how to deal\n with this and if we can add some sort of compatibility or port.", " * Fix bundled jquery's source mapping, upgraded to 1.11.1", " * Fixed missing media name in resize GET URL", " * Fix MediaDB overlay display", " * Re-Added possibility to change filename/target directory for\n media uploads", " * Update CKEditor to 4.4", " * Fixed some missing internationalization instances", " * Minor CSS improvements for upgrader, plugin sequencing widget", " * RSS importer accepts pubDate in addition to pubdate element.", " * Upgrader in Dashboard can be disabled, returns error message when\n URL not accessible", " * Added a category filtering ability for the entry editor", " * Better check when removing old/dead files to prevent error\n messages", " * WYSIWYG editor respects image floats", " * Support html5 multiple file upload", " * Modernizr, magnificPopup updates", " * Improvements to equal heights js, button labels", " * No longer truncate long entry titles", " * Improve non-WYSIWYG editor tag insertion, url insertion", " * Improve less DOM firing on certain javascript tasks", " * Introduce js_backend event hook", "\nVersion 2.0-beta1 and followup -beta2 (April 14th, 2014)\n------------------------------------------------------------------------", " * Upgrade Smarty libs to 3.1.18", " * Automatic upgrade removal of old Smarty2 files (2.0-alpha2)\n function uses SPL", " * Implemented patch https://github.com/s9y/Serendipity/pull/15", " * When switching Themes, both the backend and the frontend\n will remember the timestamp of the last theme change,\n to make sure that the browser will not cache a mismatching CSS.", " * Fix theme change issues with global template vars in core\n (1559472ca3) see 'temporary added empty $template_config_groups'\n in 1.7-rc2 (eb77dc369a)", " * Use Smarty for backend display output", " * \"Themes\" are now what has previously been mixed as \"Design\",\n \"Theme\", \"Template\" or \"Layouts\".", " * WYSIWYG-Spawn-API reworked (2k11/admin/wysiwyg_init.tpl)", " * All Javascript-functions like SetCookie now reside in a\n serendipity-object, simulating a namespace.\n SetCookie(...)\n became\n serendipity.SetCookie(...)", " * Renamed JS-Function:\n toggleCategorySelector became toggle_category_selector", " * The advanced js option (eyecandy) got removed, as such a thing\n like advanced js doesn't exist anymore", " * dashboard_plugin has an equivalent in the core, replacing the\n frontpage", " * Constants like S9Y_FRAMEWORK_COMPAT are no longer set\n (include_once is used instead)", " * New additional option to render smarty-functions:\n serendipity_smarty_show($template, $data)", " * A number of functions now returns their result instead of echoing\n them (TODO: a bunch of image- and\n trackback-functions still use echo for messages\"):\n serendipity_plugin_config\n serendipity_printEntryForm\n serendipity_printEntries\n function serendipity_showMedia\n serendipity_showPropertyForm\n showMediaLibrary\n serendipity_guessInput\n memSnap\n serendipity_displayTopUrlList\n serendipity_displayTopExits\n serendipity_displayTopReferrers\n serendipity_printConfigTemplate\n show_plugins", " * Functions removed from the core:\n serendipity_printConfigJS", " * Functions added to the core:\n serendipity_generateImageSelectorParams", " * All internal plugins got extracted from plugin_internal.inc.php\n and moved to plugins/.\n They are renamed to work there (upgrader task provides migration):\n serendipity_calendar_plugin became serendipity_plugin_calendar\n serendipity_quicksearch_plugin became serendipity_plugin_quicksearch\n serendipity_archives_plugin became serendipity_plugin_archives\n serendipity_categories_plugin became serendipity_plugin_categories\n serendipity_syndication_plugin became serendipity_plugin_syndication\n serendipity_superuser_plugin became serendipity_plugin_superuser\n serendipity_plug_plugin became serendipity_plugin_plug", " * Add plugin hook \"js\", generating a virtual serendipity.js", " * Admin JS is now bundled in serendipity_editor.js.tpl and\n rendered using smarty in the theme config", " * Admin JS got rewritten using jQuery where applicable", " * serendipity_define.js.php removed", " * Removed support for layout.php", " * The whole PHP-Code now almost never echoes integrated HTML, but\n uses smarty template (TODO: Remove the almost)\n The necessary smarty-templates reside in 2k11/admin/\n Every theme can generate its own backend if it integrates those\n templates under admin/ itself", " * 2k11 is set as the new default backend, replacing bulletproof.\n default remains the fallback so far.", " * A number of functions had some arguments removed:\n * function serendipity_displayImageList:\n From\n function serendipity_displayImageList($page = 0, $lineBreak = NULL, $manage = false, $url = NULL, $show_upload = false, $limit_path = NULL, $smarty_display = true)\n to\n function serendipity_displayImageList($page = 0, $lineBreak = NULL, $manage = false, $url = NULL, $show_upload = false, $limit_path = NULL)\n * function serendipity_showMedia\n From\n function serendipity_showMedia(&$file, &$paths, $url = '', $manage = false, $lineBreak = 3, $enclose = true, $smarty_vars = array(), $smarty_display = true)\n to\n function serendipity_showMedia(&$file, &$paths, $url = '', $manage = false, $lineBreak = 3, $enclose = true, $smarty_vars = array())\n * generate_plugins\n From\n static function generate_plugins($side, $tag = '', $negate = false, $class = null, $id = null, $tpl = 'sidebar.tpl')\n to\n static function generate_plugins($side, $negate = false, $class = null, $id = null, $tpl = 'sidebar.tpl')", " * serendipity_showMedia now no longer returns the used template and\n echoes the generated HTML, but only returns the generated HTML", " * Themes now have their own configuration page,\n ?serendipity[adminModule]=templates&serendipity[adminAction]=editConfiguration", " * jQuery in the backend no longer runs in noConflict-mode. Use\n $(...) instead of jQuery(...)", " * The entryproperty-plugin will now always delete its cache on\n uninstall, not only if the cache is activated then", " * serendipity_is_iframe now really only checks for iframe and\n doesn't also echo it", " * Added option simpleFilters (meant to indicate to show less\n filters and poweruser-options)", " * serendipity_admin_image_selector.php no longer used by 2k11,\n instead the media library (with admin/media_choose.tpl,\n admin/media_upload.tpl, media_pane.tpl, media_items.tpl)\n can generat the imageselector on its own. The editor calls\n serendipity_admin.php?serendipity[adminModule]=media instead,\n with serendipity[textarea] indicating the target, and\n serendipity[showMediaToolbar] activating the imageSelector modus", " * New required PHP-Version: 5.3 or higher (checked in the installer)", "\nVersion 1.7.8 (February 9th, 2014)\n------------------------------------------------------------------------", " * Fixed POST for db entry insert, caused by 1.7.6 security feature", "\nVersion 1.7.7 (February 6th, 2014)\n------------------------------------------------------------------------", " * Fixed PHP parse error in templatechooser plugin. Blame garvin. :(", "\nVersion 1.7.6 (February 6th, 2014)\n------------------------------------------------------------------------", " * Fixed backend security issues, thanks to Stefan Schurtz:", " - XSS of users realname in \"Manage users\" section\n (Backend, requires login)\n - XSS when creating an entry with bad id/timestamp values\n (Backend, requires login)\n - SQL-Injection for plugin installation parameter\n (Backend, requires admin login)", " * Templatechooser plugin uses \"default\" template as fallback,\n not \"bulletproof\".", "\nVersion 1.7.5 (January 18th, 2014)\n------------------------------------------------------------------------", " * Fixed textile PHP 5.2 (namespace) compat issue", " * Added default value to spamblocks required_fields option [name,\n comment]", "\nVersion 1.7.4 (January 11th, 2014)\n------------------------------------------------------------------------", " * Fixed emoticate plugin icon link to check for textile class", " * Upgrade textile plugin libs - lib3 extends to PHP >= 5.3.\n Please check for new options!", " * Fixed spamblocks Captcha imagecreate() with PHP > 5.3 versions", " * Smarty 3.1.16 bugfix release - please read bundled-libs/Smarty/change_log.txt\n about changes to versions 3.1.16 and 3.1.15.\n Please also see special bundled-libs/Smarty/3.1.16_RELEASE_NOTES.txt", " * Removed blogg.de filter from spamblock plugin, adapted htaccess\n IP block algorithm for race conditions. .htaccess can now contain\n multiple Deny From ranges to prevent parsing problems (DLange)", " * Fixed IP columns in spamblocklog, spamblock_htaccess, karmalog, visitors\n and shoutbox to varchar(45) for IPv6 - including tunneled IPv4 (39+6)", " * Fixed possible double includement of plugin_internal.inc.php", " * Fix possible temporary caching errors failing $eventData[0]['properties']", " * Basic support for static blocks (includeentry plugin) in 2k11.", " * Added \"backend_footer\" event hook", " * Exclude \"frontpage extensions\" directories \"_vti_cnf\" on windows servers\n in Media Library", " * Fixed pagination when searching terms with fetchlimit < 4", " * Fixed deprecated /e modifier with PHP >= 5.5 in nl2br plugin restore method", "\nVersion 1.7.3 (August 28th, 2013)\n------------------------------------------------------------------------", " * Trackback to https:// style URLs will use proper port 443 instead\n of 80.", " * Disabled htmlarea spellchecker module, http://osvdb.org/87395\n Thanks for Henri Salo for pointing this out. CVE-2013-5670", "\nVersion 1.7.2 (July 26th, 2013)\n------------------------------------------------------------------------", " * Fix a syntax error in the \"mysql\" deprecation code, thanks\n to Ian", "\nVersion 1.7.1 (July 26th, 2013)\n------------------------------------------------------------------------", " * Added new event hooks \"backend_plugins_install\", \"backend_plugins_update\"\n and \"backend_templates_install\".", " * Serendipity will switch to mysqli if PHP >= 5.5 is used (mysql\n is deprecated)", " * Smarty upgrade to 3.1.14 (read changeLog and the README for API changes since Smarty 2)", " * Upgrader will now remove/delete the browsercompatibility plugin", " * Fixed Media Library exclude path to not show/proceed ckeditor/kcfinders .thumbs dir", " * Fixed bulletproof->colorset GET mismatch with categorytemplates plugin\n config.inc.php [Line 29]", " * German translation for stable archives added (YL)", " * Fixed curl result bug in spartacus plugin", " * Create new migration task for propagate defaultBaseURL when\n currently empty (onli)", " * Fixed statistics sidebar querys ( & for PostgreSQL ) [242520b]\n and added some missing html end tags", " * Added missing current group name when editing usergroups", "\nVersion 1.7 (May 11th, 2013)\n------------------------------------------------------------------------", " * rc4: Get ready for CKEDITOR-wysiwyg Plugin mode", " * rc4: Fixed fetching javascript object (for nugget textareas) in non-wysiwyg-mode", " * rc4: Change .htaccess blocking mechanism by spamblock plugin to not fetch\n too many datarows, thanks to DLange from the forums. (The .htaccess\n feature is still considered experimental, use at your own risk ;))", " * rc4: Fixed entryproperties backend 'cache now' link", " * rc3 + rc4: Media database: Escape more Cookie values to prevent storing\n possible XSS (http://board.s9y.org/viewtopic.php?f=3&t=19142).\n Escape hotlinked media filename. Escape importer host name error\n Thanks to GreenSun from the forums for bringing this to attention,\n originally reported by Dshellnoi Unix", " * rc2: Alter entries.tpl to add the line:\n {assign var=\"entry\" value=$entry scope=\"parent\"}\n for proper propagation of $entry to sub-templates.", " * rc2: Alter error reporting to only fail when 'debug' mode is enabled,\n so that \"normal\" blog installations will not fail on specific\n E_STRICT warnings that are not important.", " * rc2: temporary added empty $template_config_groups into templates with config,\n to avoid display troubles for template changes, if previous template had these set.\n Please check your template.", " * rc2: reflect POST submitted changes in Bulletproof template configs re-set situations", " * various PHP 5 compatibility fixes in core and plugins", " * Allow entryproperties plugin to define defaults for custom fields", " * Onyx, Net_URL classes: Remove PHP4 style constructor due to\n PHP5 error \"Constructor already defined\"", " * Improved RSS sidebarplugin to support Atom", " * Bundled simplepie", " * For Blogs running on a non-UTF-8 language, set a Smarty constant\n to indicate the actually used charset.", " * Added to use MyISAM handler for s9y tables (we do not use InnoDB\n features, but rely on MyISAM fulltext)", " * fixed defaultBaseURL did not show up installer. Thanks to onli.\n Follow up from c292bad", " * fixed draft & future entries preview link in backend", " * Improved karmarating plugin to be able to use AJAX calls\n (gregman)", " * Allow Smarty to fetch .tpl files from all directories so that\n s9y plugin can use the fetch() call for their .tpl files no\n matter which (symlinked) directory the plugin resides in.\n The Smarty security policy to us only serves as a restriction\n within .tpl files to not allow arbitrary PHP modifier/function calls.\n If in the future Smarty supports enforcing trustedDir checks on\n {include} calls seperately to smarty->fetch() calls, we'll also\n add that to .tpl files.\n (garvinhicking)", " * Patch by Markus Brükner: Properly handle files that have no\n extension in media database", " * Made Spartacus recognize github.com mirror (garvinhicking)", " * Add \"Summary\" output to title of summary archive pages, patch by\n hboeck", " * Set the smarty object by instance (ophian)\n It is often needed to access the Smarty object from anywhere in your code, e.g. in plugins\n We now ensure that there is only one instance of the object available.\n To obtain an instance of this class: $serendipity['smarty'] = Serendipity_Smarty::getInstance();\n The first time this is called a new instance will be created. Thereafter, the same instance is handed back.\n To overwrite use $serendipity['smarty'] = new Serendipity_Smarty; to create a new instance.", " * Set a global Serendipity errorToExceptionHandler (ophian)\n changed some old smarty trigger_errors to PHPs native function", " * Updated spamblock plugin (ophian)\n changed wordfilter to function and Commenters moderation check verify_once\n to get checked via wordfilter to reject known spam comments before", " * Changed backend comment (error) messages (ophian)\n as now captured and styleable messages\n (newly added .serendipity_backend_msg_notice css class)", " * Updated nl2br plugin (ophian)\n added isolation tag using nl to br\n this also adds some NoBR buttons to backend entry forms", " * Smarty3 support (ophian)\n with this upgrade Serendipity / Smarty will at least need a webserver running the PHP 5.2 series.\n As of August 2011, all PHP users should note, that the PHP 5.2 series is NOT supported anymore by the PHP developers.\n All users are strongly encouraged to upgrade to PHP 5.3.8 and up. Please refer to your ISP about this.", " * Added new serendipity['defaultBaseURL'] variable that makes sure\n that the baseURL is not overriden when configuring serendipity\n with a possibly autodetected currentl URL. Patch by Manko10.", "\n(Older NEWS see file NEWS_OLD)" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [0, 477, 51, 78], "buggy_code_start_loc": [0, 228, 50, 57], "filenames": ["docs/NEWS", "include/admin/images.inc.php", "serendipity_config.inc.php", "templates/2k11/admin/category.inc.tpl"], "fixing_code_end_loc": [10, 480, 51, 78], "fixing_code_start_loc": [1, 228, 50, 57], "message": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:s9y:serendipity:*:*:*:*:*:*:*:*", "matchCriteriaId": "2B92E31B-BBE7-4C4B-9369-EBDD59B9D34D", "versionEndExcluding": null, "versionEndIncluding": "2.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code."}, {"lang": "es", "value": "En Serendipity en versiones anteriores a 2.0.5, un atacante puede eludir la protecci\u00f3n SSRF utilizando una direcci\u00f3n IP malformada (e.g., http://127.1) o un c\u00f3digo de estado HTTP 30x (tambi\u00e9n conocido como Redirection)."}], "evaluatorComment": null, "id": "CVE-2016-9752", "lastModified": "2016-12-03T03:27:52.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/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": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-12-01T11:59:11.120", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/94622"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://blog.s9y.org/archives/271-Serendipity-2.0.5-and-2.1-beta3-released.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}, "type": "CWE-918"}
229
Determine whether the {function_name} code is vulnerable or not.
[ "Version 2.0.5 (November 28th, 2016)\n------------------------------------------------------------------------", " * [Security] Improve preventing fetching local files, thanks to\n Xu Yue.\n \n * [Security] Prevent XSS in adding category and directory names, \n thanks to Edric Teo @smarterbitbybit.\n", "Version 2.0.4 (September 26th, 2016)\n------------------------------------------------------------------------", " * [Security] Prevent moving files by using their directory name.\n [Security] Possible SQL injection for entry category assignment\n [Security] Possible SQL injection for removing&adding a plugin", " All issues require a valid backend login.\n Thanks to Hendrik Buchwald for finding this via their\n RIPS source code analyzer (www.ripstech.com)", " * [Security] Add new configuration option to enable fetching \n local files for the media uploader. By default this is now\n disabled to prevent Server Side Request Forgery (SSRF).\n Thanks to Xu Yue for pointing this out!", "\nVersion 2.0.3 (January 4th, 2016)\n------------------------------------------------------------------------", " * Fix XSS in backend comment editing form for logged-in authors,\n thanks to Onur Yilmaz and Robert Abela from Netsparker.com", " * Fix some backend entry form related event messages", "\nVersion 2.0.2 (Jul 24th, 2015)\n------------------------------------------------------------------------", " * Fix security issues reported by Tim Coen of Curesec.com:", " - Forbid uploading files with PHP contents and possible\n PHP execution by authenticated users (critical if\n you have possible untrustworthy authors)\n - Add proper escaping for comment approval tokens to prevent\n SQL injection (authenticated authors only)\n - Add proper escaping of comment's author names in the\n comment reply form to prevent XSS (2k11 template, javascript\n based)", " * Minor layout fixes for media DB media filters", " * Backported some Importer db bugfixes", " * CKEDITOR bugfix releases to 4.4.8 - please read the changelog.\n Includes widget, lineutils, fakeobjects Plugins and S9y added\n cheatsheet and procurator Plugins.\n Changed config.autoParagraph set to false, to prevent wrapping\n p tags around extraAllowedContent tags.", " * Smarty bugfix upgrades to 3.1.27 - please read the changelog.\n Compilation time was vastly improved.\n New Features in NEW_FEATURES.txt.", " * It is now possible to switch to a theme's admin theme if it has\n been selected as a frontend theme first", " * Syndication Plugin Issue #285:\n - Add \"none\" as possible value for the xml-icon in the\n syndication plugin, to enable plain links\n - Reset subtome full icon path to support\n serendipity_getTemplateFile()\n - Link creation fixes for Bulletproof coloured style (eg blue)", " * Fix auto include of a User theme /admin/user.css backend file.", " PLEASE NOTE:", " 2.0.1 brought in an automatted include of a themes \"user.css\"\n file. If you don't want to use such file any more (and you have\n one), you will have to delete or rename it by hand!", " Also please note, that user stylesheet selectors like", " .selector {\n background-image: url(img/example.jpg);\n }", " now need to use the {TEMPLATE_PATH} like", " .selector {\n background-image: url({TEMPLATE_PATH}img/example.jpg);\n }", " Content of a user.css will always be put LAST into the combined\n CSS, this means it will override any possible plugin output.\n If a user.css file does not exist in your own template directory,\n but inside the default 2k11 template directory, this will always\n be used (this behaviour is called \"default fallback chain\").", " * Use https URLs for Atom feed, if called through HTTPS (hboeck)", " * Restore the \"Show toolbar within media selector popup?\" option,\n it was ignored before.", " * Fix Issue #321, negative offset for LIMIT SQL statements when\n using stable archive sorting and plugins like history.", " * Templatechooser will not apply theme in backend admin.", " * Use \"secure\" flag for (session) cookies sent over SSL, thanks to\n dayton967", " * Make preview_iframe.tpl template files load the proper frontend\n CSS file, including cache-busting version string when changing\n themes", " * Implement patch to properly initiate templates_c on installation\n for shared installs (thanks to fugue88)", " * Allow templatechooser plugin to read a custom \"blacklist.txt\"\n within its directory, that can blacklist certain themes from\n being selected.", " * Allow serendipity_setCookie() function to set custom expiry.", " * Adapt .htaccess profile of \"mod_rewrite for 1&1 and problematic\n servers\" to not include the \"Options -MultiViews\" option, since\n this is often blocked", " * Fix initializing smarty framework in the preview/saving iframe,\n so that a template's config.inc.php is always loaded.", " * Show debugging .tpl file information with relative directory only", " * fix wrong upgrade removal of dead files with 2.0.1 update", "\nVersion 2.0.1 (March 12th, 2015)\n------------------------------------------------------------------------", " * Fix missing escaping (possible XSS) of category names in the\n Backend Entry Admin, which would allow editors that create a\n forged category name to attack other editors in the backend\n (privileged access to the backend required). Thanks a lot to Edric\n Teo for reporting this issue.", " * Improved detection for possible upgrade/plugin/PHP errors. A\n warning will be emitted on the dashboard, when the Serendipity\n JavaScript library could not be loaded.", " * syndication fix: use absolute urls for subtome", " * Issue 306: localStorage may be deactivated by setting a config\n option or using security-related extensions at least in some\n browsers, which might (at least in FF) break backend JS\n functionality. Added extra tests to 2k11 backend JS.", " If you use localStorage, please test if it is actually available\n by testing if localStorage !== null in JS.", " * Issue 280: Allow every theme to utilize a \"user.css\" file that\n gets loaded on top of the frontend (or backend, if in admin/\n subdirectory) theme. This file can be used for customized CSS of\n a blog-admin which carries over to future Serendipity updates", " * Issue 299: Do not display dashboard for users with no permission\n to perform actions in the backend (frontend-users)", " * Make \"rewriteURL\" smarty modifier available to do a\n {$CONST.PATH_ARCHIVE|rewriteURL} within a smarty template file.", " * Add a generic odd/even for backend dashboard widgets to align\n properly. Future dashboard widgets need to get the new extra\n class dashboard widget on the section element they create.", " * Fix event emoticate plugin to reflect proper call usage of\n serendipity_getTemplateFile(), if a theme uses custom emoticons.\n UPDATE your themes emoticons.inc.php file, if have. See example\n file in plugin dir.", " * Change 2k11 config.inc.php to reflect proper\n serendipity_getTemplateFile() when frontend files shall be\n referenced within the backend.", " * Fixed missing file message for deleted media items", " * Fixed entry editor JS not emitting a 'No tags' msg in taxonomy\n quick view. Improved serendipity.tagsList exit if freetag plugin\n is not installed.", " * Minor backend UI fixes (taxonomy quick view in entry editor,\n 'Done' msg emitted by Bayes plugin)", " * Clearer language constants for entries in dashboard, labelled\n \"In progress\"", "\nVersion 2.0 (January 23rd, 2015)\n------------------------------------------------------------------------", " * Smarty fix for purging compiled files", " * Fix wrong search page ordering when stable archive was active", " * Prevent entryproperties from saving/displaying a browser-side\n stored password that was actually not set.", " * Stronger check for existing logger interface to prevent errors\n when it is not actively used.", " * Fix entryproperties being removed when publishing an article\n from the dashboard and by specific plugins (freetag, trackback)\n that modify entry data.", " * Fix deleting comments when user is not an admin, but the entry\n belongs to him. Thanks to berberic.", " * Patch PEAR.php to use \"static\" isError declaration to prevent\n PHP error messages", " * Change order of IF-statements in entries.tpl to check for\n comment_moderate/comment_added, to properly emit the message\n whether a comment is being moderated.", " * Fix searching for entries in the admin panel with database\n types other than \"mysql\"", " * Change entry editor's category assignment to toggle between\n a hierarchical and a plain list (good for many categories)", " * Fix date formatting in entry editor to not use ISO year\n but the calendar year", " * Fix autoupdate version read and transmit", "\nVersion 2.0-rc2 (December 23rd, 2014)\n------------------------------------------------------------------------", " * Fixes escaping of comments in the new backend pane to prevent\n XSS. Thanks to Steffen Röemann for reporting!", " * Fix wrong parameter count in serendipity_entity_decode", "\nVersion 2.0-rc1 (includes beta4/5/6) (December 19th, 2014)\n------------------------------------------------------------------------", " * entryproperties plugin will now automatically disable nl2br\n markup, when the WYSIWYG editor is used to create en entry", " * PHP Requirement now is at: PHP 5.3+", " * Fix for syndication subtome onclick handler", " * Fix problematic preview stylesheet reference", " * Optimized clearing smarty template files on upgrading", " * Properly reset the \"disable markup\" feature of entryproperties\n plugin when none selected", " * PHP 5.4+ fix to properly call htmlspecialchars() / htmlentities() /\n html_entity_decode() with a charset option, that has been\n set to to default to UTF-8 and will yield empty strings when\n being used in NON-UTF-8 environments. Now we utilize a\n serendipity_specialchars() wrapper call.", " * Added SQLite3 OO database layer for PHP 5.4+", " * New personal preference to choose CKEditor toolbar presets.\n Presets can be overwritte through a\n templates/xxx/admin/ckeditor_custom_config.js if needed.\n See htmlarea/ckeditor_s9y_config.js for details.", " * Proof of concept templates \"default-php\" and \"default-xml\" have\n been moved to Siber...Spartacus. They would need adapting to\n Serendipity 2.0 (simple methods like getConfigDir() et al),\n but since those Template APIs have virtually zero usage scenario,\n they remain experimental.", " * Added new PAT_JS mod_rewrite rule to .htaccess files", " * Removed experimental support for PHP/SMARTY IN-MEMORY caching\n added in 2.0-beta3, since this could not work.", " * Smarty 3.1.21 upgrade (see changelog)", " * Fix ImageMagick new sizing issues while forcing image geometry\n exactly to given sizes with imageselectorplus", " * Fix issue #220 with pdf directory moving rename() error", " * Fix bug in entry listing, which showed wrong categories for\n entries (Issue #201)", " * Improve RegExp for Feed-URL matching, thanks to fugue88", " * Proper SQLite PDO filenames in shared installations (Issue #214)", " * ImageMagick now can get parameters to generate thumbnails,\n see serendipity_config.inc.php for example values", " * Allow to enable/disable the new autosave feature in personal\n preferences (Issue #213)", " * Re-added installer test for writable serendipity base directory", "\nVersion 2.0-beta3 (July 25th, 2014)\n------------------------------------------------------------------------", " * Move admin/media_showitem.tpl to theme's directory in 2k11. With\n an adaptation in serendipity_admin_image_selector.php, this now is\n a \"true\" frontend template which uses the styles of the frontend\n theme. Theme authors might want to adapt it to their themes.", " * Moved general syndication plugin option into the core", " * Smarty 3.1.19 upgrade (see changelog)", " * Fixed thumbnail recreation, Issue #134", " * Merged external JS libraries into a central \"plugins.js\" of the 2k11\n backend template, can be updated through\n templates/2k11/admin/js/gruntipity.php helper script.", " * Adapted database table structure change for statistics, shoutbox,\n karma and spamblock plugin (for new field definition of \"ip\" field)\n Thanks to rohdef!", " * Added new option \"enabledBackendPopups\" that allow to specify\n if inline modal dialogs or popups are used in the backend for\n e.g. the category selectory and media library", " * added experimental support for PHP/SMARTY IN MEMORY caching\n Enabled by default, if classes found loaded.\n Disable with\n $serendipity['disable_apc'] = true;\n and\n $serendipity['disable_memcache'] = true;", " * Support added in serendipity_db_schema_import for sqlite\n autoincrement", " * Remove Google Reader button from syndication plugin options", " * Add subToMe-button to syndication plugin and change its defaults", " * Use Browsercache to save cache and restore entries", " * Improved installer to forbid using database table prefixes with\n special characters", " * Themes using Engines are now able to use the parent's\n configuration", " * Prevent \"new\" plugin api to install double instances of plugins\n that are not stackable (issue #45)", " * Back button in plugin-config", " * Adapted serendipity_editor.js to provide more global (though\n deprecated) API access methods for plugins like amazonchooser\n and linktrimmer, to perform insertion. Also fixed the\n insertion of text when the ID of the element is not prefixed", " * Move sort by name to simple filter in ML, replace file extension", " * Remember selected media library folder", " * Show upload-success or error with the ajax image uploader", " * Fix preview entry exception (issue #119)", " * Add serendipity.toggle_collapsible as a reusable JS function\n for the core backend and backend sections emitted by plugins as\n an easy way to provide show/hide functionality. (yellowled)", " * Fixed media insert target bug (issued by #143, #145, #121)", " * Fixed publish drafted-entries via dashboard (issue #160)", " * All frontend themes that rely on the bundled Core jQuery library\n are currently using the jquery.noConflict-mode for compatibility\n to older plugins.\n This mode is now considered deprecated and will be removed in\n future releases. A new variable:\n $serendipity['capabilities']['jquery-noconflict'] = false;\n in your theme's config.inc.php file can now turn of that\n noConflict-mode.", " * Due to distinction of backend and frontend themes, each theme\n that provides a custom jquery.js now only does so for the\n frontend. The backend now listens to a:", " $serendipity['capabilities']['jquery_backend'] = false;", " variable, and the file needs to be jquery_backend.js that\n a backend theme would reference to.", " * Changed 2k11's config.inc.php file to provide a more stable\n call of event hooks so that other themes can also hook\n their own events.", " * Changed JS for category filtering and its reset button to be a\n reusable function, which is now also used in the list of\n installable plugins.", " * Fixed wrong local documentation URL in plugin configuration", " * Added new \"backend_dashboard\" event-hook for plugins to use\n within dashboard.", " * Backend and Frontend themes can now be set independently from\n each other. New backend themes now need to set:", " Backend: Yes", " in their info.txt file. If you adapt a custom admin theme,\n ensure that it is compatible to the new \"2k11\" backend to\n ensure proper future usage within Serendipity. The bulletproof\n backend will now no longer be recognized as a backend theme\n option, but can be selected as a new frontend theme, while\n using 2k11 (=default) in the backend.", " * Include klogger, call it as $serendipity['logger']->debug/error.\n The log-level can be set in the general configuration and is\n disabled by default.", " * Fixed missing s9ymdb ID", " * Add HTTP_Request2 and dependencies as bundled libraries and\n update PEAR library to version 1.9.4", " * Implemented AJAX uploadResize option to allow resizing an image\n before upload (onli)", " * Improved file/directory removal code to (hopefully) fail more\n gracefully", " * Change \"default\" admin backend template fallback chain so that\n old admin themes can theoretically be shown with the \"old\"\n admin interface. This however in many themes breaks the\n Serendipity workflow. In other words, currently old custom backend\n themes are deprecated. We are still working on how to deal\n with this and if we can add some sort of compatibility or port.", " * Fix bundled jquery's source mapping, upgraded to 1.11.1", " * Fixed missing media name in resize GET URL", " * Fix MediaDB overlay display", " * Re-Added possibility to change filename/target directory for\n media uploads", " * Update CKEditor to 4.4", " * Fixed some missing internationalization instances", " * Minor CSS improvements for upgrader, plugin sequencing widget", " * RSS importer accepts pubDate in addition to pubdate element.", " * Upgrader in Dashboard can be disabled, returns error message when\n URL not accessible", " * Added a category filtering ability for the entry editor", " * Better check when removing old/dead files to prevent error\n messages", " * WYSIWYG editor respects image floats", " * Support html5 multiple file upload", " * Modernizr, magnificPopup updates", " * Improvements to equal heights js, button labels", " * No longer truncate long entry titles", " * Improve non-WYSIWYG editor tag insertion, url insertion", " * Improve less DOM firing on certain javascript tasks", " * Introduce js_backend event hook", "\nVersion 2.0-beta1 and followup -beta2 (April 14th, 2014)\n------------------------------------------------------------------------", " * Upgrade Smarty libs to 3.1.18", " * Automatic upgrade removal of old Smarty2 files (2.0-alpha2)\n function uses SPL", " * Implemented patch https://github.com/s9y/Serendipity/pull/15", " * When switching Themes, both the backend and the frontend\n will remember the timestamp of the last theme change,\n to make sure that the browser will not cache a mismatching CSS.", " * Fix theme change issues with global template vars in core\n (1559472ca3) see 'temporary added empty $template_config_groups'\n in 1.7-rc2 (eb77dc369a)", " * Use Smarty for backend display output", " * \"Themes\" are now what has previously been mixed as \"Design\",\n \"Theme\", \"Template\" or \"Layouts\".", " * WYSIWYG-Spawn-API reworked (2k11/admin/wysiwyg_init.tpl)", " * All Javascript-functions like SetCookie now reside in a\n serendipity-object, simulating a namespace.\n SetCookie(...)\n became\n serendipity.SetCookie(...)", " * Renamed JS-Function:\n toggleCategorySelector became toggle_category_selector", " * The advanced js option (eyecandy) got removed, as such a thing\n like advanced js doesn't exist anymore", " * dashboard_plugin has an equivalent in the core, replacing the\n frontpage", " * Constants like S9Y_FRAMEWORK_COMPAT are no longer set\n (include_once is used instead)", " * New additional option to render smarty-functions:\n serendipity_smarty_show($template, $data)", " * A number of functions now returns their result instead of echoing\n them (TODO: a bunch of image- and\n trackback-functions still use echo for messages\"):\n serendipity_plugin_config\n serendipity_printEntryForm\n serendipity_printEntries\n function serendipity_showMedia\n serendipity_showPropertyForm\n showMediaLibrary\n serendipity_guessInput\n memSnap\n serendipity_displayTopUrlList\n serendipity_displayTopExits\n serendipity_displayTopReferrers\n serendipity_printConfigTemplate\n show_plugins", " * Functions removed from the core:\n serendipity_printConfigJS", " * Functions added to the core:\n serendipity_generateImageSelectorParams", " * All internal plugins got extracted from plugin_internal.inc.php\n and moved to plugins/.\n They are renamed to work there (upgrader task provides migration):\n serendipity_calendar_plugin became serendipity_plugin_calendar\n serendipity_quicksearch_plugin became serendipity_plugin_quicksearch\n serendipity_archives_plugin became serendipity_plugin_archives\n serendipity_categories_plugin became serendipity_plugin_categories\n serendipity_syndication_plugin became serendipity_plugin_syndication\n serendipity_superuser_plugin became serendipity_plugin_superuser\n serendipity_plug_plugin became serendipity_plugin_plug", " * Add plugin hook \"js\", generating a virtual serendipity.js", " * Admin JS is now bundled in serendipity_editor.js.tpl and\n rendered using smarty in the theme config", " * Admin JS got rewritten using jQuery where applicable", " * serendipity_define.js.php removed", " * Removed support for layout.php", " * The whole PHP-Code now almost never echoes integrated HTML, but\n uses smarty template (TODO: Remove the almost)\n The necessary smarty-templates reside in 2k11/admin/\n Every theme can generate its own backend if it integrates those\n templates under admin/ itself", " * 2k11 is set as the new default backend, replacing bulletproof.\n default remains the fallback so far.", " * A number of functions had some arguments removed:\n * function serendipity_displayImageList:\n From\n function serendipity_displayImageList($page = 0, $lineBreak = NULL, $manage = false, $url = NULL, $show_upload = false, $limit_path = NULL, $smarty_display = true)\n to\n function serendipity_displayImageList($page = 0, $lineBreak = NULL, $manage = false, $url = NULL, $show_upload = false, $limit_path = NULL)\n * function serendipity_showMedia\n From\n function serendipity_showMedia(&$file, &$paths, $url = '', $manage = false, $lineBreak = 3, $enclose = true, $smarty_vars = array(), $smarty_display = true)\n to\n function serendipity_showMedia(&$file, &$paths, $url = '', $manage = false, $lineBreak = 3, $enclose = true, $smarty_vars = array())\n * generate_plugins\n From\n static function generate_plugins($side, $tag = '', $negate = false, $class = null, $id = null, $tpl = 'sidebar.tpl')\n to\n static function generate_plugins($side, $negate = false, $class = null, $id = null, $tpl = 'sidebar.tpl')", " * serendipity_showMedia now no longer returns the used template and\n echoes the generated HTML, but only returns the generated HTML", " * Themes now have their own configuration page,\n ?serendipity[adminModule]=templates&serendipity[adminAction]=editConfiguration", " * jQuery in the backend no longer runs in noConflict-mode. Use\n $(...) instead of jQuery(...)", " * The entryproperty-plugin will now always delete its cache on\n uninstall, not only if the cache is activated then", " * serendipity_is_iframe now really only checks for iframe and\n doesn't also echo it", " * Added option simpleFilters (meant to indicate to show less\n filters and poweruser-options)", " * serendipity_admin_image_selector.php no longer used by 2k11,\n instead the media library (with admin/media_choose.tpl,\n admin/media_upload.tpl, media_pane.tpl, media_items.tpl)\n can generat the imageselector on its own. The editor calls\n serendipity_admin.php?serendipity[adminModule]=media instead,\n with serendipity[textarea] indicating the target, and\n serendipity[showMediaToolbar] activating the imageSelector modus", " * New required PHP-Version: 5.3 or higher (checked in the installer)", "\nVersion 1.7.8 (February 9th, 2014)\n------------------------------------------------------------------------", " * Fixed POST for db entry insert, caused by 1.7.6 security feature", "\nVersion 1.7.7 (February 6th, 2014)\n------------------------------------------------------------------------", " * Fixed PHP parse error in templatechooser plugin. Blame garvin. :(", "\nVersion 1.7.6 (February 6th, 2014)\n------------------------------------------------------------------------", " * Fixed backend security issues, thanks to Stefan Schurtz:", " - XSS of users realname in \"Manage users\" section\n (Backend, requires login)\n - XSS when creating an entry with bad id/timestamp values\n (Backend, requires login)\n - SQL-Injection for plugin installation parameter\n (Backend, requires admin login)", " * Templatechooser plugin uses \"default\" template as fallback,\n not \"bulletproof\".", "\nVersion 1.7.5 (January 18th, 2014)\n------------------------------------------------------------------------", " * Fixed textile PHP 5.2 (namespace) compat issue", " * Added default value to spamblocks required_fields option [name,\n comment]", "\nVersion 1.7.4 (January 11th, 2014)\n------------------------------------------------------------------------", " * Fixed emoticate plugin icon link to check for textile class", " * Upgrade textile plugin libs - lib3 extends to PHP >= 5.3.\n Please check for new options!", " * Fixed spamblocks Captcha imagecreate() with PHP > 5.3 versions", " * Smarty 3.1.16 bugfix release - please read bundled-libs/Smarty/change_log.txt\n about changes to versions 3.1.16 and 3.1.15.\n Please also see special bundled-libs/Smarty/3.1.16_RELEASE_NOTES.txt", " * Removed blogg.de filter from spamblock plugin, adapted htaccess\n IP block algorithm for race conditions. .htaccess can now contain\n multiple Deny From ranges to prevent parsing problems (DLange)", " * Fixed IP columns in spamblocklog, spamblock_htaccess, karmalog, visitors\n and shoutbox to varchar(45) for IPv6 - including tunneled IPv4 (39+6)", " * Fixed possible double includement of plugin_internal.inc.php", " * Fix possible temporary caching errors failing $eventData[0]['properties']", " * Basic support for static blocks (includeentry plugin) in 2k11.", " * Added \"backend_footer\" event hook", " * Exclude \"frontpage extensions\" directories \"_vti_cnf\" on windows servers\n in Media Library", " * Fixed pagination when searching terms with fetchlimit < 4", " * Fixed deprecated /e modifier with PHP >= 5.5 in nl2br plugin restore method", "\nVersion 1.7.3 (August 28th, 2013)\n------------------------------------------------------------------------", " * Trackback to https:// style URLs will use proper port 443 instead\n of 80.", " * Disabled htmlarea spellchecker module, http://osvdb.org/87395\n Thanks for Henri Salo for pointing this out. CVE-2013-5670", "\nVersion 1.7.2 (July 26th, 2013)\n------------------------------------------------------------------------", " * Fix a syntax error in the \"mysql\" deprecation code, thanks\n to Ian", "\nVersion 1.7.1 (July 26th, 2013)\n------------------------------------------------------------------------", " * Added new event hooks \"backend_plugins_install\", \"backend_plugins_update\"\n and \"backend_templates_install\".", " * Serendipity will switch to mysqli if PHP >= 5.5 is used (mysql\n is deprecated)", " * Smarty upgrade to 3.1.14 (read changeLog and the README for API changes since Smarty 2)", " * Upgrader will now remove/delete the browsercompatibility plugin", " * Fixed Media Library exclude path to not show/proceed ckeditor/kcfinders .thumbs dir", " * Fixed bulletproof->colorset GET mismatch with categorytemplates plugin\n config.inc.php [Line 29]", " * German translation for stable archives added (YL)", " * Fixed curl result bug in spartacus plugin", " * Create new migration task for propagate defaultBaseURL when\n currently empty (onli)", " * Fixed statistics sidebar querys ( & for PostgreSQL ) [242520b]\n and added some missing html end tags", " * Added missing current group name when editing usergroups", "\nVersion 1.7 (May 11th, 2013)\n------------------------------------------------------------------------", " * rc4: Get ready for CKEDITOR-wysiwyg Plugin mode", " * rc4: Fixed fetching javascript object (for nugget textareas) in non-wysiwyg-mode", " * rc4: Change .htaccess blocking mechanism by spamblock plugin to not fetch\n too many datarows, thanks to DLange from the forums. (The .htaccess\n feature is still considered experimental, use at your own risk ;))", " * rc4: Fixed entryproperties backend 'cache now' link", " * rc3 + rc4: Media database: Escape more Cookie values to prevent storing\n possible XSS (http://board.s9y.org/viewtopic.php?f=3&t=19142).\n Escape hotlinked media filename. Escape importer host name error\n Thanks to GreenSun from the forums for bringing this to attention,\n originally reported by Dshellnoi Unix", " * rc2: Alter entries.tpl to add the line:\n {assign var=\"entry\" value=$entry scope=\"parent\"}\n for proper propagation of $entry to sub-templates.", " * rc2: Alter error reporting to only fail when 'debug' mode is enabled,\n so that \"normal\" blog installations will not fail on specific\n E_STRICT warnings that are not important.", " * rc2: temporary added empty $template_config_groups into templates with config,\n to avoid display troubles for template changes, if previous template had these set.\n Please check your template.", " * rc2: reflect POST submitted changes in Bulletproof template configs re-set situations", " * various PHP 5 compatibility fixes in core and plugins", " * Allow entryproperties plugin to define defaults for custom fields", " * Onyx, Net_URL classes: Remove PHP4 style constructor due to\n PHP5 error \"Constructor already defined\"", " * Improved RSS sidebarplugin to support Atom", " * Bundled simplepie", " * For Blogs running on a non-UTF-8 language, set a Smarty constant\n to indicate the actually used charset.", " * Added to use MyISAM handler for s9y tables (we do not use InnoDB\n features, but rely on MyISAM fulltext)", " * fixed defaultBaseURL did not show up installer. Thanks to onli.\n Follow up from c292bad", " * fixed draft & future entries preview link in backend", " * Improved karmarating plugin to be able to use AJAX calls\n (gregman)", " * Allow Smarty to fetch .tpl files from all directories so that\n s9y plugin can use the fetch() call for their .tpl files no\n matter which (symlinked) directory the plugin resides in.\n The Smarty security policy to us only serves as a restriction\n within .tpl files to not allow arbitrary PHP modifier/function calls.\n If in the future Smarty supports enforcing trustedDir checks on\n {include} calls seperately to smarty->fetch() calls, we'll also\n add that to .tpl files.\n (garvinhicking)", " * Patch by Markus Brükner: Properly handle files that have no\n extension in media database", " * Made Spartacus recognize github.com mirror (garvinhicking)", " * Add \"Summary\" output to title of summary archive pages, patch by\n hboeck", " * Set the smarty object by instance (ophian)\n It is often needed to access the Smarty object from anywhere in your code, e.g. in plugins\n We now ensure that there is only one instance of the object available.\n To obtain an instance of this class: $serendipity['smarty'] = Serendipity_Smarty::getInstance();\n The first time this is called a new instance will be created. Thereafter, the same instance is handed back.\n To overwrite use $serendipity['smarty'] = new Serendipity_Smarty; to create a new instance.", " * Set a global Serendipity errorToExceptionHandler (ophian)\n changed some old smarty trigger_errors to PHPs native function", " * Updated spamblock plugin (ophian)\n changed wordfilter to function and Commenters moderation check verify_once\n to get checked via wordfilter to reject known spam comments before", " * Changed backend comment (error) messages (ophian)\n as now captured and styleable messages\n (newly added .serendipity_backend_msg_notice css class)", " * Updated nl2br plugin (ophian)\n added isolation tag using nl to br\n this also adds some NoBR buttons to backend entry forms", " * Smarty3 support (ophian)\n with this upgrade Serendipity / Smarty will at least need a webserver running the PHP 5.2 series.\n As of August 2011, all PHP users should note, that the PHP 5.2 series is NOT supported anymore by the PHP developers.\n All users are strongly encouraged to upgrade to PHP 5.3.8 and up. Please refer to your ISP about this.", " * Added new serendipity['defaultBaseURL'] variable that makes sure\n that the baseURL is not overriden when configuring serendipity\n with a possibly autodetected currentl URL. Patch by Manko10.", "\n(Older NEWS see file NEWS_OLD)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [0, 477, 51, 78], "buggy_code_start_loc": [0, 228, 50, 57], "filenames": ["docs/NEWS", "include/admin/images.inc.php", "serendipity_config.inc.php", "templates/2k11/admin/category.inc.tpl"], "fixing_code_end_loc": [10, 480, 51, 78], "fixing_code_start_loc": [1, 228, 50, 57], "message": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:s9y:serendipity:*:*:*:*:*:*:*:*", "matchCriteriaId": "2B92E31B-BBE7-4C4B-9369-EBDD59B9D34D", "versionEndExcluding": null, "versionEndIncluding": "2.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code."}, {"lang": "es", "value": "En Serendipity en versiones anteriores a 2.0.5, un atacante puede eludir la protecci\u00f3n SSRF utilizando una direcci\u00f3n IP malformada (e.g., http://127.1) o un c\u00f3digo de estado HTTP 30x (tambi\u00e9n conocido como Redirection)."}], "evaluatorComment": null, "id": "CVE-2016-9752", "lastModified": "2016-12-03T03:27:52.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/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": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-12-01T11:59:11.120", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/94622"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://blog.s9y.org/archives/271-Serendipity-2.0.5-and-2.1-beta3-released.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}, "type": "CWE-918"}
229
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "if (IN_serendipity !== true) {\n die (\"Don't hack!\");\n}", "if (!serendipity_checkPermission('adminImages')) {\n return;\n}", "$data = array();", "if (!is_object($serendipity['smarty'])) {\n serendipity_smarty_init();\n}", "switch ($serendipity['GET']['adminAction']) {", " case 'doSync':\n $data['case_doSync'] = true;\n $data['perm_adminImagesSync'] = true;\n // I don't know how it could've changed, but let's be safe.\n if (!serendipity_checkPermission('adminImagesSync')) {\n $data['perm_adminImagesSync'] = false;\n break;\n }", " if (function_exists('set_time_limit')) {\n @set_time_limit(0);\n }\n @ignore_user_abort();", " $deleteThumbs = false;\n if (isset($serendipity['POST']['deleteThumbs'])) {\n switch ($serendipity['POST']['deleteThumbs'])\n {\n case 'yes':\n $deleteThumbs = true;\n break;\n case 'check':\n $deleteThumbs = 'checksize';\n break;\n }\n }", " $i = serendipity_syncThumbs($deleteThumbs);\n $data['print_SYNC_DONE'] = sprintf(SYNC_DONE, $i);\n flush();", " $i = serendipity_generateThumbs();\n $data['print_RESIZE_DONE'] = sprintf(RESIZE_DONE, $i);\n flush();\n break;", " case 'doDelete':\n if (!serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDelete')) {\n break;\n }", " $messages = array();\n $data['case_do_delete'] = true;\n $messages[] = serendipity_deleteImage($serendipity['GET']['fid']);\n $messages[] = sprintf('<span class=\"msg_notice\"><span class=\"icon-info-circled\"></span> ' . RIP_ENTRY . '</span>', $serendipity['GET']['fid']);", " $data['showML'] = showMediaLibrary();\n $data['messages'] = $messages;\n unset($messages);\n break;", "\n case 'doMultiDelete':\n if (!serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDelete')) {\n break;\n }", " $messages = array();\n $parts = explode(',', $serendipity['GET']['id']);\n $data['case_do_multidelete'] = true;\n foreach($parts AS $id) {\n $id = (int)$id;\n if ($id > 0) {\n $image = serendipity_fetchImageFromDatabase($id);\n $messages[] = serendipity_deleteImage((int)$id);\n $messages[] = sprintf('<span class=\"msg_notice\"><span class=\"icon-info-circled\"></span> ' . RIP_ENTRY . '</span>', $image['id'] . ' - ' . serendipity_specialchars($image['realname']));\n }\n }\n $data['showML'] = showMediaLibrary();\n $data['messages'] = $messages;\n unset($messages);\n break;", " case 'delete':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);", " if (!is_array($file) || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }", " $data['case_delete'] = true;\n if (!isset($serendipity['adminFile'])) {\n $serendipity['adminFile'] = 'serendipity_admin.php';\n }\n $abortLoc = $serendipity['serendipityHTTPPath'] . $serendipity['adminFile'] . '?serendipity[adminModule]=images';\n $newLoc = $abortLoc . '&serendipity[adminAction]=doDelete&serendipity[fid]=' . (int)$serendipity['GET']['fid'] . '&' . serendipity_setFormToken('url');\n $data['file'] = $file['name'] . '.' . $file['extension'];\n $data['abortLoc'] = $abortLoc;\n $data['newLoc'] = $newLoc;\n break;", " case 'multidelete':\n if (!serendipity_checkFormToken() || !is_array($serendipity['POST']['multiDelete'])) {\n break;\n }", " $ids = '';\n $data['rip_image'] = array();\n $data['case_multidelete'] = true;\n foreach($serendipity['POST']['multiDelete'] AS $idx => $id) {\n $ids .= (int)$id . ',';\n $image = serendipity_fetchImageFromDatabase($id);\n $data['rip_image'][] = sprintf(DELETE_SURE, $image['id'] . ' - ' . serendipity_specialchars($image['realname']));\n }\n if (!isset($serendipity['adminFile'])) {\n $serendipity['adminFile'] = 'serendipity_admin.php';\n }\n $abortLoc = $serendipity['serendipityHTTPPath'] . $serendipity['adminFile'] . '?serendipity[adminModule]=images';\n $newLoc = $serendipity['serendipityHTTPPath'] . $serendipity['adminFile'] . '?' . serendipity_setFormToken('url') . '&amp;serendipity[action]=admin&amp;serendipity[adminModule]=images&amp;serendipity[adminAction]=doMultiDelete&amp;serendipity[id]=' . $ids;\n $data['case_confirm_deletion'] = true;\n $data['abortLoc'] = $abortLoc;\n $data['newLoc'] = $newLoc;\n break;", " case 'rename':\n $data['case_rename'] = true;\n $serendipity['GET']['fid'] = (int)$serendipity['GET']['fid'];\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);\n $serendipity['GET']['newname'] = serendipity_uploadSecure($serendipity['GET']['newname'], true);", " if (!is_array($file) || !serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }", " if (!serendipity_moveMediaDirectory(null, $serendipity['GET']['newname'], 'file', $serendipity['GET']['fid'], $file)) {\n $data['go_back'] = true;\n break;\n }\n break;", " case 'properties':\n $data['case_properties'] = true;\n $new_media = array(array('image_id' => $serendipity['GET']['fid']));\n echo serendipity_showPropertyForm($new_media);\n break;", " case 'add':\n if (!serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesAdd')) {\n return;\n }\n $data['case_add'] = true;\n $messages = array();\n if ($serendipity['POST']['adminSubAction'] == 'properties') {\n $properties = serendipity_parsePropertyForm();\n $image_id = $properties['image_id'];\n $created_thumbnail = true;\n $data['showML'] = showMediaLibrary($messages, true);\n break;\n }", " $messages[] = '<span class=\"msg_notice\"><span class=\"icon-info-circled\"></span> ' . ADDING_IMAGE . '</span>';", " $authorid = (isset($serendipity['POST']['all_authors']) && $serendipity['POST']['all_authors'] == 'true') ? '0' : $serendipity['authorid'];", " $new_media = array();", " $serendipity['POST']['imageurl'] = serendipity_specialchars($serendipity['POST']['imageurl']);", " // First find out whether to fetch a file or accept an upload\n if ($serendipity['POST']['imageurl'] != '' && $serendipity['POST']['imageurl'] != 'http://') {\n if (!empty($serendipity['POST']['target_filename'][2])) {\n // Faked hidden form 2 when submitting with JavaScript\n $tfile = $serendipity['POST']['target_filename'][2];\n $tindex = 2;\n } elseif (!empty($serendipity['POST']['target_filename'][1])) {\n // Fallback key when not using JavaScript\n $tfile = $serendipity['POST']['target_filename'][1];\n $tindex = 1;\n } else {\n $tfile = $serendipity['POST']['imageurl'];\n $tindex = 1;\n }", " $tfile = serendipity_uploadSecure(basename($tfile));", " if (serendipity_isActiveFile($tfile)) {\n $messages[] = sprintf('<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . ERROR_FILE_FORBIDDEN . '</span>', $tfile);\n break;\n }", " $serendipity['POST']['target_directory'][$tindex] = serendipity_uploadSecure($serendipity['POST']['target_directory'][$tindex], true, true);\n $target = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $serendipity['POST']['target_directory'][$tindex] . $tfile;", " if (!serendipity_checkDirUpload($serendipity['POST']['target_directory'][$tindex])) {\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . PERM_DENIED . '</span>';\n return;\n }", " $realname = $tfile;\n if (file_exists($target)) {\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . $target . ' - ' . ERROR_FILE_EXISTS_ALREADY . '</span>';\n $realname = serendipity_imageAppend($tfile, $target, $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $serendipity['POST']['target_directory'][$tindex]);\n }", " if (!serendipity_url_allowed($serendipity['POST']['imageurl'])) {\n $messages[] = sprintf('<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . REMOTE_FILE_INVALID . \"</span>\\n\", $serendipity['POST']['imageurl']);\n } else {\n require_once S9Y_PEAR_PATH . 'HTTP/Request.php';\n $options = array('allowRedirects' => true, 'maxRedirects' => 5);\n serendipity_plugin_api::hook_event('backend_http_request', $options, 'image');\n serendipity_request_start();\n $req = new HTTP_Request($serendipity['POST']['imageurl'], $options);\n // Try to get the URL", " if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') {\n $messages[] = sprintf('<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . REMOTE_FILE_NOT_FOUND . '</span>', $serendipity['POST']['imageurl']);\n } else {\n // Fetch file\n $fContent = $req->getResponseBody();", "\n if ($serendipity['POST']['imageimporttype'] == 'hotlink') {", " $tempfile = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . '/hotlink_' . time();\n $fp = fopen($tempfile, 'w');\n fwrite($fp, $fContent);\n fclose($fp);", " $image_id = @serendipity_insertHotlinkedImageInDatabase($tfile, $serendipity['POST']['imageurl'], $authorid, null, $tempfile);\n $messages[] = sprintf('<span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> ' . HOTLINK_DONE . '</span>', $serendipity['POST']['imageurl'] , $tfile .'');\n serendipity_plugin_api::hook_event('backend_image_addHotlink', $tempfile);\n } else {\n $fp = fopen($target, 'w');\n fwrite($fp, $fContent);\n fclose($fp);", " $messages[] = sprintf('<span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> ' . FILE_FETCHED . '</span>', $serendipity['POST']['imageurl'] , $tfile . '');", " if (serendipity_checkMediaSize($target)) {\n $thumbs = array(array(\n 'thumbSize' => $serendipity['thumbSize'],\n 'thumb' => $serendipity['thumbSuffix']\n ));\n serendipity_plugin_api::hook_event('backend_media_makethumb', $thumbs);", " foreach($thumbs as $thumb) {\n // Create thumbnail\n if ( $created_thumbnail = serendipity_makeThumbnail($tfile, $serendipity['POST']['target_directory'][$tindex], $thumb['thumbSize'], $thumb['thumb']) ) {\n $messages[] = '<span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> ' . THUMB_CREATED_DONE . '</span>';\n }\n }", " // Insert into database\n $image_id = serendipity_insertImageInDatabase($tfile, $serendipity['POST']['target_directory'][$tindex], $authorid, null, $realname);\n serendipity_plugin_api::hook_event('backend_image_add', $target);\n $new_media[] = array(\n 'image_id' => $image_id,\n 'target' => $target,\n 'created_thumbnail' => $created_thumbnail\n );\n }\n }\n serendipity_request_end();\n }\n }\n } else {\n if (!is_array($_FILES['serendipity']['name']['userfile'])) {\n break;\n }", " foreach($_FILES['serendipity']['name']['userfile'] AS $idx => $uploadfiles) {\n if (! is_array($uploadfiles)) {\n $uploadfiles = array($uploadfiles);\n }\n $uploadFileCounter=-1;\n foreach($uploadfiles AS $uploadfile) {\n $uploadFileCounter++;\n $target_filename = $serendipity['POST']['target_filename'][$idx];\n $uploadtmp = $_FILES['serendipity']['tmp_name']['userfile'][$idx];\n if (is_array($uploadtmp)) {\n $uploadtmp = $uploadtmp[$uploadFileCounter];\n }\n if (!empty($target_filename)) {\n $tfile = $target_filename;\n } elseif (!empty($uploadfile)) {\n $tfile = $uploadfile;\n } else {\n // skip empty array\n continue;\n }", " $tfile = serendipity_uploadSecure(basename($tfile));", " if (serendipity_isActiveFile($tfile)) {\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . ERROR_FILE_FORBIDDEN .' '. $tfile . '</span>';\n continue;\n }", " $serendipity['POST']['target_directory'][$idx] = serendipity_uploadSecure($serendipity['POST']['target_directory'][$idx], true, true);", " if (!serendipity_checkDirUpload($serendipity['POST']['target_directory'][$idx])) {\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . PERM_DENIED . '</span>';\n continue;\n }", " $target = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $serendipity['POST']['target_directory'][$idx] . $tfile;", " $realname = $tfile;\n if (file_exists($target)) {\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . $target . ' - ' . ERROR_FILE_EXISTS_ALREADY . '</span>';\n $realname = serendipity_imageAppend($tfile, $target, $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $serendipity['POST']['target_directory'][$idx]);\n }", " // Accept file\n if (is_uploaded_file($uploadtmp) && serendipity_checkMediaSize($uploadtmp) && move_uploaded_file($uploadtmp, $target)) {\n $messages[] = sprintf('<span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> ' . FILE_UPLOADED . '</span>', $uploadfile , $target);\n @umask(0000);\n @chmod($target, 0664);", " $thumbs = array(array(\n 'thumbSize' => $serendipity['thumbSize'],\n 'thumb' => $serendipity['thumbSuffix']\n ));\n serendipity_plugin_api::hook_event('backend_media_makethumb', $thumbs);", " foreach($thumbs as $thumb) {\n // Create thumbnail\n if ( $created_thumbnail = serendipity_makeThumbnail($tfile, $serendipity['POST']['target_directory'][$idx], $thumb['thumbSize'], $thumb['thumb']) ) {\n $messages[] = '<span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> ' . THUMB_CREATED_DONE . '</span>';\n }\n }", " // Insert into database\n $image_id = serendipity_insertImageInDatabase($tfile, $serendipity['POST']['target_directory'][$idx], $authorid, null, $realname);\n serendipity_plugin_api::hook_event('backend_image_add', $target, $created_thumbnail);\n $new_media[] = array(\n 'image_id' => $image_id,\n 'target' => $target,\n 'created_thumbnail' => $created_thumbnail\n );\n } else {\n // necessary for the ajax-uplaoder to show upload errors\n header(\"Internal Server Error\", true, 500);\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . ERROR_UNKNOWN_NOUPLOAD . '</span>';\n }\n }\n }\n }", " if (isset($_REQUEST['go_properties'])) {\n echo serendipity_showPropertyForm($new_media);\n } else {\n $hidden = array(\n 'author' => $serendipity['serendipityUser'],\n 'authorid' => $serendipity['authorid']\n );", " foreach($new_media AS $nm) {\n serendipity_insertMediaProperty('base_hidden', '', $nm['image_id'], $hidden);\n }\n $data['showML'] = showMediaLibrary(null, true);\n }\n $data['messages'] = $messages;\n break;", "\n case 'directoryDoDelete':\n if (!serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }", " $data['case_directoryDoDelete'] = true;\n $new_dir = serendipity_uploadSecure($serendipity['GET']['dir'], true);\n if (is_dir($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $new_dir)) {\n if (!is_writable($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $new_dir)) {\n $data['print_DIRECTORY_WRITE_ERROR'] = sprintf(DIRECTORY_WRITE_ERROR, $new_dir);\n } else {\n ob_start();\n // Directory exists and is writable. Now dive within subdirectories and kill 'em all.\n serendipity_killPath($serendipity['serendipityPath'] . $serendipity['uploadPath'], $new_dir, (isset($serendipity['POST']['nuke']) ? true : false));\n $data['ob_serendipity_killPath'] = ob_get_contents();\n ob_end_clean();\n }\n } else {\n $data['print_ERROR_NO_DIRECTORY'] = sprintf(ERROR_NO_DIRECTORY, $new_dir);\n }", " serendipity_plugin_api::hook_event('backend_directory_delete', $new_dir);\n break;", " case 'directoryEdit':\n if (!serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }", " $data['case_directoryEdit'] = true;\n $use_dir = serendipity_uploadSecure($serendipity['GET']['dir']);\n $checkpath = array(\n array(\n 'relpath' => $use_dir\n )\n );", " if (!serendipity_directoryACL($checkpath, 'write')) {\n return;\n }", " if (!empty($serendipity['POST']['save'])) {\n $newDir = serendipity_uploadSecure($serendipity['POST']['newDir']) . '/';\n $oldDir = serendipity_uploadSecure($serendipity['POST']['oldDir']) . '/';", " if ($oldDir != $newDir) {\n //is this possible?\n ob_start();\n serendipity_moveMediaDirectory($oldDir, $newDir);\n $data['ob_serendipity_moveMediaDirectory'] = ob_get_contents();\n ob_end_clean();\n $use_dir = $newDir;\n }\n serendipity_ACLGrant(0, 'directory', 'read', $serendipity['POST']['read_authors'], $use_dir);\n serendipity_ACLGrant(0, 'directory', 'write', $serendipity['POST']['write_authors'], $use_dir);\n $data['print_SETTINGS_SAVED_AT'] = sprintf(SETTINGS_SAVED_AT, serendipity_strftime('%H:%M:%S'));\n }", " $groups = serendipity_getAllGroups();\n $read_groups = serendipity_ACLGet(0, 'directory', 'read', $use_dir);\n $write_groups = serendipity_ACLGet(0, 'directory', 'write', $use_dir);", " if (!empty($serendipity['POST']['update_children'])) {\n $dir_list = serendipity_traversePath($serendipity['serendipityPath'] . $serendipity['uploadPath'], $use_dir, true, NULL, 1, NULL, 'write', NULL);\n foreach($dir_list AS $f => $dir) {\n // Apply parent ACL to children.\n serendipity_ACLGrant(0, 'directory', 'read', $serendipity['POST']['read_authors'], $dir['relpath']);\n serendipity_ACLGrant(0, 'directory', 'write', $serendipity['POST']['write_authors'], $dir['relpath']);\n }\n }\n $data['groups'] = $groups;\n $data['use_dir'] = $use_dir;\n $data['formtoken'] = serendipity_setFormToken();\n $data['dir'] = serendipity_specialchars($serendipity['GET']['dir']);\n $data['rgroups'] = (isset($read_groups[0]) ? true : false);\n $data['wgroups'] = (isset($write_groups[0]) ? true : false);\n $data['read_groups'] = $read_groups;\n $data['write_groups'] = $write_groups;\n break;", " case 'directoryDelete':\n if (!serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }\n $data['case_directoryDelete'] = true;\n $data['dir'] = serendipity_specialchars($serendipity['GET']['dir']);\n $data['formtoken'] = serendipity_setFormToken();\n $data['basename_dir'] = basename(serendipity_specialchars($serendipity['GET']['dir']));\n break;", " case 'directoryDoCreate':\n if (!serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }", " $data['case_directoryDoCreate'] = true;\n $new_dir = serendipity_uploadSecure($serendipity['POST']['parent'] . '/' . $serendipity['POST']['name'], true);\n $new_dir = str_replace(array('..', '//'), array('', '/'), $new_dir);\n $nd = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $new_dir;\n serendipity_plugin_api::hook_event('backend_directory_create', $nd);", " /* TODO: check if directory already exist */\n if (is_dir($nd) || @mkdir($nd)) {", " $data['print_DIRECTORY_CREATED'] = sprintf(DIRECTORY_CREATED, $serendipity['POST']['name']);", " @umask(0000);\n @chmod($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $new_dir, 0777);", " // Apply parent ACL to new child.\n $array_parent_read = serendipity_ACLGet(0, 'directory', 'read', $serendipity['POST']['parent']);\n $array_parent_write = serendipity_ACLGet(0, 'directory', 'write', $serendipity['POST']['parent']);\n if (!is_array($array_parent_read) || count($array_parent_read) < 1) {\n $parent_read = array(0);\n } else {\n $parent_read = array_keys($array_parent_read);\n }\n if (!is_array($array_parent_write) || count($array_parent_write) < 1) {\n $parent_write = array(0);\n } else {\n $parent_write = array_keys($array_parent_write);\n }", " serendipity_ACLGrant(0, 'directory', 'read', $parent_read, $new_dir . '/');\n serendipity_ACLGrant(0, 'directory', 'write', $parent_write, $new_dir . '/');\n } else {\n $data['print_DIRECTORY_WRITE_ERROR'] = sprintf(DIRECTORY_WRITE_ERROR, $new_dir);\n }", " break;", " case 'directoryCreate':\n case 'directoryCreateSub':\n if (!serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }", " $folders = serendipity_traversePath(\n $serendipity['serendipityPath'] . $serendipity['uploadPath'],\n '',\n true,\n NULL,\n 1,\n NULL,\n 'write'\n );\n usort($folders, 'serendipity_sortPath');\n $data['case_directoryCreate'] = true;\n $data['formtoken'] = serendipity_setFormToken();\n $data['folders'] = $folders;\n $data['dir'] = $serendipity['GET']['dir'];\n break;", " case 'directorySelect':\n if (!serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }", " $folders = serendipity_traversePath(\n $serendipity['serendipityPath'] . $serendipity['uploadPath'],\n '',\n true,\n NULL,\n 1,\n NULL,\n 'write'\n );\n usort($folders, 'serendipity_sortPath');\n $data['case_directorySelect'] = true;\n $data['folders'] = $folders;\n break;", " case 'addSelect':\n if (!serendipity_checkPermission('adminImagesAdd')) {\n return;\n }", " serendipity_restoreVar($serendipity['COOKIE']['addmedia_directory'], $serendipity['GET']['only_path']);\n $folders = serendipity_traversePath(\n $serendipity['serendipityPath'] . $serendipity['uploadPath'],\n '',\n true,\n NULL,\n 1,\n NULL,\n 'write'\n );\n usort($folders, 'serendipity_sortPath');", " $form_hidden = '';\n if (isset($image_selector_addvars) && is_array($image_selector_addvars)) {\n // These variables may come from serendipity_admin_image_selector.php to show embedded upload form\n foreach($image_selector_addvars AS $imgsel_key => $imgsel_val) {\n $form_hidden .= ' <input type=\"hidden\" name=\"serendipity[' . serendipity_specialchars($imgsel_key) . ']\" value=\"' . serendipity_specialchars($imgsel_val) . '\" />' . \"\\n\";\n }\n }", " $mediaFiles = array(\n 'token' => serendipity_setFormToken(),\n 'form_hidden' => $form_hidden,\n 'folders' => $folders,\n 'only_path' => $serendipity['GET']['only_path'],\n 'max_file_size' => $serendipity['maxFileSize'],\n 'maxImgHeight' => $serendipity['maxImgHeight'],\n 'maxImgWidth' => $serendipity['maxImgWidth'],\n 'extraParems' => serendipity_generateImageSelectorParems(),\n 'manage' => isset($serendipity['GET']['showMediaToolbar']) ? serendipity_db_bool($serendipity['GET']['showMediaToolbar']) : true\n );\n // ToDo later: merge $data and $media\n $serendipity['smarty']->assign('media', $mediaFiles);\n $serendipity['smarty']->display(serendipity_getTemplateFile('admin/media_upload.tpl', 'serendipityPath'));\n return;", " case 'rotateCW':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);\n if (!is_array($file) || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }", " if (empty($serendipity['adminFile_redirect'])) {\n $serendipity['adminFile_redirect'] = serendipity_specialchars($_SERVER['HTTP_REFERER']);\n }", " $data['case_rotateCW'] = true;\n if (serendipity_rotateImg($serendipity['GET']['fid'], -90)) {\n $data['rotate_img_done'] = true;\n $data['adminFile_redirect'] = $serendipity['adminFile_redirect'];\n }\n break;", " case 'rotateCCW':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);\n if (!is_array($file) || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }", " if (empty($serendipity['adminFile_redirect'])) {\n $serendipity['adminFile_redirect'] = serendipity_specialchars($_SERVER['HTTP_REFERER']);\n }", " $data['case_rotateCCW'] = true;\n if (serendipity_rotateImg($serendipity['GET']['fid'], 90)) {\n $data['rotate_img_done'] = true;\n $data['adminFile_redirect'] = $serendipity['adminFile_redirect'];\n }\n break;", " case 'scale':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);", " if (!is_array($file) || !serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }", " $data['case_scale'] = true;\n $data['print_SCALING_IMAGE'] = sprintf(\n SCALING_IMAGE,\n $file['path'] . $file['name'] .'.'. $file['extension'],\n (int)$serendipity['GET']['width'],\n (int)$serendipity['GET']['height']\n );\n $data['extraParems'] = serendipity_generateImageSelectorParems();\n $data['print_serendipity_scaleImg'] = serendipity_scaleImg($serendipity['GET']['fid'], $serendipity['GET']['width'], $serendipity['GET']['height']);\n break;", " case 'scaleSelect':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);", " if (!is_array($file) || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }\n \n $data['extraParems'] = serendipity_generateImageSelectorParems(\"form\");\n $data['case_scaleSelect'] = true;\n $s = getimagesize($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $file['path'] . $file['name'] . ($file['extension'] ? '.'. $file['extension'] : \"\"));\n $data['img_width'] = $s[0];\n $data['img_height'] = $s[1];", " $data['print_RESIZE_BLAHBLAH'] = sprintf(RESIZE_BLAHBLAH, serendipity_specialchars($serendipity['GET']['fname']));\n $data['print_ORIGINAL_SIZE'] = sprintf(ORIGINAL_SIZE, $s[0],$s[1]);\n $data['formtoken'] = serendipity_setFormToken();\n $data['file'] = $serendipity['uploadHTTPPath'] . $file['path'] . $file['name'] .($file['extension'] ? '.'. $file['extension'] : \"\");\n break;", " case 'choose':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);\n $media['file'] = &$file;\n if (!is_array($file)) {\n $media['perm_denied'] = true;\n break;\n }", " serendipity_prepareMedia($file);", " $media['file']['props'] =& serendipity_fetchMediaProperties((int)$serendipity['GET']['fid']);\n serendipity_plugin_api::hook_event('media_getproperties_cached', $media['file']['props']['base_metadata'], $media['file']['realfile']);", " if ($file['is_image']) {\n $file['finishJSFunction'] = $file['origfinishJSFunction'] = 'serendipity.serendipity_imageSelector_done(\\'' . serendipity_specialchars($serendipity['GET']['textarea']) . '\\')';", " if (!empty($serendipity['GET']['filename_only']) && $serendipity['GET']['filename_only'] !== 'true') {\n $file['fast_select'] = true;\n }\n }\n $media = array_merge($serendipity['GET'], $media);\n $serendipity['smarty']->assignByRef('media', $media);\n echo serendipity_smarty_show('admin/media_choose.tpl', $data);\n break;", " default:\n serendipity_restoreVar($serendipity['COOKIE']['serendipity_only_path'], $serendipity['GET']['only_path']);\n $data['case_default'] = true;\n $data['showML'] = showMediaLibrary();\n break;\n}", "function showMediaLibrary($messages=false, $addvar_check = false, $smarty_vars = array()) {\n global $serendipity;", " if (!serendipity_checkPermission('adminImagesView')) {\n return;\n }\n $output = \"\";", " // After upload, do not show the list to be able to proceed to\n // media selection.\n if ($addvar_check && !empty($GLOBALS['image_selector_addvars'])) {\n return true;\n }", " if (!isset($serendipity['thumbPerPage'])) {\n $serendipity['thumbPerPage'] = 2;\n }\n $smarty_vars = array(\n 'textarea' => isset($serendipity['GET']['textarea']) ? $serendipity['GET']['textarea'] : false,\n 'htmltarget' => isset($serendipity['GET']['htmltarget']) ? $serendipity['GET']['htmltarget'] : '',\n 'filename_only' => isset($serendipity['GET']['filename_only']) ? $serendipity['GET']['filename_only'] : false,\n );", " $show_upload = isset($serendipity['GET']['showUpload']) ? $serendipity['GET']['showUpload'] : false;", " $output .= serendipity_displayImageList(\n isset($serendipity['GET']['page']) ? $serendipity['GET']['page'] : 1,\n $serendipity['thumbPerPage'],\n isset($serendipity['GET']['showMediaToolbar']) ? serendipity_db_bool($serendipity['GET']['showMediaToolbar']) : true,\n NULL,\n $show_upload,\n NULL,\n $smarty_vars\n );\n return $output;\n}", "if (! isset($data['showML'])) {\n if (isset($_REQUEST['go_properties'])) {\n $data['showMLbutton'] = true;\n } else {\n // always having the ML available is useful when switching the filter after adding an image, thus being in the add-case\n $data['showML'] = showMediaLibrary();\n }\n}", "$data['get']['fid'] = $serendipity['GET']['fid']; // don't trust {$smarty.get.vars} if not proofed, as we often change GET vars via serendipty['GET'] by runtime\n$data['get']['only_path'] = $serendipity['GET']['only_path'];", "echo serendipity_smarty_show('admin/images.inc.tpl', $data);", "/* vim: set sts=4 ts=4 expandtab : */" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [0, 477, 51, 78], "buggy_code_start_loc": [0, 228, 50, 57], "filenames": ["docs/NEWS", "include/admin/images.inc.php", "serendipity_config.inc.php", "templates/2k11/admin/category.inc.tpl"], "fixing_code_end_loc": [10, 480, 51, 78], "fixing_code_start_loc": [1, 228, 50, 57], "message": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:s9y:serendipity:*:*:*:*:*:*:*:*", "matchCriteriaId": "2B92E31B-BBE7-4C4B-9369-EBDD59B9D34D", "versionEndExcluding": null, "versionEndIncluding": "2.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code."}, {"lang": "es", "value": "En Serendipity en versiones anteriores a 2.0.5, un atacante puede eludir la protecci\u00f3n SSRF utilizando una direcci\u00f3n IP malformada (e.g., http://127.1) o un c\u00f3digo de estado HTTP 30x (tambi\u00e9n conocido como Redirection)."}], "evaluatorComment": null, "id": "CVE-2016-9752", "lastModified": "2016-12-03T03:27:52.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/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": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-12-01T11:59:11.120", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/94622"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://blog.s9y.org/archives/271-Serendipity-2.0.5-and-2.1-beta3-released.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}, "type": "CWE-918"}
229
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "if (IN_serendipity !== true) {\n die (\"Don't hack!\");\n}", "if (!serendipity_checkPermission('adminImages')) {\n return;\n}", "$data = array();", "if (!is_object($serendipity['smarty'])) {\n serendipity_smarty_init();\n}", "switch ($serendipity['GET']['adminAction']) {", " case 'doSync':\n $data['case_doSync'] = true;\n $data['perm_adminImagesSync'] = true;\n // I don't know how it could've changed, but let's be safe.\n if (!serendipity_checkPermission('adminImagesSync')) {\n $data['perm_adminImagesSync'] = false;\n break;\n }", " if (function_exists('set_time_limit')) {\n @set_time_limit(0);\n }\n @ignore_user_abort();", " $deleteThumbs = false;\n if (isset($serendipity['POST']['deleteThumbs'])) {\n switch ($serendipity['POST']['deleteThumbs'])\n {\n case 'yes':\n $deleteThumbs = true;\n break;\n case 'check':\n $deleteThumbs = 'checksize';\n break;\n }\n }", " $i = serendipity_syncThumbs($deleteThumbs);\n $data['print_SYNC_DONE'] = sprintf(SYNC_DONE, $i);\n flush();", " $i = serendipity_generateThumbs();\n $data['print_RESIZE_DONE'] = sprintf(RESIZE_DONE, $i);\n flush();\n break;", " case 'doDelete':\n if (!serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDelete')) {\n break;\n }", " $messages = array();\n $data['case_do_delete'] = true;\n $messages[] = serendipity_deleteImage($serendipity['GET']['fid']);\n $messages[] = sprintf('<span class=\"msg_notice\"><span class=\"icon-info-circled\"></span> ' . RIP_ENTRY . '</span>', $serendipity['GET']['fid']);", " $data['showML'] = showMediaLibrary();\n $data['messages'] = $messages;\n unset($messages);\n break;", "\n case 'doMultiDelete':\n if (!serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDelete')) {\n break;\n }", " $messages = array();\n $parts = explode(',', $serendipity['GET']['id']);\n $data['case_do_multidelete'] = true;\n foreach($parts AS $id) {\n $id = (int)$id;\n if ($id > 0) {\n $image = serendipity_fetchImageFromDatabase($id);\n $messages[] = serendipity_deleteImage((int)$id);\n $messages[] = sprintf('<span class=\"msg_notice\"><span class=\"icon-info-circled\"></span> ' . RIP_ENTRY . '</span>', $image['id'] . ' - ' . serendipity_specialchars($image['realname']));\n }\n }\n $data['showML'] = showMediaLibrary();\n $data['messages'] = $messages;\n unset($messages);\n break;", " case 'delete':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);", " if (!is_array($file) || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }", " $data['case_delete'] = true;\n if (!isset($serendipity['adminFile'])) {\n $serendipity['adminFile'] = 'serendipity_admin.php';\n }\n $abortLoc = $serendipity['serendipityHTTPPath'] . $serendipity['adminFile'] . '?serendipity[adminModule]=images';\n $newLoc = $abortLoc . '&serendipity[adminAction]=doDelete&serendipity[fid]=' . (int)$serendipity['GET']['fid'] . '&' . serendipity_setFormToken('url');\n $data['file'] = $file['name'] . '.' . $file['extension'];\n $data['abortLoc'] = $abortLoc;\n $data['newLoc'] = $newLoc;\n break;", " case 'multidelete':\n if (!serendipity_checkFormToken() || !is_array($serendipity['POST']['multiDelete'])) {\n break;\n }", " $ids = '';\n $data['rip_image'] = array();\n $data['case_multidelete'] = true;\n foreach($serendipity['POST']['multiDelete'] AS $idx => $id) {\n $ids .= (int)$id . ',';\n $image = serendipity_fetchImageFromDatabase($id);\n $data['rip_image'][] = sprintf(DELETE_SURE, $image['id'] . ' - ' . serendipity_specialchars($image['realname']));\n }\n if (!isset($serendipity['adminFile'])) {\n $serendipity['adminFile'] = 'serendipity_admin.php';\n }\n $abortLoc = $serendipity['serendipityHTTPPath'] . $serendipity['adminFile'] . '?serendipity[adminModule]=images';\n $newLoc = $serendipity['serendipityHTTPPath'] . $serendipity['adminFile'] . '?' . serendipity_setFormToken('url') . '&amp;serendipity[action]=admin&amp;serendipity[adminModule]=images&amp;serendipity[adminAction]=doMultiDelete&amp;serendipity[id]=' . $ids;\n $data['case_confirm_deletion'] = true;\n $data['abortLoc'] = $abortLoc;\n $data['newLoc'] = $newLoc;\n break;", " case 'rename':\n $data['case_rename'] = true;\n $serendipity['GET']['fid'] = (int)$serendipity['GET']['fid'];\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);\n $serendipity['GET']['newname'] = serendipity_uploadSecure($serendipity['GET']['newname'], true);", " if (!is_array($file) || !serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }", " if (!serendipity_moveMediaDirectory(null, $serendipity['GET']['newname'], 'file', $serendipity['GET']['fid'], $file)) {\n $data['go_back'] = true;\n break;\n }\n break;", " case 'properties':\n $data['case_properties'] = true;\n $new_media = array(array('image_id' => $serendipity['GET']['fid']));\n echo serendipity_showPropertyForm($new_media);\n break;", " case 'add':\n if (!serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesAdd')) {\n return;\n }\n $data['case_add'] = true;\n $messages = array();\n if ($serendipity['POST']['adminSubAction'] == 'properties') {\n $properties = serendipity_parsePropertyForm();\n $image_id = $properties['image_id'];\n $created_thumbnail = true;\n $data['showML'] = showMediaLibrary($messages, true);\n break;\n }", " $messages[] = '<span class=\"msg_notice\"><span class=\"icon-info-circled\"></span> ' . ADDING_IMAGE . '</span>';", " $authorid = (isset($serendipity['POST']['all_authors']) && $serendipity['POST']['all_authors'] == 'true') ? '0' : $serendipity['authorid'];", " $new_media = array();", " $serendipity['POST']['imageurl'] = serendipity_specialchars($serendipity['POST']['imageurl']);", " // First find out whether to fetch a file or accept an upload\n if ($serendipity['POST']['imageurl'] != '' && $serendipity['POST']['imageurl'] != 'http://') {\n if (!empty($serendipity['POST']['target_filename'][2])) {\n // Faked hidden form 2 when submitting with JavaScript\n $tfile = $serendipity['POST']['target_filename'][2];\n $tindex = 2;\n } elseif (!empty($serendipity['POST']['target_filename'][1])) {\n // Fallback key when not using JavaScript\n $tfile = $serendipity['POST']['target_filename'][1];\n $tindex = 1;\n } else {\n $tfile = $serendipity['POST']['imageurl'];\n $tindex = 1;\n }", " $tfile = serendipity_uploadSecure(basename($tfile));", " if (serendipity_isActiveFile($tfile)) {\n $messages[] = sprintf('<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . ERROR_FILE_FORBIDDEN . '</span>', $tfile);\n break;\n }", " $serendipity['POST']['target_directory'][$tindex] = serendipity_uploadSecure($serendipity['POST']['target_directory'][$tindex], true, true);\n $target = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $serendipity['POST']['target_directory'][$tindex] . $tfile;", " if (!serendipity_checkDirUpload($serendipity['POST']['target_directory'][$tindex])) {\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . PERM_DENIED . '</span>';\n return;\n }", " $realname = $tfile;\n if (file_exists($target)) {\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . $target . ' - ' . ERROR_FILE_EXISTS_ALREADY . '</span>';\n $realname = serendipity_imageAppend($tfile, $target, $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $serendipity['POST']['target_directory'][$tindex]);\n }", " if (!serendipity_url_allowed($serendipity['POST']['imageurl'])) {\n $messages[] = sprintf('<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . REMOTE_FILE_INVALID . \"</span>\\n\", $serendipity['POST']['imageurl']);\n } else {\n require_once S9Y_PEAR_PATH . 'HTTP/Request.php';\n $options = array('allowRedirects' => true, 'maxRedirects' => 5);\n serendipity_plugin_api::hook_event('backend_http_request', $options, 'image');\n serendipity_request_start();\n $req = new HTTP_Request($serendipity['POST']['imageurl'], $options);\n // Try to get the URL", " if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') {\n $messages[] = sprintf('<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . REMOTE_FILE_NOT_FOUND . '</span>', $serendipity['POST']['imageurl']);\n } else {\n // Fetch file\n $fContent = $req->getResponseBody();", " $fUrl = $req->getEffectiveUrl();", " if (!serendipity_url_allowed($fUrl)) {\n $messages[] = sprintf('<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . REMOTE_FILE_INVALID . \"</span>\\n\", $fUrl);\n } elseif ($serendipity['POST']['imageimporttype'] == 'hotlink') {", " $tempfile = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . '/hotlink_' . time();\n $fp = fopen($tempfile, 'w');\n fwrite($fp, $fContent);\n fclose($fp);", " $image_id = @serendipity_insertHotlinkedImageInDatabase($tfile, $serendipity['POST']['imageurl'], $authorid, null, $tempfile);\n $messages[] = sprintf('<span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> ' . HOTLINK_DONE . '</span>', $serendipity['POST']['imageurl'] , $tfile .'');\n serendipity_plugin_api::hook_event('backend_image_addHotlink', $tempfile);\n } else {\n $fp = fopen($target, 'w');\n fwrite($fp, $fContent);\n fclose($fp);", " $messages[] = sprintf('<span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> ' . FILE_FETCHED . '</span>', $serendipity['POST']['imageurl'] , $tfile . '');", " if (serendipity_checkMediaSize($target)) {\n $thumbs = array(array(\n 'thumbSize' => $serendipity['thumbSize'],\n 'thumb' => $serendipity['thumbSuffix']\n ));\n serendipity_plugin_api::hook_event('backend_media_makethumb', $thumbs);", " foreach($thumbs as $thumb) {\n // Create thumbnail\n if ( $created_thumbnail = serendipity_makeThumbnail($tfile, $serendipity['POST']['target_directory'][$tindex], $thumb['thumbSize'], $thumb['thumb']) ) {\n $messages[] = '<span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> ' . THUMB_CREATED_DONE . '</span>';\n }\n }", " // Insert into database\n $image_id = serendipity_insertImageInDatabase($tfile, $serendipity['POST']['target_directory'][$tindex], $authorid, null, $realname);\n serendipity_plugin_api::hook_event('backend_image_add', $target);\n $new_media[] = array(\n 'image_id' => $image_id,\n 'target' => $target,\n 'created_thumbnail' => $created_thumbnail\n );\n }\n }\n serendipity_request_end();\n }\n }\n } else {\n if (!is_array($_FILES['serendipity']['name']['userfile'])) {\n break;\n }", " foreach($_FILES['serendipity']['name']['userfile'] AS $idx => $uploadfiles) {\n if (! is_array($uploadfiles)) {\n $uploadfiles = array($uploadfiles);\n }\n $uploadFileCounter=-1;\n foreach($uploadfiles AS $uploadfile) {\n $uploadFileCounter++;\n $target_filename = $serendipity['POST']['target_filename'][$idx];\n $uploadtmp = $_FILES['serendipity']['tmp_name']['userfile'][$idx];\n if (is_array($uploadtmp)) {\n $uploadtmp = $uploadtmp[$uploadFileCounter];\n }\n if (!empty($target_filename)) {\n $tfile = $target_filename;\n } elseif (!empty($uploadfile)) {\n $tfile = $uploadfile;\n } else {\n // skip empty array\n continue;\n }", " $tfile = serendipity_uploadSecure(basename($tfile));", " if (serendipity_isActiveFile($tfile)) {\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . ERROR_FILE_FORBIDDEN .' '. $tfile . '</span>';\n continue;\n }", " $serendipity['POST']['target_directory'][$idx] = serendipity_uploadSecure($serendipity['POST']['target_directory'][$idx], true, true);", " if (!serendipity_checkDirUpload($serendipity['POST']['target_directory'][$idx])) {\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . PERM_DENIED . '</span>';\n continue;\n }", " $target = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $serendipity['POST']['target_directory'][$idx] . $tfile;", " $realname = $tfile;\n if (file_exists($target)) {\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . $target . ' - ' . ERROR_FILE_EXISTS_ALREADY . '</span>';\n $realname = serendipity_imageAppend($tfile, $target, $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $serendipity['POST']['target_directory'][$idx]);\n }", " // Accept file\n if (is_uploaded_file($uploadtmp) && serendipity_checkMediaSize($uploadtmp) && move_uploaded_file($uploadtmp, $target)) {\n $messages[] = sprintf('<span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> ' . FILE_UPLOADED . '</span>', $uploadfile , $target);\n @umask(0000);\n @chmod($target, 0664);", " $thumbs = array(array(\n 'thumbSize' => $serendipity['thumbSize'],\n 'thumb' => $serendipity['thumbSuffix']\n ));\n serendipity_plugin_api::hook_event('backend_media_makethumb', $thumbs);", " foreach($thumbs as $thumb) {\n // Create thumbnail\n if ( $created_thumbnail = serendipity_makeThumbnail($tfile, $serendipity['POST']['target_directory'][$idx], $thumb['thumbSize'], $thumb['thumb']) ) {\n $messages[] = '<span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> ' . THUMB_CREATED_DONE . '</span>';\n }\n }", " // Insert into database\n $image_id = serendipity_insertImageInDatabase($tfile, $serendipity['POST']['target_directory'][$idx], $authorid, null, $realname);\n serendipity_plugin_api::hook_event('backend_image_add', $target, $created_thumbnail);\n $new_media[] = array(\n 'image_id' => $image_id,\n 'target' => $target,\n 'created_thumbnail' => $created_thumbnail\n );\n } else {\n // necessary for the ajax-uplaoder to show upload errors\n header(\"Internal Server Error\", true, 500);\n $messages[] = '<span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> ' . ERROR_UNKNOWN_NOUPLOAD . '</span>';\n }\n }\n }\n }", " if (isset($_REQUEST['go_properties'])) {\n echo serendipity_showPropertyForm($new_media);\n } else {\n $hidden = array(\n 'author' => $serendipity['serendipityUser'],\n 'authorid' => $serendipity['authorid']\n );", " foreach($new_media AS $nm) {\n serendipity_insertMediaProperty('base_hidden', '', $nm['image_id'], $hidden);\n }\n $data['showML'] = showMediaLibrary(null, true);\n }\n $data['messages'] = $messages;\n break;", "\n case 'directoryDoDelete':\n if (!serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }", " $data['case_directoryDoDelete'] = true;\n $new_dir = serendipity_uploadSecure($serendipity['GET']['dir'], true);\n if (is_dir($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $new_dir)) {\n if (!is_writable($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $new_dir)) {\n $data['print_DIRECTORY_WRITE_ERROR'] = sprintf(DIRECTORY_WRITE_ERROR, $new_dir);\n } else {\n ob_start();\n // Directory exists and is writable. Now dive within subdirectories and kill 'em all.\n serendipity_killPath($serendipity['serendipityPath'] . $serendipity['uploadPath'], $new_dir, (isset($serendipity['POST']['nuke']) ? true : false));\n $data['ob_serendipity_killPath'] = ob_get_contents();\n ob_end_clean();\n }\n } else {\n $data['print_ERROR_NO_DIRECTORY'] = sprintf(ERROR_NO_DIRECTORY, $new_dir);\n }", " serendipity_plugin_api::hook_event('backend_directory_delete', $new_dir);\n break;", " case 'directoryEdit':\n if (!serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }", " $data['case_directoryEdit'] = true;\n $use_dir = serendipity_uploadSecure($serendipity['GET']['dir']);\n $checkpath = array(\n array(\n 'relpath' => $use_dir\n )\n );", " if (!serendipity_directoryACL($checkpath, 'write')) {\n return;\n }", " if (!empty($serendipity['POST']['save'])) {\n $newDir = serendipity_uploadSecure($serendipity['POST']['newDir']) . '/';\n $oldDir = serendipity_uploadSecure($serendipity['POST']['oldDir']) . '/';", " if ($oldDir != $newDir) {\n //is this possible?\n ob_start();\n serendipity_moveMediaDirectory($oldDir, $newDir);\n $data['ob_serendipity_moveMediaDirectory'] = ob_get_contents();\n ob_end_clean();\n $use_dir = $newDir;\n }\n serendipity_ACLGrant(0, 'directory', 'read', $serendipity['POST']['read_authors'], $use_dir);\n serendipity_ACLGrant(0, 'directory', 'write', $serendipity['POST']['write_authors'], $use_dir);\n $data['print_SETTINGS_SAVED_AT'] = sprintf(SETTINGS_SAVED_AT, serendipity_strftime('%H:%M:%S'));\n }", " $groups = serendipity_getAllGroups();\n $read_groups = serendipity_ACLGet(0, 'directory', 'read', $use_dir);\n $write_groups = serendipity_ACLGet(0, 'directory', 'write', $use_dir);", " if (!empty($serendipity['POST']['update_children'])) {\n $dir_list = serendipity_traversePath($serendipity['serendipityPath'] . $serendipity['uploadPath'], $use_dir, true, NULL, 1, NULL, 'write', NULL);\n foreach($dir_list AS $f => $dir) {\n // Apply parent ACL to children.\n serendipity_ACLGrant(0, 'directory', 'read', $serendipity['POST']['read_authors'], $dir['relpath']);\n serendipity_ACLGrant(0, 'directory', 'write', $serendipity['POST']['write_authors'], $dir['relpath']);\n }\n }\n $data['groups'] = $groups;\n $data['use_dir'] = $use_dir;\n $data['formtoken'] = serendipity_setFormToken();\n $data['dir'] = serendipity_specialchars($serendipity['GET']['dir']);\n $data['rgroups'] = (isset($read_groups[0]) ? true : false);\n $data['wgroups'] = (isset($write_groups[0]) ? true : false);\n $data['read_groups'] = $read_groups;\n $data['write_groups'] = $write_groups;\n break;", " case 'directoryDelete':\n if (!serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }\n $data['case_directoryDelete'] = true;\n $data['dir'] = serendipity_specialchars($serendipity['GET']['dir']);\n $data['formtoken'] = serendipity_setFormToken();\n $data['basename_dir'] = basename(serendipity_specialchars($serendipity['GET']['dir']));\n break;", " case 'directoryDoCreate':\n if (!serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }", " $data['case_directoryDoCreate'] = true;\n $new_dir = serendipity_uploadSecure($serendipity['POST']['parent'] . '/' . $serendipity['POST']['name'], true);\n $new_dir = str_replace(array('..', '//'), array('', '/'), $new_dir);\n $nd = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $new_dir;\n serendipity_plugin_api::hook_event('backend_directory_create', $nd);", " /* TODO: check if directory already exist */\n if (is_dir($nd) || @mkdir($nd)) {", " $data['print_DIRECTORY_CREATED'] = sprintf(DIRECTORY_CREATED, $new_dir);", " @umask(0000);\n @chmod($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $new_dir, 0777);", " // Apply parent ACL to new child.\n $array_parent_read = serendipity_ACLGet(0, 'directory', 'read', $serendipity['POST']['parent']);\n $array_parent_write = serendipity_ACLGet(0, 'directory', 'write', $serendipity['POST']['parent']);\n if (!is_array($array_parent_read) || count($array_parent_read) < 1) {\n $parent_read = array(0);\n } else {\n $parent_read = array_keys($array_parent_read);\n }\n if (!is_array($array_parent_write) || count($array_parent_write) < 1) {\n $parent_write = array(0);\n } else {\n $parent_write = array_keys($array_parent_write);\n }", " serendipity_ACLGrant(0, 'directory', 'read', $parent_read, $new_dir . '/');\n serendipity_ACLGrant(0, 'directory', 'write', $parent_write, $new_dir . '/');\n } else {\n $data['print_DIRECTORY_WRITE_ERROR'] = sprintf(DIRECTORY_WRITE_ERROR, $new_dir);\n }", " break;", " case 'directoryCreate':\n case 'directoryCreateSub':\n if (!serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }", " $folders = serendipity_traversePath(\n $serendipity['serendipityPath'] . $serendipity['uploadPath'],\n '',\n true,\n NULL,\n 1,\n NULL,\n 'write'\n );\n usort($folders, 'serendipity_sortPath');\n $data['case_directoryCreate'] = true;\n $data['formtoken'] = serendipity_setFormToken();\n $data['folders'] = $folders;\n $data['dir'] = $serendipity['GET']['dir'];\n break;", " case 'directorySelect':\n if (!serendipity_checkPermission('adminImagesDirectories')) {\n return;\n }", " $folders = serendipity_traversePath(\n $serendipity['serendipityPath'] . $serendipity['uploadPath'],\n '',\n true,\n NULL,\n 1,\n NULL,\n 'write'\n );\n usort($folders, 'serendipity_sortPath');\n $data['case_directorySelect'] = true;\n $data['folders'] = $folders;\n break;", " case 'addSelect':\n if (!serendipity_checkPermission('adminImagesAdd')) {\n return;\n }", " serendipity_restoreVar($serendipity['COOKIE']['addmedia_directory'], $serendipity['GET']['only_path']);\n $folders = serendipity_traversePath(\n $serendipity['serendipityPath'] . $serendipity['uploadPath'],\n '',\n true,\n NULL,\n 1,\n NULL,\n 'write'\n );\n usort($folders, 'serendipity_sortPath');", " $form_hidden = '';\n if (isset($image_selector_addvars) && is_array($image_selector_addvars)) {\n // These variables may come from serendipity_admin_image_selector.php to show embedded upload form\n foreach($image_selector_addvars AS $imgsel_key => $imgsel_val) {\n $form_hidden .= ' <input type=\"hidden\" name=\"serendipity[' . serendipity_specialchars($imgsel_key) . ']\" value=\"' . serendipity_specialchars($imgsel_val) . '\" />' . \"\\n\";\n }\n }", " $mediaFiles = array(\n 'token' => serendipity_setFormToken(),\n 'form_hidden' => $form_hidden,\n 'folders' => $folders,\n 'only_path' => $serendipity['GET']['only_path'],\n 'max_file_size' => $serendipity['maxFileSize'],\n 'maxImgHeight' => $serendipity['maxImgHeight'],\n 'maxImgWidth' => $serendipity['maxImgWidth'],\n 'extraParems' => serendipity_generateImageSelectorParems(),\n 'manage' => isset($serendipity['GET']['showMediaToolbar']) ? serendipity_db_bool($serendipity['GET']['showMediaToolbar']) : true\n );\n // ToDo later: merge $data and $media\n $serendipity['smarty']->assign('media', $mediaFiles);\n $serendipity['smarty']->display(serendipity_getTemplateFile('admin/media_upload.tpl', 'serendipityPath'));\n return;", " case 'rotateCW':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);\n if (!is_array($file) || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }", " if (empty($serendipity['adminFile_redirect'])) {\n $serendipity['adminFile_redirect'] = serendipity_specialchars($_SERVER['HTTP_REFERER']);\n }", " $data['case_rotateCW'] = true;\n if (serendipity_rotateImg($serendipity['GET']['fid'], -90)) {\n $data['rotate_img_done'] = true;\n $data['adminFile_redirect'] = $serendipity['adminFile_redirect'];\n }\n break;", " case 'rotateCCW':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);\n if (!is_array($file) || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }", " if (empty($serendipity['adminFile_redirect'])) {\n $serendipity['adminFile_redirect'] = serendipity_specialchars($_SERVER['HTTP_REFERER']);\n }", " $data['case_rotateCCW'] = true;\n if (serendipity_rotateImg($serendipity['GET']['fid'], 90)) {\n $data['rotate_img_done'] = true;\n $data['adminFile_redirect'] = $serendipity['adminFile_redirect'];\n }\n break;", " case 'scale':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);", " if (!is_array($file) || !serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }", " $data['case_scale'] = true;\n $data['print_SCALING_IMAGE'] = sprintf(\n SCALING_IMAGE,\n $file['path'] . $file['name'] .'.'. $file['extension'],\n (int)$serendipity['GET']['width'],\n (int)$serendipity['GET']['height']\n );\n $data['extraParems'] = serendipity_generateImageSelectorParems();\n $data['print_serendipity_scaleImg'] = serendipity_scaleImg($serendipity['GET']['fid'], $serendipity['GET']['width'], $serendipity['GET']['height']);\n break;", " case 'scaleSelect':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);", " if (!is_array($file) || !serendipity_checkPermission('adminImagesDelete') || (!serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid'])) {\n return;\n }\n \n $data['extraParems'] = serendipity_generateImageSelectorParems(\"form\");\n $data['case_scaleSelect'] = true;\n $s = getimagesize($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $file['path'] . $file['name'] . ($file['extension'] ? '.'. $file['extension'] : \"\"));\n $data['img_width'] = $s[0];\n $data['img_height'] = $s[1];", " $data['print_RESIZE_BLAHBLAH'] = sprintf(RESIZE_BLAHBLAH, serendipity_specialchars($serendipity['GET']['fname']));\n $data['print_ORIGINAL_SIZE'] = sprintf(ORIGINAL_SIZE, $s[0],$s[1]);\n $data['formtoken'] = serendipity_setFormToken();\n $data['file'] = $serendipity['uploadHTTPPath'] . $file['path'] . $file['name'] .($file['extension'] ? '.'. $file['extension'] : \"\");\n break;", " case 'choose':\n $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);\n $media['file'] = &$file;\n if (!is_array($file)) {\n $media['perm_denied'] = true;\n break;\n }", " serendipity_prepareMedia($file);", " $media['file']['props'] =& serendipity_fetchMediaProperties((int)$serendipity['GET']['fid']);\n serendipity_plugin_api::hook_event('media_getproperties_cached', $media['file']['props']['base_metadata'], $media['file']['realfile']);", " if ($file['is_image']) {\n $file['finishJSFunction'] = $file['origfinishJSFunction'] = 'serendipity.serendipity_imageSelector_done(\\'' . serendipity_specialchars($serendipity['GET']['textarea']) . '\\')';", " if (!empty($serendipity['GET']['filename_only']) && $serendipity['GET']['filename_only'] !== 'true') {\n $file['fast_select'] = true;\n }\n }\n $media = array_merge($serendipity['GET'], $media);\n $serendipity['smarty']->assignByRef('media', $media);\n echo serendipity_smarty_show('admin/media_choose.tpl', $data);\n break;", " default:\n serendipity_restoreVar($serendipity['COOKIE']['serendipity_only_path'], $serendipity['GET']['only_path']);\n $data['case_default'] = true;\n $data['showML'] = showMediaLibrary();\n break;\n}", "function showMediaLibrary($messages=false, $addvar_check = false, $smarty_vars = array()) {\n global $serendipity;", " if (!serendipity_checkPermission('adminImagesView')) {\n return;\n }\n $output = \"\";", " // After upload, do not show the list to be able to proceed to\n // media selection.\n if ($addvar_check && !empty($GLOBALS['image_selector_addvars'])) {\n return true;\n }", " if (!isset($serendipity['thumbPerPage'])) {\n $serendipity['thumbPerPage'] = 2;\n }\n $smarty_vars = array(\n 'textarea' => isset($serendipity['GET']['textarea']) ? $serendipity['GET']['textarea'] : false,\n 'htmltarget' => isset($serendipity['GET']['htmltarget']) ? $serendipity['GET']['htmltarget'] : '',\n 'filename_only' => isset($serendipity['GET']['filename_only']) ? $serendipity['GET']['filename_only'] : false,\n );", " $show_upload = isset($serendipity['GET']['showUpload']) ? $serendipity['GET']['showUpload'] : false;", " $output .= serendipity_displayImageList(\n isset($serendipity['GET']['page']) ? $serendipity['GET']['page'] : 1,\n $serendipity['thumbPerPage'],\n isset($serendipity['GET']['showMediaToolbar']) ? serendipity_db_bool($serendipity['GET']['showMediaToolbar']) : true,\n NULL,\n $show_upload,\n NULL,\n $smarty_vars\n );\n return $output;\n}", "if (! isset($data['showML'])) {\n if (isset($_REQUEST['go_properties'])) {\n $data['showMLbutton'] = true;\n } else {\n // always having the ML available is useful when switching the filter after adding an image, thus being in the add-case\n $data['showML'] = showMediaLibrary();\n }\n}", "$data['get']['fid'] = $serendipity['GET']['fid']; // don't trust {$smarty.get.vars} if not proofed, as we often change GET vars via serendipty['GET'] by runtime\n$data['get']['only_path'] = $serendipity['GET']['only_path'];", "echo serendipity_smarty_show('admin/images.inc.tpl', $data);", "/* vim: set sts=4 ts=4 expandtab : */" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [0, 477, 51, 78], "buggy_code_start_loc": [0, 228, 50, 57], "filenames": ["docs/NEWS", "include/admin/images.inc.php", "serendipity_config.inc.php", "templates/2k11/admin/category.inc.tpl"], "fixing_code_end_loc": [10, 480, 51, 78], "fixing_code_start_loc": [1, 228, 50, 57], "message": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:s9y:serendipity:*:*:*:*:*:*:*:*", "matchCriteriaId": "2B92E31B-BBE7-4C4B-9369-EBDD59B9D34D", "versionEndExcluding": null, "versionEndIncluding": "2.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code."}, {"lang": "es", "value": "En Serendipity en versiones anteriores a 2.0.5, un atacante puede eludir la protecci\u00f3n SSRF utilizando una direcci\u00f3n IP malformada (e.g., http://127.1) o un c\u00f3digo de estado HTTP 30x (tambi\u00e9n conocido como Redirection)."}], "evaluatorComment": null, "id": "CVE-2016-9752", "lastModified": "2016-12-03T03:27:52.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/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": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-12-01T11:59:11.120", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/94622"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://blog.s9y.org/archives/271-Serendipity-2.0.5-and-2.1-beta3-released.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}, "type": "CWE-918"}
229
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n# Copyright (c) 2003-2005, Jannis Hermanns (on behalf the Serendipity Developer Team)\n# All rights reserved. See LICENSE file for licensing details", "if (defined('S9Y_FRAMEWORK')) {\n return;\n}", "@define('S9Y_FRAMEWORK', true);\nif (!headers_sent() && php_sapi_name() !== 'cli') {\n // Only set the session name, if no session has yet been issued.\n if (session_id() == '') {\n $cookieParams = session_get_cookie_params();\n $cookieParams['secure'] = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? true : false);\n session_set_cookie_params($cookieParams['lifetime'], $cookieParams['path'], $cookieParams['domain'], $cookieParams['secure'], $cookieParams['httponly']);\n session_name('s9y_' . md5(dirname(__FILE__)));\n session_start();\n }", " // Prevent session fixation by only allowing sessions that have been sent by the server.\n // Any session that does not contain our unique token will be regarded as foreign/fixated\n // and be regenerated with a system-generated SID.\n // Patch by David Vieira-Kurz of majorsecurity.de\n if (!isset($_SESSION['SERVER_GENERATED_SID'])) {\n session_regenerate_id(true);\n @session_start();\n header('X-Session-Reinit: true');\n $_SESSION['SERVER_GENERATED_SID'] = $_SERVER['REMOTE_ADDR'] . $_SERVER['QUERY_STRING'];\n }\n}", "if (!defined('S9Y_INCLUDE_PATH')) {\n define('S9Y_INCLUDE_PATH', dirname(__FILE__) . '/');\n}\ndefine('S9Y_CONFIG_TEMPLATE', S9Y_INCLUDE_PATH . 'include/tpl/config_local.inc.php');\ndefine('S9Y_CONFIG_USERTEMPLATE', S9Y_INCLUDE_PATH . 'include/tpl/config_personal.inc.php');", "define('IS_installed', file_exists('serendipity_config_local.inc.php') && (filesize('serendipity_config_local.inc.php') > 0));", "if (!defined('IN_serendipity')) {\n define('IN_serendipity', true);\n}", "include(S9Y_INCLUDE_PATH . 'include/compat.inc.php');\nif (defined('USE_MEMSNAP')) {\n echo memSnap('Framework init');\n}", "// The version string", "$serendipity['version'] = '2.0.4';", "", "// Setting this to 'false' will enable debugging output. All alpha/beta/cvs snapshot versions will emit debug information by default. To increase the debug level (to enable Smarty debugging), set this flag to 'debug'.\nif (!isset($serendipity['production'])) {\n $serendipity['production'] = ! preg_match('@\\-(alpha|beta|cvs|rc).*@', $serendipity['version']);\n}", "// Set error reporting\n// TODO: E_STRICT throws problematic errors due to \"hook_event\" being a static function, but all of our plugins don't really define that...\nerror_reporting(E_ALL & ~(E_STRICT|E_NOTICE));", "if ($serendipity['production'] !== true) {\n @ini_set('display_errors', 'on');\n}", "\n// The serendipity errorhandler string\n$serendipity['errorhandler'] = 'errorToExceptionHandler';", "\n// Default rewrite method\n$serendipity['rewrite'] = 'none';", "// Message container\n$serendipity['messagestack'] = array();", "// Can the user change the date of publishing for an entry?\n$serendipity['allowDateManipulation'] = true;", "// How much time is allowed to pass since the publising of an entry, so that a comment to that entry\n// will update it's LastModified stamp? If the time is passed, a comment to an old entry will no longer\n// push an article as being updated.\n$serendipity['max_last_modified'] = 60 * 60 * 24 * 7;", "// Clients can send a If-Modified Header to the RSS Feed (Conditional Get) and receive all articles beyond\n// that date. However it is still limited by the number below of maximum entries\n$serendipity['max_fetch_limit'] = 50;", "// How many bytes are allowed for fetching trackbacks, so that no binary files get accidently trackbacked?\n$serendipity['trackback_filelimit'] = 150 * 1024;", "// Allow \"Access-Controll-Allow-Origin: *\" to be used in sensible locations (RSS feed)\n$serendipity['cors'] = false;", "if (!isset($serendipity['fetchLimit'])) {\n $serendipity['fetchLimit'] = 15;\n}", "if (!isset($serendipity['RSSfetchLimit'])) {\n $serendipity['RSSfetchLimit'] = 15;\n}", "if (!isset($serendipity['mediaProperties'])) {\n $serendipity['mediaProperties'] = 'DPI;COPYRIGHT;TITLE;COMMENT1:MULTI;COMMENT2:MULTI;ALT';\n}", "if (!isset($serendipity['use_PEAR'])) {\n $serendipity['use_PEAR'] = true;\n}", "if (!isset($serendipity['useHTTP-Auth'])) {\n $serendipity['useHTTP-Auth'] = true;\n}", "if (!isset($serendipity['CacheControl'])) {\n $serendipity['CacheControl'] = true;\n}", "if (!isset($serendipity['expose_s9y'])) {\n $serendipity['expose_s9y'] = true;\n}", "// Should IFRAMEs be used for previewing entries and sending trackbacks?\n$serendipity['use_iframe'] = true;", "/* Default language for autodetection */\n$serendipity['autolang'] = 'en';", "/* Name of folder for the default theme */\n$serendipity['defaultTemplate'] = '2k11';", "/* Default backend theme */\nif (!isset($serendipity['template_backend'])) {\n $serendipity['template_backend'] = '2k11';\n}", "/* Available languages */\nif (!isset($serendipity['languages'])) {\n $serendipity['languages'] = array('en' => 'English',\n 'de' => 'German',\n 'da' => 'Danish',\n 'es' => 'Spanish',\n 'fr' => 'French',\n 'fi' => 'Finnish',\n 'cs' => 'Czech (Win-1250)',\n 'cz' => 'Czech (ISO-8859-2)',\n 'sk' => 'Slovak',\n 'nl' => 'Dutch',\n 'is' => 'Icelandic',\n 'tr' => 'Turkish',\n 'se' => 'Swedish',\n 'pt' => 'Portuguese Brazilian',\n 'pt_PT' => 'Portuguese European',\n 'bg' => 'Bulgarian',\n 'hu' => 'Hungarian',\n 'no' => 'Norwegian',\n 'pl' => 'Polish',\n 'ro' => 'Romanian',\n 'it' => 'Italian',\n 'ru' => 'Russian',\n 'fa' => 'Persian',\n 'tw' => 'Traditional Chinese (Big5)',\n 'tn' => 'Traditional Chinese (UTF-8)',\n 'zh' => 'Simplified Chinese (GB2312)',\n 'cn' => 'Simplified Chinese (UTF-8)',\n 'ja' => 'Japanese',\n 'ko' => 'Korean',\n 'sa' => 'Arabic',\n 'ta' => 'Tamil');\n}", "/* Available Calendars */\n$serendipity['calendars'] = array('gregorian' => 'Gregorian',\n 'persian-utf8' => 'Persian (utf8)');\n/*\n * Load main language file\n */\ninclude($serendipity['serendipityPath'] . 'include/lang.inc.php');", "$serendipity['charsets'] = array(\n 'UTF-8/' => 'UTF-8',\n '' => CHARSET_NATIVE\n);", "@define('PATH_SMARTY_COMPILE', 'templates_c'); // will be placed inside the template directory\n@define('USERLEVEL_ADMIN', 255);\n@define('USERLEVEL_CHIEF', 1);\n@define('USERLEVEL_EDITOR', 0);", "@define('VIEWMODE_THREADED', 'threaded');\n@define('VIEWMODE_LINEAR', 'linear');", "if (!version_compare(phpversion(), '5.3', '>=')) {\n $serendipity['lang'] = 'en';\n include(S9Y_INCLUDE_PATH . 'include/lang.inc.php');\n serendipity_die(sprintf(SERENDIPITY_PHPVERSION_FAIL, phpversion(), '5.3'));\n}", "\n/*\n * Kill the script if we are not installed, and not inside the installer\n */\nif ( !defined('IN_installer') && IS_installed === false ) {\n header('Status: 302 Found');\n header('X-RequireInstall: 1');\n header('Location: ' . (strtolower($_SERVER['HTTPS']) == 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . str_replace('\\\\', '/', dirname($_SERVER['PHP_SELF'])) . '/serendipity_admin.php');\n serendipity_die(sprintf(SERENDIPITY_NOT_INSTALLED, 'serendipity_admin.php'));\n}", "/* Do the PEAR dance. If $serendipity['use_PEAR'] is set to FALSE, Serendipity will first put its own PEAR include path.\n By default, a local PEAR will be used. */\nif (function_exists('get_include_path')) {\n $old_include = @get_include_path();\n} else {\n $old_include = @ini_get('include_path');\n}", "\nrequire_once(\"bundled-libs/autoload.php\");", "$new_include = ($serendipity['use_PEAR'] ? $old_include . PATH_SEPARATOR : '')\n . S9Y_INCLUDE_PATH . 'bundled-libs/' . PATH_SEPARATOR\n . S9Y_INCLUDE_PATH . 'bundled-libs/Smarty/libs/' . PATH_SEPARATOR\n . $serendipity['serendipityPath'] . PATH_SEPARATOR\n . (!$serendipity['use_PEAR'] ? $old_include . PATH_SEPARATOR : '');", "if (function_exists('set_include_path')) {\n $use_include = @set_include_path($new_include);\n} else {\n $use_include = @ini_set('include_path', $new_include);\n}", "if ($use_include !== false && $use_include == $new_include) {\n @define('S9Y_PEAR', true);\n @define('S9Y_PEAR_PATH', '');\n} else {\n @define('S9Y_PEAR', false);\n @define('S9Y_PEAR_PATH', S9Y_INCLUDE_PATH . 'bundled-libs/');\n}\n/* PEAR path setup inclusion finished */", "if (defined('IN_installer') && IS_installed === false) {\n $serendipity['lang'] = $serendipity['autolang'];\n $css_mode = 'serendipity_admin.css';\n return 1;\n}", "/*\n * Load DB configuration information\n * Load Functions\n * Make sure that the file included is in the current directory and not any possible\n * include path\n */\nif (!defined('S9Y_DATA_PATH') && file_exists(dirname(__FILE__) . '/serendipity_config_local.inc.php')) {\n $local_config = dirname(__FILE__) . '/serendipity_config_local.inc.php';\n} elseif (@file_exists($_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/serendipity_config_local.inc.php')) {\n $local_config = $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/serendipity_config_local.inc.php';\n} elseif (defined('S9Y_DATA_PATH')) {\n // Shared installation!\n $local_config = S9Y_DATA_PATH . '/serendipity_config_local.inc.php';\n} elseif (@file_exists($serendipity['serendipityPath'] . '/serendipity_config_local.inc.php')) {\n $local_config = $serendipity['serendipityPath'] . '/serendipity_config_local.inc.php';\n} else {\n // Installation fallback\n $local_config = S9Y_INCLUDE_PATH . '/serendipity_config_local.inc.php';\n}", "if (!is_readable($local_config)) {\n $serendipity['lang'] = 'en';\n include(S9Y_INCLUDE_PATH . 'include/lang.inc.php');\n serendipity_die(sprintf(INCLUDE_ERROR . '<br />' . FILE_CREATE_YOURSELF, $local_config));\n}", "include($local_config);", "if ($serendipity['production'] === 'debug') {\n error_reporting(E_ALL &~E_NOTICE | E_STRICT);\n}", "//[internal callback function]: errorToExceptionHandler()\nif(is_callable($serendipity['errorhandler'], false, $callable_name)) {\n // set serendipity global error to exeption handler\n if ($serendipity['production'] === 'debug') {\n set_error_handler($serendipity['errorhandler'], error_reporting()); // Yes, DEBUG mode should actually report E_STRICT errors! In PHP 5.4s is contained in E_ALL already, but not in PHP 5.2.\n } else {\n // Caution! If we want to have the same noshow effect as upper set error_reporting(E_ALL) in 'debug' mode,\n // do not clone it to set_error_handler(E_ALL), else everythimg is haltet to debug, which makes using debug obsolet.\n set_error_handler($serendipity['errorhandler'], E_ALL & ~(E_NOTICE|E_STRICT));\n }\n}", "define('IS_up2date', version_compare($serendipity['version'], $serendipity['versionInstalled'], '<='));", "/*\n * Include main functions\n */\ninclude(S9Y_INCLUDE_PATH . 'include/functions.inc.php');", "if (serendipity_FUNCTIONS_LOADED !== true) {\n $serendipity['lang'] = 'en';\n include(S9Y_INCLUDE_PATH . 'include/lang.inc.php');\n serendipity_die(sprintf(INCLUDE_ERROR . '<br />' . FILE_CREATE_YOURSELF, 'include/functions.inc.php'));\n}", "/*\n * Attempt to connect to the database\n */\nif (!serendipity_db_connect()) {\n $serendipity['lang'] = 'en';\n include(S9Y_INCLUDE_PATH . 'include/lang.inc.php');\n if (is_object($serendipity['logger'])) $serendipity['logger']->critical(DATABASE_ERROR);\n serendipity_die(DATABASE_ERROR);\n}", "/*\n * Load Configuration options from the database\n */", "if (defined('USE_MEMSNAP')) {\n echo memSnap('Framework init');\n}", "serendipity_load_configuration();\n$serendipity['lang'] = serendipity_getSessionLanguage();", "serendipity_initLog();", "if (is_object($serendipity['logger'])) serendipity_logTimer('Logger Framework init');", "if ( (isset($serendipity['autodetect_baseURL']) && serendipity_db_bool($serendipity['autodetect_baseURL'])) ||\n (isset($serendipity['embed']) && serendipity_db_bool($serendipity['embed'])) ) {\n $serendipity['baseURL'] = 'http' . (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . (!strstr($_SERVER['HTTP_HOST'], ':') && !empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != '80' && $_SERVER['SERVER_PORT'] != '443' ? ':' . $_SERVER['SERVER_PORT'] : '') . $serendipity['serendipityHTTPPath'];\n}\n/*\n * If a user is logged in, fetch his preferences. He possibly wants to have a different language\n */", "if (IS_installed === true && php_sapi_name() !== 'cli') {\n // Import HTTP auth (mostly used for RSS feeds)\n if ($serendipity['useHTTP-Auth'] && (isset($_REQUEST['http_auth']) || isset($_SERVER['PHP_AUTH_USER']))) {\n if (!isset($_SERVER['PHP_AUTH_USER'])) {\n header(\"WWW-Authenticate: Basic realm=\\\"Feed Login\\\"\");\n header(\"HTTP/1.0 401 Unauthorized\");\n header(\"Status: 401 Unauthorized\");\n exit;\n } else {\n if (!isset($serendipity['POST']['user'])) {\n $serendipity['POST']['user'] = $_SERVER['PHP_AUTH_USER'];\n }\n if (!isset($serendipity['POST']['pass'])) {\n $serendipity['POST']['pass'] = $_SERVER['PHP_AUTH_PW'];\n }\n }\n } elseif (isset($_REQUEST['http_auth_user']) && isset($_REQUEST['http_auth_pw'])) {\n $serendipity['POST']['user'] = $_REQUEST['http_auth_user'];\n $serendipity['POST']['pass'] = $_REQUEST['http_auth_pw'];\n }", " serendipity_login(false);\n}", "if (isset($_SESSION['serendipityAuthorid'])) {\n serendipity_load_configuration($_SESSION['serendipityAuthorid']);\n $serendipity['lang'] = serendipity_getPostAuthSessionLanguage();\n}", "// Try to fix some path settings. It seems common users have this setting wrong\n// when s9y is installed into the root directory, especially 0.7.1 upgrade users.\nif (empty($serendipity['serendipityHTTPPath'])) {\n $serendipity['serendipityHTTPPath'] = '/';\n}", "/* Changing this is NOT recommended, rewrite rules does not take them into account - yet */\nserendipity_initPermalinks();", "// Apply constants/definitions from custom permalinks\nserendipity_permalinkPatterns();", "if (is_object($serendipity['logger'])) serendipity_logTimer('Permalinks init');", "/*\n * Load main language file again, because now we have the preferred language\n */\ninclude(S9Y_INCLUDE_PATH . 'include/lang.inc.php');", "if (is_object($serendipity['logger'])) serendipity_logTimer('Language init');\n/*\n * Reset charset definition now that final language is known\n */\n$serendipity['charsets'] = array(\n 'UTF-8/' => 'UTF-8',\n '' => CHARSET_NATIVE\n);", "/*\n * Set current locale, if any has been defined\n */\nif (defined('DATE_LOCALES')) {\n $locales = explode(',', DATE_LOCALES);\n foreach ($locales as $locale) {\n $locale = trim($locale);\n if (setlocale(LC_TIME, $locale) == $locale) {\n break;\n }\n }\n}\nif (function_exists('date_default_timezone_set')) {\n if(isset($serendipity['useServerOffset']) && $serendipity['useServerOffset']==false) {\n date_default_timezone_set('UTC');\n }\n}\n/*\n * Fallback charset, if none is defined in the language files\n */\n@define('LANG_CHARSET', 'ISO-8859-1');", "/*\n * Create array of permission levels, with descriptions\n */\n$serendipity['permissionLevels'] = array(USERLEVEL_EDITOR => USERLEVEL_EDITOR_DESC,\n USERLEVEL_CHIEF => USERLEVEL_CHIEF_DESC,\n USERLEVEL_ADMIN => USERLEVEL_ADMIN_DESC);", "// Redirect to the upgrader\nif (IS_up2date === false && !defined('IN_upgrader')) {\n if (preg_match(PAT_CSS, $_SERVER['REQUEST_URI'], $matches)) {\n $css_mode = 'serendipity_admin.css';\n return 1;\n }\n if (preg_match('@/(serendipity_editor\\.js$)@', $_SERVER['REQUEST_URI'], $matches)) {\n return 1;\n }\n serendipity_die(sprintf(SERENDIPITY_NEEDS_UPGRADE, $serendipity['versionInstalled'], $serendipity['version'], $serendipity['serendipityHTTPPath'] . 'serendipity_admin.php'));\n}", "// We don't care who tells us what to do\nif (!isset($serendipity['GET']['action'])) {\n $serendipity['GET']['action'] = (isset($serendipity['POST']['action']) ? $serendipity['POST']['action'] : '');\n}", "if (!isset($serendipity['GET']['adminAction'])) {\n $serendipity['GET']['adminAction'] = (isset($serendipity['POST']['adminAction']) ? $serendipity['POST']['adminAction'] : '');\n}", "// Make sure this variable is always properly sanitized. Previously in compat.inc.php, but there LANG_CHARSET was not defined.\nif (isset($serendipity['GET']['searchTerm'])) {\n $serendipity['GET']['searchTerm'] = serendipity_specialchars(strip_tags($serendipity['GET']['searchTerm']));\n}", "// Some stuff...\nif (!isset($_SESSION['serendipityAuthedUser'])) {\n $_SESSION['serendipityAuthedUser'] = false;\n}", "if (isset($_SESSION['serendipityUser'])) {\n $serendipity['user'] = $_SESSION['serendipityUser'];\n}", "if (isset($_SESSION['serendipityEmail'])) {\n $serendipity['email'] = $_SESSION['serendipityEmail'];\n}", "if (!isset($serendipity['use_autosave'])) {\n $serendipity['use_autosave'] = true;\n}", "// You can set parameters which ImageMagick should use to generate the thumbnails\n// by default, thumbs will get a little more brightness and saturation (modulate)\n// an unsharp-mask (unsharp)\n// and quality-compression of 75% (default would be to use quality of original image)\nif (!isset($serendipity['imagemagick_thumb_parameters'])) {\n $serendipity['imagemagick_thumb_parameters'] = '';\n // Set a variable like below in your serendpity_config_local.inc.php\n //$serendipity['imagemagick_thumb_parameters'] = '-modulate 105,140 -unsharp 0.5x0.5+1.0 -quality 75';\n}", "if (is_object($serendipity['logger'])) serendipity_logTimer('Core Framework finish');", "serendipity_plugin_api::hook_event('frontend_configure', $serendipity);\n/* vim: set sts=4 ts=4 expandtab : */" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [0, 477, 51, 78], "buggy_code_start_loc": [0, 228, 50, 57], "filenames": ["docs/NEWS", "include/admin/images.inc.php", "serendipity_config.inc.php", "templates/2k11/admin/category.inc.tpl"], "fixing_code_end_loc": [10, 480, 51, 78], "fixing_code_start_loc": [1, 228, 50, 57], "message": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:s9y:serendipity:*:*:*:*:*:*:*:*", "matchCriteriaId": "2B92E31B-BBE7-4C4B-9369-EBDD59B9D34D", "versionEndExcluding": null, "versionEndIncluding": "2.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code."}, {"lang": "es", "value": "En Serendipity en versiones anteriores a 2.0.5, un atacante puede eludir la protecci\u00f3n SSRF utilizando una direcci\u00f3n IP malformada (e.g., http://127.1) o un c\u00f3digo de estado HTTP 30x (tambi\u00e9n conocido como Redirection)."}], "evaluatorComment": null, "id": "CVE-2016-9752", "lastModified": "2016-12-03T03:27:52.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/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": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-12-01T11:59:11.120", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/94622"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://blog.s9y.org/archives/271-Serendipity-2.0.5-and-2.1-beta3-released.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}, "type": "CWE-918"}
229
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n# Copyright (c) 2003-2005, Jannis Hermanns (on behalf the Serendipity Developer Team)\n# All rights reserved. See LICENSE file for licensing details", "if (defined('S9Y_FRAMEWORK')) {\n return;\n}", "@define('S9Y_FRAMEWORK', true);\nif (!headers_sent() && php_sapi_name() !== 'cli') {\n // Only set the session name, if no session has yet been issued.\n if (session_id() == '') {\n $cookieParams = session_get_cookie_params();\n $cookieParams['secure'] = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? true : false);\n session_set_cookie_params($cookieParams['lifetime'], $cookieParams['path'], $cookieParams['domain'], $cookieParams['secure'], $cookieParams['httponly']);\n session_name('s9y_' . md5(dirname(__FILE__)));\n session_start();\n }", " // Prevent session fixation by only allowing sessions that have been sent by the server.\n // Any session that does not contain our unique token will be regarded as foreign/fixated\n // and be regenerated with a system-generated SID.\n // Patch by David Vieira-Kurz of majorsecurity.de\n if (!isset($_SESSION['SERVER_GENERATED_SID'])) {\n session_regenerate_id(true);\n @session_start();\n header('X-Session-Reinit: true');\n $_SESSION['SERVER_GENERATED_SID'] = $_SERVER['REMOTE_ADDR'] . $_SERVER['QUERY_STRING'];\n }\n}", "if (!defined('S9Y_INCLUDE_PATH')) {\n define('S9Y_INCLUDE_PATH', dirname(__FILE__) . '/');\n}\ndefine('S9Y_CONFIG_TEMPLATE', S9Y_INCLUDE_PATH . 'include/tpl/config_local.inc.php');\ndefine('S9Y_CONFIG_USERTEMPLATE', S9Y_INCLUDE_PATH . 'include/tpl/config_personal.inc.php');", "define('IS_installed', file_exists('serendipity_config_local.inc.php') && (filesize('serendipity_config_local.inc.php') > 0));", "if (!defined('IN_serendipity')) {\n define('IN_serendipity', true);\n}", "include(S9Y_INCLUDE_PATH . 'include/compat.inc.php');\nif (defined('USE_MEMSNAP')) {\n echo memSnap('Framework init');\n}", "// The version string", "$serendipity['version'] = '2.0.5';", "", "// Setting this to 'false' will enable debugging output. All alpha/beta/cvs snapshot versions will emit debug information by default. To increase the debug level (to enable Smarty debugging), set this flag to 'debug'.\nif (!isset($serendipity['production'])) {\n $serendipity['production'] = ! preg_match('@\\-(alpha|beta|cvs|rc).*@', $serendipity['version']);\n}", "// Set error reporting\n// TODO: E_STRICT throws problematic errors due to \"hook_event\" being a static function, but all of our plugins don't really define that...\nerror_reporting(E_ALL & ~(E_STRICT|E_NOTICE));", "if ($serendipity['production'] !== true) {\n @ini_set('display_errors', 'on');\n}", "\n// The serendipity errorhandler string\n$serendipity['errorhandler'] = 'errorToExceptionHandler';", "\n// Default rewrite method\n$serendipity['rewrite'] = 'none';", "// Message container\n$serendipity['messagestack'] = array();", "// Can the user change the date of publishing for an entry?\n$serendipity['allowDateManipulation'] = true;", "// How much time is allowed to pass since the publising of an entry, so that a comment to that entry\n// will update it's LastModified stamp? If the time is passed, a comment to an old entry will no longer\n// push an article as being updated.\n$serendipity['max_last_modified'] = 60 * 60 * 24 * 7;", "// Clients can send a If-Modified Header to the RSS Feed (Conditional Get) and receive all articles beyond\n// that date. However it is still limited by the number below of maximum entries\n$serendipity['max_fetch_limit'] = 50;", "// How many bytes are allowed for fetching trackbacks, so that no binary files get accidently trackbacked?\n$serendipity['trackback_filelimit'] = 150 * 1024;", "// Allow \"Access-Controll-Allow-Origin: *\" to be used in sensible locations (RSS feed)\n$serendipity['cors'] = false;", "if (!isset($serendipity['fetchLimit'])) {\n $serendipity['fetchLimit'] = 15;\n}", "if (!isset($serendipity['RSSfetchLimit'])) {\n $serendipity['RSSfetchLimit'] = 15;\n}", "if (!isset($serendipity['mediaProperties'])) {\n $serendipity['mediaProperties'] = 'DPI;COPYRIGHT;TITLE;COMMENT1:MULTI;COMMENT2:MULTI;ALT';\n}", "if (!isset($serendipity['use_PEAR'])) {\n $serendipity['use_PEAR'] = true;\n}", "if (!isset($serendipity['useHTTP-Auth'])) {\n $serendipity['useHTTP-Auth'] = true;\n}", "if (!isset($serendipity['CacheControl'])) {\n $serendipity['CacheControl'] = true;\n}", "if (!isset($serendipity['expose_s9y'])) {\n $serendipity['expose_s9y'] = true;\n}", "// Should IFRAMEs be used for previewing entries and sending trackbacks?\n$serendipity['use_iframe'] = true;", "/* Default language for autodetection */\n$serendipity['autolang'] = 'en';", "/* Name of folder for the default theme */\n$serendipity['defaultTemplate'] = '2k11';", "/* Default backend theme */\nif (!isset($serendipity['template_backend'])) {\n $serendipity['template_backend'] = '2k11';\n}", "/* Available languages */\nif (!isset($serendipity['languages'])) {\n $serendipity['languages'] = array('en' => 'English',\n 'de' => 'German',\n 'da' => 'Danish',\n 'es' => 'Spanish',\n 'fr' => 'French',\n 'fi' => 'Finnish',\n 'cs' => 'Czech (Win-1250)',\n 'cz' => 'Czech (ISO-8859-2)',\n 'sk' => 'Slovak',\n 'nl' => 'Dutch',\n 'is' => 'Icelandic',\n 'tr' => 'Turkish',\n 'se' => 'Swedish',\n 'pt' => 'Portuguese Brazilian',\n 'pt_PT' => 'Portuguese European',\n 'bg' => 'Bulgarian',\n 'hu' => 'Hungarian',\n 'no' => 'Norwegian',\n 'pl' => 'Polish',\n 'ro' => 'Romanian',\n 'it' => 'Italian',\n 'ru' => 'Russian',\n 'fa' => 'Persian',\n 'tw' => 'Traditional Chinese (Big5)',\n 'tn' => 'Traditional Chinese (UTF-8)',\n 'zh' => 'Simplified Chinese (GB2312)',\n 'cn' => 'Simplified Chinese (UTF-8)',\n 'ja' => 'Japanese',\n 'ko' => 'Korean',\n 'sa' => 'Arabic',\n 'ta' => 'Tamil');\n}", "/* Available Calendars */\n$serendipity['calendars'] = array('gregorian' => 'Gregorian',\n 'persian-utf8' => 'Persian (utf8)');\n/*\n * Load main language file\n */\ninclude($serendipity['serendipityPath'] . 'include/lang.inc.php');", "$serendipity['charsets'] = array(\n 'UTF-8/' => 'UTF-8',\n '' => CHARSET_NATIVE\n);", "@define('PATH_SMARTY_COMPILE', 'templates_c'); // will be placed inside the template directory\n@define('USERLEVEL_ADMIN', 255);\n@define('USERLEVEL_CHIEF', 1);\n@define('USERLEVEL_EDITOR', 0);", "@define('VIEWMODE_THREADED', 'threaded');\n@define('VIEWMODE_LINEAR', 'linear');", "if (!version_compare(phpversion(), '5.3', '>=')) {\n $serendipity['lang'] = 'en';\n include(S9Y_INCLUDE_PATH . 'include/lang.inc.php');\n serendipity_die(sprintf(SERENDIPITY_PHPVERSION_FAIL, phpversion(), '5.3'));\n}", "\n/*\n * Kill the script if we are not installed, and not inside the installer\n */\nif ( !defined('IN_installer') && IS_installed === false ) {\n header('Status: 302 Found');\n header('X-RequireInstall: 1');\n header('Location: ' . (strtolower($_SERVER['HTTPS']) == 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . str_replace('\\\\', '/', dirname($_SERVER['PHP_SELF'])) . '/serendipity_admin.php');\n serendipity_die(sprintf(SERENDIPITY_NOT_INSTALLED, 'serendipity_admin.php'));\n}", "/* Do the PEAR dance. If $serendipity['use_PEAR'] is set to FALSE, Serendipity will first put its own PEAR include path.\n By default, a local PEAR will be used. */\nif (function_exists('get_include_path')) {\n $old_include = @get_include_path();\n} else {\n $old_include = @ini_get('include_path');\n}", "\nrequire_once(\"bundled-libs/autoload.php\");", "$new_include = ($serendipity['use_PEAR'] ? $old_include . PATH_SEPARATOR : '')\n . S9Y_INCLUDE_PATH . 'bundled-libs/' . PATH_SEPARATOR\n . S9Y_INCLUDE_PATH . 'bundled-libs/Smarty/libs/' . PATH_SEPARATOR\n . $serendipity['serendipityPath'] . PATH_SEPARATOR\n . (!$serendipity['use_PEAR'] ? $old_include . PATH_SEPARATOR : '');", "if (function_exists('set_include_path')) {\n $use_include = @set_include_path($new_include);\n} else {\n $use_include = @ini_set('include_path', $new_include);\n}", "if ($use_include !== false && $use_include == $new_include) {\n @define('S9Y_PEAR', true);\n @define('S9Y_PEAR_PATH', '');\n} else {\n @define('S9Y_PEAR', false);\n @define('S9Y_PEAR_PATH', S9Y_INCLUDE_PATH . 'bundled-libs/');\n}\n/* PEAR path setup inclusion finished */", "if (defined('IN_installer') && IS_installed === false) {\n $serendipity['lang'] = $serendipity['autolang'];\n $css_mode = 'serendipity_admin.css';\n return 1;\n}", "/*\n * Load DB configuration information\n * Load Functions\n * Make sure that the file included is in the current directory and not any possible\n * include path\n */\nif (!defined('S9Y_DATA_PATH') && file_exists(dirname(__FILE__) . '/serendipity_config_local.inc.php')) {\n $local_config = dirname(__FILE__) . '/serendipity_config_local.inc.php';\n} elseif (@file_exists($_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/serendipity_config_local.inc.php')) {\n $local_config = $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/serendipity_config_local.inc.php';\n} elseif (defined('S9Y_DATA_PATH')) {\n // Shared installation!\n $local_config = S9Y_DATA_PATH . '/serendipity_config_local.inc.php';\n} elseif (@file_exists($serendipity['serendipityPath'] . '/serendipity_config_local.inc.php')) {\n $local_config = $serendipity['serendipityPath'] . '/serendipity_config_local.inc.php';\n} else {\n // Installation fallback\n $local_config = S9Y_INCLUDE_PATH . '/serendipity_config_local.inc.php';\n}", "if (!is_readable($local_config)) {\n $serendipity['lang'] = 'en';\n include(S9Y_INCLUDE_PATH . 'include/lang.inc.php');\n serendipity_die(sprintf(INCLUDE_ERROR . '<br />' . FILE_CREATE_YOURSELF, $local_config));\n}", "include($local_config);", "if ($serendipity['production'] === 'debug') {\n error_reporting(E_ALL &~E_NOTICE | E_STRICT);\n}", "//[internal callback function]: errorToExceptionHandler()\nif(is_callable($serendipity['errorhandler'], false, $callable_name)) {\n // set serendipity global error to exeption handler\n if ($serendipity['production'] === 'debug') {\n set_error_handler($serendipity['errorhandler'], error_reporting()); // Yes, DEBUG mode should actually report E_STRICT errors! In PHP 5.4s is contained in E_ALL already, but not in PHP 5.2.\n } else {\n // Caution! If we want to have the same noshow effect as upper set error_reporting(E_ALL) in 'debug' mode,\n // do not clone it to set_error_handler(E_ALL), else everythimg is haltet to debug, which makes using debug obsolet.\n set_error_handler($serendipity['errorhandler'], E_ALL & ~(E_NOTICE|E_STRICT));\n }\n}", "define('IS_up2date', version_compare($serendipity['version'], $serendipity['versionInstalled'], '<='));", "/*\n * Include main functions\n */\ninclude(S9Y_INCLUDE_PATH . 'include/functions.inc.php');", "if (serendipity_FUNCTIONS_LOADED !== true) {\n $serendipity['lang'] = 'en';\n include(S9Y_INCLUDE_PATH . 'include/lang.inc.php');\n serendipity_die(sprintf(INCLUDE_ERROR . '<br />' . FILE_CREATE_YOURSELF, 'include/functions.inc.php'));\n}", "/*\n * Attempt to connect to the database\n */\nif (!serendipity_db_connect()) {\n $serendipity['lang'] = 'en';\n include(S9Y_INCLUDE_PATH . 'include/lang.inc.php');\n if (is_object($serendipity['logger'])) $serendipity['logger']->critical(DATABASE_ERROR);\n serendipity_die(DATABASE_ERROR);\n}", "/*\n * Load Configuration options from the database\n */", "if (defined('USE_MEMSNAP')) {\n echo memSnap('Framework init');\n}", "serendipity_load_configuration();\n$serendipity['lang'] = serendipity_getSessionLanguage();", "serendipity_initLog();", "if (is_object($serendipity['logger'])) serendipity_logTimer('Logger Framework init');", "if ( (isset($serendipity['autodetect_baseURL']) && serendipity_db_bool($serendipity['autodetect_baseURL'])) ||\n (isset($serendipity['embed']) && serendipity_db_bool($serendipity['embed'])) ) {\n $serendipity['baseURL'] = 'http' . (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . (!strstr($_SERVER['HTTP_HOST'], ':') && !empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != '80' && $_SERVER['SERVER_PORT'] != '443' ? ':' . $_SERVER['SERVER_PORT'] : '') . $serendipity['serendipityHTTPPath'];\n}\n/*\n * If a user is logged in, fetch his preferences. He possibly wants to have a different language\n */", "if (IS_installed === true && php_sapi_name() !== 'cli') {\n // Import HTTP auth (mostly used for RSS feeds)\n if ($serendipity['useHTTP-Auth'] && (isset($_REQUEST['http_auth']) || isset($_SERVER['PHP_AUTH_USER']))) {\n if (!isset($_SERVER['PHP_AUTH_USER'])) {\n header(\"WWW-Authenticate: Basic realm=\\\"Feed Login\\\"\");\n header(\"HTTP/1.0 401 Unauthorized\");\n header(\"Status: 401 Unauthorized\");\n exit;\n } else {\n if (!isset($serendipity['POST']['user'])) {\n $serendipity['POST']['user'] = $_SERVER['PHP_AUTH_USER'];\n }\n if (!isset($serendipity['POST']['pass'])) {\n $serendipity['POST']['pass'] = $_SERVER['PHP_AUTH_PW'];\n }\n }\n } elseif (isset($_REQUEST['http_auth_user']) && isset($_REQUEST['http_auth_pw'])) {\n $serendipity['POST']['user'] = $_REQUEST['http_auth_user'];\n $serendipity['POST']['pass'] = $_REQUEST['http_auth_pw'];\n }", " serendipity_login(false);\n}", "if (isset($_SESSION['serendipityAuthorid'])) {\n serendipity_load_configuration($_SESSION['serendipityAuthorid']);\n $serendipity['lang'] = serendipity_getPostAuthSessionLanguage();\n}", "// Try to fix some path settings. It seems common users have this setting wrong\n// when s9y is installed into the root directory, especially 0.7.1 upgrade users.\nif (empty($serendipity['serendipityHTTPPath'])) {\n $serendipity['serendipityHTTPPath'] = '/';\n}", "/* Changing this is NOT recommended, rewrite rules does not take them into account - yet */\nserendipity_initPermalinks();", "// Apply constants/definitions from custom permalinks\nserendipity_permalinkPatterns();", "if (is_object($serendipity['logger'])) serendipity_logTimer('Permalinks init');", "/*\n * Load main language file again, because now we have the preferred language\n */\ninclude(S9Y_INCLUDE_PATH . 'include/lang.inc.php');", "if (is_object($serendipity['logger'])) serendipity_logTimer('Language init');\n/*\n * Reset charset definition now that final language is known\n */\n$serendipity['charsets'] = array(\n 'UTF-8/' => 'UTF-8',\n '' => CHARSET_NATIVE\n);", "/*\n * Set current locale, if any has been defined\n */\nif (defined('DATE_LOCALES')) {\n $locales = explode(',', DATE_LOCALES);\n foreach ($locales as $locale) {\n $locale = trim($locale);\n if (setlocale(LC_TIME, $locale) == $locale) {\n break;\n }\n }\n}\nif (function_exists('date_default_timezone_set')) {\n if(isset($serendipity['useServerOffset']) && $serendipity['useServerOffset']==false) {\n date_default_timezone_set('UTC');\n }\n}\n/*\n * Fallback charset, if none is defined in the language files\n */\n@define('LANG_CHARSET', 'ISO-8859-1');", "/*\n * Create array of permission levels, with descriptions\n */\n$serendipity['permissionLevels'] = array(USERLEVEL_EDITOR => USERLEVEL_EDITOR_DESC,\n USERLEVEL_CHIEF => USERLEVEL_CHIEF_DESC,\n USERLEVEL_ADMIN => USERLEVEL_ADMIN_DESC);", "// Redirect to the upgrader\nif (IS_up2date === false && !defined('IN_upgrader')) {\n if (preg_match(PAT_CSS, $_SERVER['REQUEST_URI'], $matches)) {\n $css_mode = 'serendipity_admin.css';\n return 1;\n }\n if (preg_match('@/(serendipity_editor\\.js$)@', $_SERVER['REQUEST_URI'], $matches)) {\n return 1;\n }\n serendipity_die(sprintf(SERENDIPITY_NEEDS_UPGRADE, $serendipity['versionInstalled'], $serendipity['version'], $serendipity['serendipityHTTPPath'] . 'serendipity_admin.php'));\n}", "// We don't care who tells us what to do\nif (!isset($serendipity['GET']['action'])) {\n $serendipity['GET']['action'] = (isset($serendipity['POST']['action']) ? $serendipity['POST']['action'] : '');\n}", "if (!isset($serendipity['GET']['adminAction'])) {\n $serendipity['GET']['adminAction'] = (isset($serendipity['POST']['adminAction']) ? $serendipity['POST']['adminAction'] : '');\n}", "// Make sure this variable is always properly sanitized. Previously in compat.inc.php, but there LANG_CHARSET was not defined.\nif (isset($serendipity['GET']['searchTerm'])) {\n $serendipity['GET']['searchTerm'] = serendipity_specialchars(strip_tags($serendipity['GET']['searchTerm']));\n}", "// Some stuff...\nif (!isset($_SESSION['serendipityAuthedUser'])) {\n $_SESSION['serendipityAuthedUser'] = false;\n}", "if (isset($_SESSION['serendipityUser'])) {\n $serendipity['user'] = $_SESSION['serendipityUser'];\n}", "if (isset($_SESSION['serendipityEmail'])) {\n $serendipity['email'] = $_SESSION['serendipityEmail'];\n}", "if (!isset($serendipity['use_autosave'])) {\n $serendipity['use_autosave'] = true;\n}", "// You can set parameters which ImageMagick should use to generate the thumbnails\n// by default, thumbs will get a little more brightness and saturation (modulate)\n// an unsharp-mask (unsharp)\n// and quality-compression of 75% (default would be to use quality of original image)\nif (!isset($serendipity['imagemagick_thumb_parameters'])) {\n $serendipity['imagemagick_thumb_parameters'] = '';\n // Set a variable like below in your serendpity_config_local.inc.php\n //$serendipity['imagemagick_thumb_parameters'] = '-modulate 105,140 -unsharp 0.5x0.5+1.0 -quality 75';\n}", "if (is_object($serendipity['logger'])) serendipity_logTimer('Core Framework finish');", "serendipity_plugin_api::hook_event('frontend_configure', $serendipity);\n/* vim: set sts=4 ts=4 expandtab : */" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [0, 477, 51, 78], "buggy_code_start_loc": [0, 228, 50, 57], "filenames": ["docs/NEWS", "include/admin/images.inc.php", "serendipity_config.inc.php", "templates/2k11/admin/category.inc.tpl"], "fixing_code_end_loc": [10, 480, 51, 78], "fixing_code_start_loc": [1, 228, 50, 57], "message": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:s9y:serendipity:*:*:*:*:*:*:*:*", "matchCriteriaId": "2B92E31B-BBE7-4C4B-9369-EBDD59B9D34D", "versionEndExcluding": null, "versionEndIncluding": "2.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code."}, {"lang": "es", "value": "En Serendipity en versiones anteriores a 2.0.5, un atacante puede eludir la protecci\u00f3n SSRF utilizando una direcci\u00f3n IP malformada (e.g., http://127.1) o un c\u00f3digo de estado HTTP 30x (tambi\u00e9n conocido como Redirection)."}], "evaluatorComment": null, "id": "CVE-2016-9752", "lastModified": "2016-12-03T03:27:52.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/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": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-12-01T11:59:11.120", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/94622"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://blog.s9y.org/archives/271-Serendipity-2.0.5-and-2.1-beta3-released.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}, "type": "CWE-918"}
229
Determine whether the {function_name} code is vulnerable or not.
[ "{if $post_save}\n {if $new}\n <span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> {$CONST.CATEGORY_SAVED}</span>\n {/if}\n {if $edit}\n {if isset($editPermission) && $editPermission == false}\n <span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> {$CONST.PERM_DENIED}</span>\n {else}\n {if $subcat}{$subcat}{else}\n <span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> {$CONST.CATEGORY_SAVED}</span>\n {/if}\n {/if}\n {/if}\n {if $error_name}\n <span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> {$CONST.CATEGORY_ALREADY_EXIST|sprintf:$category_name|escape}</span>\n {/if}\n{/if}\n{if $doDelete}\n {if $deleteSuccess}\n <span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> {if $remainingCat}{$CONST.CATEGORY_DELETED_ARTICLES_MOVED|sprintf:$remainingCat:$cid}{else}{$cid|string_format:\"{$CONST.CATEGORY_DELETED}\"}{/if}</span>\n {else}\n <span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> {$CONST.INVALID_CATEGORY}</span>\n {/if}\n{/if}\n{if $delete}\n {if $deletePermission == true}\n <h2>{$categoryName|escape}</h2>", " <form method=\"POST\" name=\"serendipityCategory\" action=\"?serendipity[adminModule]=category&amp;serendipity[adminAction]=doDelete&amp;serendipity[cid]={$cid}\">\n {$formToken}", " <div class=\"form_select\">\n <label for=\"remaining_cat\">{$CONST.CATEGORY_REMAINING}:</label>\n <select id=\"remaining_cat\" name=\"serendipity[cat][remaining_catid]\">\n <option value=\"0\">{$CONST.NO_CATEGORY}</option>\n {foreach $cats as $cat_data}\n <option value=\"{$cat_data.categoryid}\">{$cat_data.category_name|escape}</option>\n {/foreach}\n </select>\n </div>", " <input class=\"state_cancel\" name=\"REMOVE\" type=\"submit\" value=\"{$CONST.DELETE}\">\n </form>\n {/if}\n{/if}", "{if (! $post_save) && ($edit || $new)}\n {if $edit}\n <h2>{$category_name|escape|string_format:\"{$CONST.EDIT_THIS_CAT}\"}</h2>\n {/if}\n <form id=\"serendipity_category\" method=\"POST\" name=\"serendipityCategory\">\n {$formToken}", " <div id=\"category_basics\" class=\"clearfix\">\n <div class=\"form_field\">\n <label for=\"category_name\">{$CONST.NAME}</label>", " <input id=\"category_name\" pattern=\"{if $new}^(?!({foreach $categories as $cat}{$cat.category_name}|{/foreach})$).*{else}^(?!({foreach $categories as $cat}{if $this_cat.category_name != $cat.category_name}{$cat.category_name}{/if}|{/foreach})$).*{/if}\" name=\"serendipity[cat][name]\" type=\"text\" value=\"{$this_cat.category_name|default:\"\"|escape}\" title=\"Categoryname\">", " </div>", " <div class=\"form_field\">\n <label for=\"category_description\">{$CONST.DESCRIPTION}</label>\n <input id=\"category_description\" name=\"serendipity[cat][description]\" type=\"text\" value=\"{$this_cat.category_description|default:\"\"|escape}\">\n </div>\n </div>", " <h3 class=\"toggle_headline\">\n <button class=\"show_config_option icon_link {if $newSub}show_config_option_now{/if}\" type=\"button\" data-href=\"#category_subcats\" title=\"{$CONST.TOGGLE_OPTION}\"><span class=\"icon-right-dir\"></span> {$CONST.PARENT_CATEGORY}</button>\n </h3>", " <div id=\"category_subcats\" class=\"clearfix additional_info\">\n <div class=\"form_select\">\n <label for=\"parent_cat\">{$CONST.PARENT_CATEGORY}</label>\n <select id=\"parent_cat\" name=\"serendipity[cat][parent_cat]\">\n <option value=\"0\"{if $cid == 0} selected{/if}>{$CONST.NO_CATEGORY}</option>\n {foreach $categories as $cat}\n {if $cat.categoryid == $cid}{continue}{/if}", " <option value=\"{$cat.categoryid}\"{if $this_cat.parentid == $cat.categoryid} selected{/if}>{for $i=1 to $cat.depth}&nbsp{/for} {$cat.category_name}</option>", " {/foreach}\n </select>\n </div>", " <fieldset class=\"clearfix inputs\">\n <span class=\"wrap_legend\"><legend>{$CONST.CATEGORY_HIDE_SUB} <a class=\"toggle_info button_link\" href=\"#hide_subcats_info\"><span class=\"icon-info-circled\"></span><span class=\"visuallyhidden\"> More</span></a></legend></span>", " <span id=\"hide_subcats_info\" class=\"field_info additional_info\">{$CONST.CATEGORY_HIDE_SUB_DESC}</span>", " <div class=\"clearfix grouped\">\n <div class=\"form_radio\">\n <input id=\"hide_sub_yes\" name=\"serendipity[cat][hide_sub]\" type=\"radio\" value=\"1\"{if $this_cat.hide_sub== 1} checked=\"checked\"{/if}>\n <label for=\"hide_sub_yes\">{$CONST.YES}</label>\n </div>", " <div class=\"form_radio\">\n <input id=\"hide_sub_no\" name=\"serendipity[cat][hide_sub]\" type=\"radio\" value=\"0\"{if $this_cat.hide_sub == 0} checked=\"checked\"{/if}>\n <label for=\"hide_sub_no\">{$CONST.NO}</label>\n </div>\n </div>\n </fieldset>\n </div>", " <h3 class=\"toggle_headline\">\n <button class=\"show_config_option icon_link\" type=\"button\" data-href=\"#category_permissions\" title=\"{$CONST.TOGGLE_OPTION}\"><span class=\"icon-right-dir\"></span> {$CONST.PERMISSIONS}</button>\n </h3>", " <div id=\"category_permissions\" class=\"clearfix additional_info\">\n <div class=\"form_multiselect\">\n <label for=\"read_authors\">{$CONST.PERM_READ}</label>\n <select id=\"read_authors\" size=\"6\" multiple name=\"serendipity[cat][read_authors][]\">\n <option value=\"0\"{if $selectAllReadAuthors} selected{/if}>{$CONST.ALL_AUTHORS}</option>\n {foreach $groups as $group}\n <option value=\"{$group.confkey}\"{if isset($read_groups.{$group.confkey})} selected{/if} >{$group.confvalue|escape}</option>\n {/foreach}\n </select>\n </div>", " <div class=\"form_multiselect\">\n <label for=\"write_authors\">{$CONST.PERM_WRITE}</label>\n <select id=\"write_authors\" size=\"6\" multiple name=\"serendipity[cat][write_authors][]\">\n <option value=\"0\"{if $selectAllReadAuthors} selected{/if}>{$CONST.ALL_AUTHORS}</option>\n {foreach $groups as $group}\n <option value=\"{$group.confkey}\"{if isset($read_groups.{$group.confkey})} selected{/if}>{$group.confvalue|escape}</option>\n {/foreach}\n </select>\n </div>\n </div>", " <h3 class=\"toggle_headline\">\n <button class=\"show_config_option icon_link\" type=\"button\" data-href=\"#category_preview\" title=\"{$CONST.TOGGLE_OPTION}\"><span class=\"icon-right-dir\"></span> {$CONST.CATEGORY} {$CONST.IMAGE}</button>\n </h3>", " <div id=\"category_preview\" class=\"clearfix additional_info\">\n <div class=\"form_field\">\n <label for=\"category_icon\">{$CONST.CATEGORY} {$CONST.IMAGE}</label>", " <input id=\"category_icon\" class=\"change_preview\" name=\"serendipity[cat][icon]\" type=\"text\" data-configitem=\"category_icon\" value=\"{$this_cat.category_icon|default:\"\"|escape}\">", " <button class=\"choose_media\" type=\"button\" name=\"insImage\" title=\"{$CONST.MEDIA_LIBRARY}\"><span class=\"icon-picture\"></span><span class=\"visuallyhidden\"> {$CONST.MEDIA_LIBRARY}</span></button>\n </div>", " <figure id=\"category_icon_preview\">\n <figcaption>{$CONST.PREVIEW}</figcaption>\n <img src=\"{$this_cat.category_icon|default:\"\"|escape}\" alt=\"\">\n </figure>\n </div>", " {$category_showForm|default:''}", " <a class=\"button_link\" href=\"?serendipity[adminModule]=category&serendipity[adminAction]=view\">{$CONST.BACK}</a>\n <input class=\"standalone\" name=\"SAVE\" type=\"submit\" value=\"{$save}\">\n </form>\n{/if}\n{if $view}\n <h2>{$CONST.CATEGORIES}</h2>\n {if is_array($viewCats)}\n <ul id=\"categories\" class=\"option_list\">\n {foreach $viewCategories as $category}\n {if ! $category@first}\n {if $category.depth > $priorDepth}\n <ul>\n {/if}", " {if $category.depth < $priorDepth}\n </li>\n {for $i=$category.depth+1 to $priorDepth}\n </ul></li>\n {/for}\n {/if}", " {if $category.depth == $priorDepth}\n </li>\n {/if}\n {/if}", " {$priorDepth=$category.depth}\n \n <li>\n <div class=\"clearfix {cycle values=\"odd,even\"}\">\n <details class=\"category_data\">\n <summary>{$category.category_name|escape}</summary>", " <div class=\"category_info clearfix\">\n {if $category.category_description != ''}\n <span class=\"category_desc\">{$category.category_description|escape}</span>\n {/if}\n (<span>{if $category.authorid == 0}{$CONST.ALL_AUTHORS}{else}{$category.realname|escape}{/if}</span>)\n </div>\n </details>", " <ul class=\"plainList clearfix edit_actions\">\n <li><a class=\"button_link\" href=\"?serendipity[adminModule]=category&amp;serendipity[adminAction]=edit&amp;serendipity[cid]={$category.categoryid}\" title=\"{$CONST.EDIT} {$category.category_name|escape}\"><span class=\"icon-edit\"></span><span class=\"visuallyhidden\"> {$CONST.EDIT}</span></a></li>\n <li><a class=\"button_link\" href=\"?serendipity[adminModule]=category&amp;serendipity[adminAction]=newSub&amp;serendipity[cid]={$category.categoryid}\" title=\"{$CONST.CREATE_NEW_CAT}\"><span class=\"icon-plus\"></span><span class=\"visuallyhidden\"> {$CONST.CREATE_NEW_CAT}</span></a></li>\n <li><a class=\"button_link\" href=\"?serendipity[adminModule]=category&amp;serendipity[adminAction]=delete&amp;serendipity[cid]={$category.categoryid}\" title=\"{$CONST.DELETE} {$category.category_name|escape}\"><span class=\"icon-trash\"></span><span class=\"visuallyhidden\"> {$CONST.DELETE}</span></a></li>\n </ul>\n </div>\n {/foreach}\n </li>\n {for $i=1 to $priorDepth}\n </ul></li>\n {/for}\n </ul>\n {else}\n <span class=\"msg_notice\"><span class=\"icon-info-circled\"></span> {$CONST.NO_CATEGORIES}</span>\n {/if}\n <a class=\"button_link\" href=\"?serendipity[adminModule]=category&serendipity[adminAction]=new\">{$CONST.CREATE_NEW_CAT}</a>\n{/if}" ]
[ 1, 1, 1, 1, 1, 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 ]
PreciseBugs
{"buggy_code_end_loc": [0, 477, 51, 78], "buggy_code_start_loc": [0, 228, 50, 57], "filenames": ["docs/NEWS", "include/admin/images.inc.php", "serendipity_config.inc.php", "templates/2k11/admin/category.inc.tpl"], "fixing_code_end_loc": [10, 480, 51, 78], "fixing_code_start_loc": [1, 228, 50, 57], "message": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:s9y:serendipity:*:*:*:*:*:*:*:*", "matchCriteriaId": "2B92E31B-BBE7-4C4B-9369-EBDD59B9D34D", "versionEndExcluding": null, "versionEndIncluding": "2.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code."}, {"lang": "es", "value": "En Serendipity en versiones anteriores a 2.0.5, un atacante puede eludir la protecci\u00f3n SSRF utilizando una direcci\u00f3n IP malformada (e.g., http://127.1) o un c\u00f3digo de estado HTTP 30x (tambi\u00e9n conocido como Redirection)."}], "evaluatorComment": null, "id": "CVE-2016-9752", "lastModified": "2016-12-03T03:27:52.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/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": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-12-01T11:59:11.120", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/94622"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://blog.s9y.org/archives/271-Serendipity-2.0.5-and-2.1-beta3-released.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}, "type": "CWE-918"}
229
Determine whether the {function_name} code is vulnerable or not.
[ "{if $post_save}\n {if $new}\n <span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> {$CONST.CATEGORY_SAVED}</span>\n {/if}\n {if $edit}\n {if isset($editPermission) && $editPermission == false}\n <span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> {$CONST.PERM_DENIED}</span>\n {else}\n {if $subcat}{$subcat}{else}\n <span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> {$CONST.CATEGORY_SAVED}</span>\n {/if}\n {/if}\n {/if}\n {if $error_name}\n <span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> {$CONST.CATEGORY_ALREADY_EXIST|sprintf:$category_name|escape}</span>\n {/if}\n{/if}\n{if $doDelete}\n {if $deleteSuccess}\n <span class=\"msg_success\"><span class=\"icon-ok-circled\"></span> {if $remainingCat}{$CONST.CATEGORY_DELETED_ARTICLES_MOVED|sprintf:$remainingCat:$cid}{else}{$cid|string_format:\"{$CONST.CATEGORY_DELETED}\"}{/if}</span>\n {else}\n <span class=\"msg_error\"><span class=\"icon-attention-circled\"></span> {$CONST.INVALID_CATEGORY}</span>\n {/if}\n{/if}\n{if $delete}\n {if $deletePermission == true}\n <h2>{$categoryName|escape}</h2>", " <form method=\"POST\" name=\"serendipityCategory\" action=\"?serendipity[adminModule]=category&amp;serendipity[adminAction]=doDelete&amp;serendipity[cid]={$cid}\">\n {$formToken}", " <div class=\"form_select\">\n <label for=\"remaining_cat\">{$CONST.CATEGORY_REMAINING}:</label>\n <select id=\"remaining_cat\" name=\"serendipity[cat][remaining_catid]\">\n <option value=\"0\">{$CONST.NO_CATEGORY}</option>\n {foreach $cats as $cat_data}\n <option value=\"{$cat_data.categoryid}\">{$cat_data.category_name|escape}</option>\n {/foreach}\n </select>\n </div>", " <input class=\"state_cancel\" name=\"REMOVE\" type=\"submit\" value=\"{$CONST.DELETE}\">\n </form>\n {/if}\n{/if}", "{if (! $post_save) && ($edit || $new)}\n {if $edit}\n <h2>{$category_name|escape|string_format:\"{$CONST.EDIT_THIS_CAT}\"}</h2>\n {/if}\n <form id=\"serendipity_category\" method=\"POST\" name=\"serendipityCategory\">\n {$formToken}", " <div id=\"category_basics\" class=\"clearfix\">\n <div class=\"form_field\">\n <label for=\"category_name\">{$CONST.NAME}</label>", " <input id=\"category_name\" pattern=\"{if $new}^(?!({foreach $categories as $cat}{$cat.category_name|escape}|{/foreach})$).*{else}^(?!({foreach $categories as $cat}{if $this_cat.category_name != $cat.category_name}{$cat.category_name|escape}{/if}|{/foreach})$).*{/if}\" name=\"serendipity[cat][name]\" type=\"text\" value=\"{$this_cat.category_name|default:\"\"|escape}\" title=\"{$CONST.CATEGORY}\">", " </div>", " <div class=\"form_field\">\n <label for=\"category_description\">{$CONST.DESCRIPTION}</label>\n <input id=\"category_description\" name=\"serendipity[cat][description]\" type=\"text\" value=\"{$this_cat.category_description|default:\"\"|escape}\">\n </div>\n </div>", " <h3 class=\"toggle_headline\">\n <button class=\"show_config_option icon_link {if $newSub}show_config_option_now{/if}\" type=\"button\" data-href=\"#category_subcats\" title=\"{$CONST.TOGGLE_OPTION}\"><span class=\"icon-right-dir\"></span> {$CONST.PARENT_CATEGORY}</button>\n </h3>", " <div id=\"category_subcats\" class=\"clearfix additional_info\">\n <div class=\"form_select\">\n <label for=\"parent_cat\">{$CONST.PARENT_CATEGORY}</label>\n <select id=\"parent_cat\" name=\"serendipity[cat][parent_cat]\">\n <option value=\"0\"{if $cid == 0} selected{/if}>{$CONST.NO_CATEGORY}</option>\n {foreach $categories as $cat}\n {if $cat.categoryid == $cid}{continue}{/if}", " <option value=\"{$cat.categoryid}\"{if $this_cat.parentid == $cat.categoryid} selected{/if}>{for $i=1 to $cat.depth}&nbsp{/for} {$cat.category_name|escape}</option>", " {/foreach}\n </select>\n </div>", " <fieldset class=\"clearfix inputs\">\n <span class=\"wrap_legend\"><legend>{$CONST.CATEGORY_HIDE_SUB} <a class=\"toggle_info button_link\" href=\"#hide_subcats_info\"><span class=\"icon-info-circled\"></span><span class=\"visuallyhidden\"> More</span></a></legend></span>", " <span id=\"hide_subcats_info\" class=\"field_info additional_info\">{$CONST.CATEGORY_HIDE_SUB_DESC}</span>", " <div class=\"clearfix grouped\">\n <div class=\"form_radio\">\n <input id=\"hide_sub_yes\" name=\"serendipity[cat][hide_sub]\" type=\"radio\" value=\"1\"{if $this_cat.hide_sub== 1} checked=\"checked\"{/if}>\n <label for=\"hide_sub_yes\">{$CONST.YES}</label>\n </div>", " <div class=\"form_radio\">\n <input id=\"hide_sub_no\" name=\"serendipity[cat][hide_sub]\" type=\"radio\" value=\"0\"{if $this_cat.hide_sub == 0} checked=\"checked\"{/if}>\n <label for=\"hide_sub_no\">{$CONST.NO}</label>\n </div>\n </div>\n </fieldset>\n </div>", " <h3 class=\"toggle_headline\">\n <button class=\"show_config_option icon_link\" type=\"button\" data-href=\"#category_permissions\" title=\"{$CONST.TOGGLE_OPTION}\"><span class=\"icon-right-dir\"></span> {$CONST.PERMISSIONS}</button>\n </h3>", " <div id=\"category_permissions\" class=\"clearfix additional_info\">\n <div class=\"form_multiselect\">\n <label for=\"read_authors\">{$CONST.PERM_READ}</label>\n <select id=\"read_authors\" size=\"6\" multiple name=\"serendipity[cat][read_authors][]\">\n <option value=\"0\"{if $selectAllReadAuthors} selected{/if}>{$CONST.ALL_AUTHORS}</option>\n {foreach $groups as $group}\n <option value=\"{$group.confkey}\"{if isset($read_groups.{$group.confkey})} selected{/if} >{$group.confvalue|escape}</option>\n {/foreach}\n </select>\n </div>", " <div class=\"form_multiselect\">\n <label for=\"write_authors\">{$CONST.PERM_WRITE}</label>\n <select id=\"write_authors\" size=\"6\" multiple name=\"serendipity[cat][write_authors][]\">\n <option value=\"0\"{if $selectAllReadAuthors} selected{/if}>{$CONST.ALL_AUTHORS}</option>\n {foreach $groups as $group}\n <option value=\"{$group.confkey}\"{if isset($read_groups.{$group.confkey})} selected{/if}>{$group.confvalue|escape}</option>\n {/foreach}\n </select>\n </div>\n </div>", " <h3 class=\"toggle_headline\">\n <button class=\"show_config_option icon_link\" type=\"button\" data-href=\"#category_preview\" title=\"{$CONST.TOGGLE_OPTION}\"><span class=\"icon-right-dir\"></span> {$CONST.CATEGORY} {$CONST.IMAGE}</button>\n </h3>", " <div id=\"category_preview\" class=\"clearfix additional_info\">\n <div class=\"form_field\">\n <label for=\"category_icon\">{$CONST.CATEGORY} {$CONST.IMAGE}</label>", " <input id=\"category_icon\" class=\"change_preview\" name=\"serendipity[cat][icon]\" type=\"text\" data-configitem=\"category_icon\" value=\"{$this_cat.category_icon|default:\"\"|escape}\">", " <button class=\"choose_media\" type=\"button\" name=\"insImage\" title=\"{$CONST.MEDIA_LIBRARY}\"><span class=\"icon-picture\"></span><span class=\"visuallyhidden\"> {$CONST.MEDIA_LIBRARY}</span></button>\n </div>", " <figure id=\"category_icon_preview\">\n <figcaption>{$CONST.PREVIEW}</figcaption>\n <img src=\"{$this_cat.category_icon|default:\"\"|escape}\" alt=\"\">\n </figure>\n </div>", " {$category_showForm|default:''}", " <a class=\"button_link\" href=\"?serendipity[adminModule]=category&serendipity[adminAction]=view\">{$CONST.BACK}</a>\n <input class=\"standalone\" name=\"SAVE\" type=\"submit\" value=\"{$save}\">\n </form>\n{/if}\n{if $view}\n <h2>{$CONST.CATEGORIES}</h2>\n {if is_array($viewCats)}\n <ul id=\"categories\" class=\"option_list\">\n {foreach $viewCategories as $category}\n {if ! $category@first}\n {if $category.depth > $priorDepth}\n <ul>\n {/if}", " {if $category.depth < $priorDepth}\n </li>\n {for $i=$category.depth+1 to $priorDepth}\n </ul></li>\n {/for}\n {/if}", " {if $category.depth == $priorDepth}\n </li>\n {/if}\n {/if}", " {$priorDepth=$category.depth}\n \n <li>\n <div class=\"clearfix {cycle values=\"odd,even\"}\">\n <details class=\"category_data\">\n <summary>{$category.category_name|escape}</summary>", " <div class=\"category_info clearfix\">\n {if $category.category_description != ''}\n <span class=\"category_desc\">{$category.category_description|escape}</span>\n {/if}\n (<span>{if $category.authorid == 0}{$CONST.ALL_AUTHORS}{else}{$category.realname|escape}{/if}</span>)\n </div>\n </details>", " <ul class=\"plainList clearfix edit_actions\">\n <li><a class=\"button_link\" href=\"?serendipity[adminModule]=category&amp;serendipity[adminAction]=edit&amp;serendipity[cid]={$category.categoryid}\" title=\"{$CONST.EDIT} {$category.category_name|escape}\"><span class=\"icon-edit\"></span><span class=\"visuallyhidden\"> {$CONST.EDIT}</span></a></li>\n <li><a class=\"button_link\" href=\"?serendipity[adminModule]=category&amp;serendipity[adminAction]=newSub&amp;serendipity[cid]={$category.categoryid}\" title=\"{$CONST.CREATE_NEW_CAT}\"><span class=\"icon-plus\"></span><span class=\"visuallyhidden\"> {$CONST.CREATE_NEW_CAT}</span></a></li>\n <li><a class=\"button_link\" href=\"?serendipity[adminModule]=category&amp;serendipity[adminAction]=delete&amp;serendipity[cid]={$category.categoryid}\" title=\"{$CONST.DELETE} {$category.category_name|escape}\"><span class=\"icon-trash\"></span><span class=\"visuallyhidden\"> {$CONST.DELETE}</span></a></li>\n </ul>\n </div>\n {/foreach}\n </li>\n {for $i=1 to $priorDepth}\n </ul></li>\n {/for}\n </ul>\n {else}\n <span class=\"msg_notice\"><span class=\"icon-info-circled\"></span> {$CONST.NO_CATEGORIES}</span>\n {/if}\n <a class=\"button_link\" href=\"?serendipity[adminModule]=category&serendipity[adminAction]=new\">{$CONST.CREATE_NEW_CAT}</a>\n{/if}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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": [0, 477, 51, 78], "buggy_code_start_loc": [0, 228, 50, 57], "filenames": ["docs/NEWS", "include/admin/images.inc.php", "serendipity_config.inc.php", "templates/2k11/admin/category.inc.tpl"], "fixing_code_end_loc": [10, 480, 51, 78], "fixing_code_start_loc": [1, 228, 50, 57], "message": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:s9y:serendipity:*:*:*:*:*:*:*:*", "matchCriteriaId": "2B92E31B-BBE7-4C4B-9369-EBDD59B9D34D", "versionEndExcluding": null, "versionEndIncluding": "2.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Serendipity before 2.0.5, an attacker can bypass SSRF protection by using a malformed IP address (e.g., http://127.1) or a 30x (aka Redirection) HTTP status code."}, {"lang": "es", "value": "En Serendipity en versiones anteriores a 2.0.5, un atacante puede eludir la protecci\u00f3n SSRF utilizando una direcci\u00f3n IP malformada (e.g., http://127.1) o un c\u00f3digo de estado HTTP 30x (tambi\u00e9n conocido como Redirection)."}], "evaluatorComment": null, "id": "CVE-2016-9752", "lastModified": "2016-12-03T03:27:52.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/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": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-12-01T11:59:11.120", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/94622"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://blog.s9y.org/archives/271-Serendipity-2.0.5-and-2.1-beta3-released.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/s9y/Serendipity/commit/fbdd50a448ed87ba34ea8c56446b8f1873eadd6f"}, "type": "CWE-918"}
229
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at", " http://www.apache.org/licenses/LICENSE-2.0", "Unless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/", "// See docs in ../ops/data_flow_ops.cc.", "#define EIGEN_USE_THREADS", "#include <limits>\n#include <vector>\n// TODO(b/31496047): Fix non-standard include order.\n#include <numeric> // clang-format off", "#include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n#include \"tensorflow/core/framework/bounds_check.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/resource_mgr.h\"\n#include \"tensorflow/core/framework/tensor.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/tensor_util.h\"\n#include \"tensorflow/core/framework/types.h\"\n#include \"tensorflow/core/kernels/concat_lib.h\"\n#include \"tensorflow/core/kernels/split_lib.h\"\n#include \"tensorflow/core/kernels/tensor_array.h\"\n#include \"tensorflow/core/lib/core/errors.h\"\n#include \"tensorflow/core/lib/core/refcount.h\"\n#include \"tensorflow/core/lib/strings/strcat.h\"\n#include \"tensorflow/core/platform/dynamic_annotations.h\"\n#include \"tensorflow/core/platform/logging.h\"\n#include \"tensorflow/core/platform/thread_annotations.h\"\n#include \"tensorflow/core/platform/types.h\"\n#include \"tensorflow/core/util/ptr_util.h\"", "typedef Eigen::ThreadPoolDevice CPUDevice;\n#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM\ntypedef Eigen::GpuDevice GPUDevice;\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// clang-format on", "namespace tensorflow {", "Status GetHandle(OpKernelContext* ctx, string* container, string* ta_handle) {\n {\n Tensor tensor;\n // Assuming that handle is the input at index 0.\n if (IsRefType(ctx->input_dtype(0))) {\n tensor = ctx->mutable_input(0, false);\n } else {\n tensor = ctx->input(0);\n }\n if (tensor.NumElements() != 2) {\n return errors::InvalidArgument(\n \"Tensor array handle must be 2-element vector, but had shape: \",\n tensor.shape().DebugString());\n }\n auto h = tensor.flat<tstring>();\n *container = h(0);\n *ta_handle = h(1);\n }\n return OkStatus();\n}", "Status GetTensorArray(OpKernelContext* ctx, TensorArray** tensor_array) {\n string container;\n string ta_handle;\n if (ctx->input_dtype(0) != DT_RESOURCE) {\n TF_RETURN_IF_ERROR(GetHandle(ctx, &container, &ta_handle));\n ResourceMgr* rm = ctx->resource_manager();\n if (rm == nullptr) return errors::Internal(\"No resource manager.\");", " TF_RETURN_IF_ERROR(\n ctx->step_container()->Lookup(rm, container + ta_handle, tensor_array));", " return OkStatus();\n } else {\n return LookupResource(ctx, HandleFromInput(ctx, 0), tensor_array);\n }\n}", "Status SetupFlowControlInputs(OpKernelContext* ctx, bool set_output) {\n const Tensor* flow_control;\n TF_RETURN_IF_ERROR(ctx->input(\"flow_in\", &flow_control));\n if (set_output) {\n TF_RETURN_IF_ERROR(ctx->set_output(\"flow_out\", *flow_control));\n }\n return OkStatus();\n}", "// CREATION *******************************************************************", "// Virtual class for shared behavior between TensorArrayOp and\n// TensorArrayGradOp.\nclass TensorArrayCreationOp : public OpKernel {\n public:\n explicit TensorArrayCreationOp(OpKernelConstruction* context)\n : OpKernel(context), device_type_(context->device_type()) {}", " void Compute(OpKernelContext* ctx) override {\n Tensor tensor_array_output_handle;", " AllocatorAttributes alloc_attr;\n alloc_attr.set_on_host(true);\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(\n tensorflow::DT_STRING, tensorflow::TensorShape({2}),\n &tensor_array_output_handle, alloc_attr));\n // Store the handle in a per-step container of the RM.\n ResourceMgr* rm = ctx->resource_manager();\n OP_REQUIRES(ctx, rm != nullptr, errors::Internal(\"No resource manager.\"));", " TensorArray* output_tensor_array;\n OP_REQUIRES_OK(ctx, CreateTensorArray(ctx, rm, &tensor_array_output_handle,\n &output_tensor_array));\n if (IsRefType(ctx->expected_output_dtype(0))) {\n ctx->set_output_ref(0, output_tensor_array->mu(),\n output_tensor_array->handle());\n } else if (ctx->expected_output_dtype(0) == DT_STRING) {\n ctx->set_output(0, *output_tensor_array->handle());\n } else {\n Tensor* handle;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));\n handle->flat<ResourceHandle>()(0) =\n output_tensor_array->resource_handle(ctx);\n }\n if (ctx->num_outputs() == 2) {\n // Create the flow output.\n Tensor* flow;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &flow));\n if (device_type_ == DEVICE_CPU) {\n // Value doesn't matter, but this makes msan not complaint about\n // copying an uninitialized value. To do this on GPU would require\n // a kernel launch or a host->device memcpy, so we avoid that.\n flow->flat<float>()(0) = 0;\n }\n }\n }", " protected:\n virtual Status CreateTensorArray(OpKernelContext* ctx, ResourceMgr* rm,\n Tensor* tensor_array_output_handle,\n TensorArray** output_tensor_array) = 0;", " private:\n const DeviceType device_type_;\n};", "// A per-run local tensor array. The tensor array uses a \"per-step\" resource\n// manager which ensures that correct garbage collection on error or\n// successful completion.\nclass TensorArrayOp : public TensorArrayCreationOp {\n public:\n explicit TensorArrayOp(OpKernelConstruction* context)\n : TensorArrayCreationOp(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"dtype\", &dtype_));\n OP_REQUIRES_OK(context, context->GetAttr(\"element_shape\", &element_shape_));\n OP_REQUIRES_OK(context, context->GetAttr(\"dynamic_size\", &dynamic_size_));\n // The HasAttr check is for backwards compatibility with older op\n // versions which do not have this attribute.\n if (context->HasAttr(\"identical_element_shapes\")) {\n OP_REQUIRES_OK(context, context->GetAttr(\"identical_element_shapes\",\n &identical_element_shapes_));\n } else {\n identical_element_shapes_ = false;\n }\n OP_REQUIRES_OK(context,\n context->GetAttr(\"clear_after_read\", &clear_after_read_));\n OP_REQUIRES_OK(context,\n context->GetAttr(\"tensor_array_name\", &tensor_array_name_));\n if (tensor_array_name_.empty()) tensor_array_name_ = name();\n }", " Status CreateTensorArray(OpKernelContext* ctx, ResourceMgr* rm,\n Tensor* tensor_array_output_handle,\n TensorArray** output_tensor_array) override {\n const Tensor* tensor_size;\n TF_RETURN_IF_ERROR(ctx->input(\"size\", &tensor_size));", " if (!TensorShapeUtils::IsScalar(tensor_size->shape())) {\n return errors::InvalidArgument(\n \"TensorArray size must be scalar, but had shape: \",\n tensor_size->shape().DebugString());\n }\n const int32_t size = tensor_size->scalar<int32>()();\n if (size < 0) {\n return errors::InvalidArgument(\"Size should be >= 0.\");\n }", " auto handle = tensor_array_output_handle->flat<tstring>();\n string unique_tensor_array_name =\n strings::StrCat(tensor_array_name_, \"_\",\n TensorArray::tensor_array_counter.fetch_add(1));\n handle(0) = \"_tensor_arrays\";\n handle(1) = unique_tensor_array_name;", " auto key = strings::StrCat(handle(0), unique_tensor_array_name);", " TensorArray* tensor_array = new TensorArray(\n key, dtype_, *tensor_array_output_handle, size, element_shape_,\n identical_element_shapes_, dynamic_size_,\n false /* multiple_writes_aggregate */, false /* is_grad */,\n -1 /* marked_size */, clear_after_read_);", " TF_RETURN_IF_ERROR(ctx->step_container()->Create(rm, key, tensor_array));", " *output_tensor_array = tensor_array;", " return OkStatus();\n }", " private:\n DataType dtype_;\n PartialTensorShape element_shape_;\n bool identical_element_shapes_;\n bool dynamic_size_;\n bool clear_after_read_;\n string tensor_array_name_; // The name used to create the TensorArray.", " TF_DISALLOW_COPY_AND_ASSIGN(TensorArrayOp);\n};", "REGISTER_KERNEL_BUILDER(Name(\"TensorArray\").Device(DEVICE_CPU), TensorArrayOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayV2\").Device(DEVICE_CPU),\n TensorArrayOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayV3\").Device(DEVICE_CPU),\n TensorArrayOp);", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArray\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"size\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayOp); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"size\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayOp); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"size\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayOp);", "TF_CALL_int64(REGISTER_GPU);\nTF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// GRADIENT *******************************************************************\n// Note that this op may have an optional third input. If present, it represents\n// a shape value. It indicates that element shape of this gradient array is that\n// shape value concatenated with the element shape of the original tensor array.\n// See TensorArrayGradWithShape.\nclass TensorArrayGradOp : public TensorArrayCreationOp {\n public:\n explicit TensorArrayGradOp(OpKernelConstruction* context)\n : TensorArrayCreationOp(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"source\", &source_));\n }", " Status CreateTensorArray(OpKernelContext* ctx, ResourceMgr* rm,\n Tensor* tensor_array_output_handle,\n TensorArray** output_tensor_array) override {\n string container;\n string tensor_array_name;\n if (ctx->input_dtype(0) != DT_RESOURCE) {\n TF_RETURN_IF_ERROR(GetHandle(ctx, &container, &tensor_array_name));\n if (container != \"_tensor_arrays\") {\n return errors::InvalidArgument(\n \"Input container should be '_tensor_arrays', but received '\",\n container, \"'\");\n }\n } else {\n container = \"_tensor_arrays\";\n const auto& resource = ctx->input(0).flat<ResourceHandle>()(0);\n if (StringPiece(resource.name()).substr(0, container.size()) !=\n container) {\n return errors::InvalidArgument(\"Wrong input container. \",\n resource.name());\n }\n tensor_array_name =\n string(StringPiece(resource.name()).substr(container.size()));\n }", " auto output_handle = tensor_array_output_handle->flat<tstring>();\n output_handle(0) = \"_tensor_array_grads\";\n output_handle(1) = strings::StrCat(tensor_array_name, \"@\", source_);", " TensorArray* tensor_array;\n TF_RETURN_IF_ERROR(ctx->step_container()->Lookup(\n rm, strings::StrCat(container, tensor_array_name), &tensor_array));\n core::ScopedUnref unref(tensor_array);", " // Once gradients are being calculated, the forward TensorArray\n // may no longer be resized by new Writes.\n tensor_array->DisableDynamicSize();", " int32_t array_size = 0;\n int32_t marked_size = 0;\n TF_RETURN_IF_ERROR(tensor_array->Size(&array_size));\n TF_RETURN_IF_ERROR(tensor_array->MarkedSize(&marked_size));", " if (array_size < 0) {\n return errors::InvalidArgument(\"ArraySize should be >= 0.\");\n }\n if (!tensor_array->GradientsAllowed()) {\n return errors::InvalidArgument(\n \"Unable to create a gradients TensorArray for \", tensor_array_name,\n \". Perhaps you used the multiple_writes_aggregate flag on a \"\n \"previous write? Gradient calculation is impossible when multiple \"\n \"writes are performed to the same index.\");\n }\n TensorShape shape_to_prepend;\n auto element_shape = PartialTensorShape();\n if (ctx->num_inputs() > 2) {\n TF_RETURN_IF_ERROR(tensor::MakeShape(ctx->input(2), &shape_to_prepend));\n auto ta_element_shape = tensor_array->ElemShape();\n if (!ta_element_shape.unknown_rank()) {\n std::vector<int64_t> dims;\n for (auto dim : shape_to_prepend) {\n dims.push_back(dim.size);\n }\n for (auto dim : ta_element_shape) {\n dims.push_back(dim.size);\n }\n TF_RETURN_IF_ERROR(TensorShapeUtils::MakeShape(\n gtl::ArraySlice<int64_t>(dims), &element_shape));\n }\n } else {\n element_shape = tensor_array->ElemShape();\n }", " const auto key = strings::StrCat(output_handle(0), output_handle(1));\n auto creator = [key, tensor_array, array_size, marked_size, element_shape,\n shape_to_prepend,\n tensor_array_output_handle](TensorArray** ret) -> Status {\n *ret = new TensorArray(\n key, tensor_array->ElemType(), *tensor_array_output_handle,\n array_size, element_shape, tensor_array->HasIdenticalElementShapes(),\n false /* dynamic_size */, true /* multiple_writes_aggregate */,\n true /* is_grad */, marked_size /* marked_size */,\n true /* close_after_read */);\n return (*ret)->CopyShapesFrom(tensor_array, &shape_to_prepend);\n };", " Status s = ctx->step_container()->LookupOrCreate<TensorArray>(\n rm, key, output_tensor_array, creator);\n (*output_tensor_array)->Unref();", " return s;\n }", " private:\n // The gradient source for creating the given\n // gradient TensorArray. This should be unique to each gradients\n // call. Typical values look like \"gradients\", \"gradients_1\", ...\n string source_;", " TF_DISALLOW_COPY_AND_ASSIGN(TensorArrayGradOp);\n};", "REGISTER_KERNEL_BUILDER(Name(\"TensorArrayGrad\").Device(DEVICE_CPU),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradV2\").Device(DEVICE_CPU),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradV3\").Device(DEVICE_CPU),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradWithShape\").Device(DEVICE_CPU),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGrad\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"grad_handle\"),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradV2\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"grad_handle\"),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradV3\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"grad_handle\"),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradWithShape\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"shape_to_prepend\")\n .HostMemory(\"grad_handle\"),\n TensorArrayGradOp);", "// WRITE **********************************************************************", "template <typename Device, typename T>\nclass TensorArrayWriteOp : public OpKernel {\n public:\n explicit TensorArrayWriteOp(OpKernelConstruction* context)\n : OpKernel(context) {}", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, true));", " const Tensor* tensor_index;\n const Tensor* tensor_value;\n OP_REQUIRES_OK(ctx, ctx->input(\"index\", &tensor_index));\n OP_REQUIRES_OK(ctx, ctx->input(\"value\", &tensor_value));", " OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(tensor_index->shape()),\n errors::InvalidArgument(\n \"TensorArray index must be scalar, but had shape: \",\n tensor_index->shape().DebugString()));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n const int32_t index = tensor_index->scalar<int32>()();\n OP_REQUIRES(\n ctx, tensor_value->dtype() == tensor_array->ElemType(),\n errors::InvalidArgument(\"TensorArray dtype is \",\n DataTypeString(tensor_array->ElemType()),\n \" but Op is trying to write dtype \",\n DataTypeString(tensor_value->dtype()), \".\"));\n Status s =\n tensor_array->WriteOrAggregate<Device, T>(ctx, index, tensor_value);\n OP_REQUIRES_OK(ctx, s);\n }\n};", "#define REGISTER_WRITE(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayWrite\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArrayWriteOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayWriteV2\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArrayWriteOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayWriteV3\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArrayWriteOp<CPUDevice, type>);", "TF_CALL_ALL_TYPES(REGISTER_WRITE);", "#undef REGISTER_WRITE", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayWrite\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayWriteOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayWriteV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayWriteOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayWriteV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayWriteOp<GPUDevice, type>);", "TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// READ ***********************************************************************", "template <typename Device, typename T>\nclass TensorArrayReadOp : public OpKernel {\n public:\n explicit TensorArrayReadOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"dtype\", &dtype_));\n }", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, false));", " const Tensor* tensor_index;\n OP_REQUIRES_OK(ctx, ctx->input(\"index\", &tensor_index));", " OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(tensor_index->shape()),\n errors::InvalidArgument(\n \"TensorArray index must be scalar, but had shape: \",\n tensor_index->shape().DebugString()));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);", " const int32_t index = tensor_index->scalar<int32>()();\n OP_REQUIRES(\n ctx, dtype_ == tensor_array->ElemType(),\n errors::InvalidArgument(\n \"TensorArray dtype is \", DataTypeString(tensor_array->ElemType()),\n \" but Op requested dtype \", DataTypeString(dtype_), \".\"));\n Tensor value;\n Status s = tensor_array->Read<Device, T>(ctx, index, &value);\n OP_REQUIRES_OK(ctx, s);\n ctx->set_output(0, value);\n }", " private:\n DataType dtype_;\n};", "#define REGISTER_READ(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayRead\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayReadOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayReadV2\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayReadOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayReadV3\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayReadOp<CPUDevice, type>);", "TF_CALL_ALL_TYPES(REGISTER_READ)", "#undef REGISTER_READ", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayRead\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayReadOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayReadV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayReadOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayReadV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayReadOp<GPUDevice, type>);", "TF_CALL_int64(REGISTER_GPU);\nTF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// PACK and GATHER ************************************************************", "// Concatenate the elements in a TensorArray. All elements must be\n// defined and have the same shape.\ntemplate <typename Device, typename T, bool LEGACY_PACK>\nclass TensorArrayPackOrGatherOp : public OpKernel {\n public:\n typedef typename TTypes<T, 2>::ConstMatrix ConstMatrix;\n typedef std::vector<std::unique_ptr<ConstMatrix> > ConstMatrixVector;", " explicit TensorArrayPackOrGatherOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"dtype\", &dtype_));\n OP_REQUIRES_OK(context, context->GetAttr(\"element_shape\", &element_shape_));\n }", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, false));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));", " core::ScopedUnref unref(tensor_array);\n OP_REQUIRES(\n ctx, dtype_ == tensor_array->ElemType(),\n errors::InvalidArgument(\n \"TensorArray dtype is \", DataTypeString(tensor_array->ElemType()),\n \" but Op requested dtype \", DataTypeString(dtype_), \".\"));", " // Ensure new element shape is compatible with the one stored in the\n // TensorArray.\n OP_REQUIRES_OK(ctx, tensor_array->SetElemShape(element_shape_));", " int32_t num_indices;\n std::vector<Tensor> values;\n std::vector<int32> indices;\n if (LEGACY_PACK) {\n OP_REQUIRES_OK(ctx, tensor_array->PackOrConcatSize(&num_indices));\n indices.resize(num_indices);\n std::iota(indices.begin(), indices.end(), 0);\n } else {\n const Tensor* tensor_indices;\n OP_REQUIRES_OK(ctx, ctx->input(\"indices\", &tensor_indices));\n OP_REQUIRES(ctx, TensorShapeUtils::IsVector(tensor_indices->shape()),\n errors::InvalidArgument(\n \"Expected indices to be a vector, but received shape: \",\n tensor_indices->shape().DebugString()));\n const auto indices_t = tensor_indices->vec<int32>();\n num_indices = tensor_indices->NumElements();\n indices.resize(num_indices);\n std::copy(indices_t.data(), indices_t.data() + num_indices,\n indices.begin());\n }", " // If there are no elements to return, return a zero-element Tensor with\n // shape [0] + element_shape_\n if (num_indices == 0) {\n OP_REQUIRES(ctx, element_shape_.IsFullyDefined(),\n errors::Unimplemented(\n \"TensorArray has size zero, but element shape \",\n element_shape_.DebugString(),\n \" is not fully defined. \"\n \"Currently only static shapes are supported when packing \"\n \"zero-size TensorArrays.\"));\n TensorShape empty_shape;\n element_shape_.AsTensorShape(&empty_shape);\n empty_shape.InsertDim(0, 0);\n Tensor* empty_unused;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, empty_shape, &empty_unused));\n return;\n }", " // Read all the Tensors into a vector to keep track of their memory.\n Status s = tensor_array->ReadMany<Device, T>(ctx, indices, &values);\n OP_REQUIRES_OK(ctx, s);", " const Tensor* value_0_t = &values[0];", " OP_REQUIRES(\n ctx, element_shape_.IsCompatibleWith(value_0_t->shape()),\n errors::InvalidArgument(\"TensorArray was passed element_shape \",\n element_shape_.DebugString(),\n \" which does not match the Tensor at index 0: \",\n value_0_t->shape().DebugString()));", " TensorShape output_shape(value_0_t->shape());\n output_shape.InsertDim(0, num_indices);", " Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape, &output_tensor));", " // If output_tensor is empty, there is nothing to concatenate so return it.\n if (output_shape.num_elements() == 0) {\n return;\n }", " ConstMatrixVector input_tensors_flat;\n input_tensors_flat.reserve(num_indices);\n auto output_flat =\n output_tensor->shaped<T, 2>({1, output_shape.num_elements()});", " // Insert the first value\n input_tensors_flat.push_back(MakeUnique<ConstMatrix>(\n value_0_t->shaped<T, 2>({1, value_0_t->NumElements()})));", " for (int i = 1; i < num_indices; ++i) {\n const Tensor* value_t = &values[i];\n OP_REQUIRES(\n ctx, value_0_t->shape() == value_t->shape(),\n errors::InvalidArgument(\n \"TensorArray has inconsistent shapes. Index 0 has shape: \",\n value_0_t->shape().DebugString(), \" but index \", i,\n \" has shape: \", value_t->shape().DebugString()));\n input_tensors_flat.push_back(MakeUnique<ConstMatrix>(\n value_t->shaped<T, 2>({1, value_t->NumElements()})));\n }", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n if (std::is_same<Device, GPUDevice>::value) {\n ConcatGPU<T>(ctx, input_tensors_flat, output_tensor, &output_flat);\n return;\n }\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n ConcatCPU<T>(ctx->device(), input_tensors_flat, &output_flat);\n }", " private:\n DataType dtype_;\n PartialTensorShape element_shape_;\n};", "#define REGISTER_GATHER_AND_PACK(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayPack\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayPackOrGatherOp<CPUDevice, type, true /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGather\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayPackOrGatherOp<CPUDevice, type, false /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGatherV2\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayPackOrGatherOp<CPUDevice, type, false /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGatherV3\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayPackOrGatherOp<CPUDevice, type, false /* LEGACY_PACK */>);", "TF_CALL_POD_STRING_TYPES(REGISTER_GATHER_AND_PACK);\nTF_CALL_variant(REGISTER_GATHER_AND_PACK);\nREGISTER_GATHER_AND_PACK(quint8);\nREGISTER_GATHER_AND_PACK(qint8);\nREGISTER_GATHER_AND_PACK(qint32);", "#undef REGISTER_GATHER_AND_PACK", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayPack\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayPackOrGatherOp<GPUDevice, type, true /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGather\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayPackOrGatherOp<GPUDevice, type, false /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGatherV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayPackOrGatherOp<GPUDevice, type, false /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGatherV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayPackOrGatherOp<GPUDevice, type, false /* LEGACY_PACK */>);", "TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "// A special GPU kernel for int32.\n// TODO(b/25387198): Also enable int32 in device memory. This kernel\n// registration requires all int32 inputs and outputs to be in host memory.\nREGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayGather\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"indices\")\n .HostMemory(\"handle\"),\n TensorArrayPackOrGatherOp<CPUDevice, int32, false /* LEGACY_PACK */>);\nREGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayGatherV2\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"indices\")\n .HostMemory(\"handle\"),\n TensorArrayPackOrGatherOp<CPUDevice, int32, false /* LEGACY_PACK */>);\nREGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayGatherV3\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"indices\")\n .HostMemory(\"handle\"),\n TensorArrayPackOrGatherOp<CPUDevice, int32, false /* LEGACY_PACK */>);", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// CONCAT *********************************************************************", "// Concatenate the elements in a TensorArray. All elements must be\n// defined and (excepting the first dimension) have the same shape.\ntemplate <typename Device, typename T>\nclass TensorArrayConcatOp : public OpKernel {\n public:\n typedef typename TTypes<T, 2>::ConstMatrix ConstMatrix;\n typedef std::vector<std::unique_ptr<ConstMatrix> > ConstMatrixVector;", " explicit TensorArrayConcatOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"dtype\", &dtype_));\n OP_REQUIRES_OK(context, context->GetAttr(\"element_shape_except0\",\n &element_shape_except0_));\n }", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, false));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n OP_REQUIRES(\n ctx, dtype_ == tensor_array->ElemType(),\n errors::InvalidArgument(\n \"TensorArray dtype is \", DataTypeString(tensor_array->ElemType()),\n \" but Op requested dtype \", DataTypeString(dtype_), \".\"));", " int32_t array_size;\n OP_REQUIRES_OK(ctx, tensor_array->PackOrConcatSize(&array_size));", " // If there are no elements, return a zero-element Tensor with\n // shape [0] + element_shape_except0_\n if (array_size == 0) {\n OP_REQUIRES(\n ctx, element_shape_except0_.IsFullyDefined(),\n errors::Unimplemented(\n \"TensorArray has size zero, but element_shape_except0 \",\n element_shape_except0_.DebugString(),\n \" is not fully defined. \"\n \"Currently only static shapes are supported when concatenating \"\n \"zero-size TensorArrays.\"));\n TensorShape empty_shape;\n element_shape_except0_.AsTensorShape(&empty_shape);\n empty_shape.InsertDim(0, 0);\n Tensor* empty_unused;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, empty_shape, &empty_unused));\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, {0}, &empty_unused));\n return;\n }", " // Read all the Tensors into a vector to keep track of their memory.\n std::vector<Tensor> values;\n std::vector<int32> indices(array_size);\n std::iota(indices.begin(), indices.end(), 0);\n Status s = tensor_array->ReadMany<Device, T>(ctx, indices, &values);\n OP_REQUIRES_OK(ctx, s);", " Tensor* lengths_tensor = nullptr;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(\n 1, TensorShape({static_cast<int64_t>(values.size())}),\n &lengths_tensor));\n auto lengths_tensor_t = lengths_tensor->vec<int64_t>();", " TensorShape output_shape;\n TensorShape output_shape_except0;\n for (std::size_t i = 0; i < values.size(); ++i) {\n TensorShape value_shape_t = values[i].shape();", " OP_REQUIRES(\n ctx, TensorShapeUtils::IsVectorOrHigher(value_shape_t),\n errors::InvalidArgument(\n \"Concat saw a scalar shape at index \", i,\n \" but requires at least vectors. Did you mean to call pack?\"));", " lengths_tensor_t(i) = value_shape_t.dim_size(0);", " TensorShape value_shape_t_except0 = value_shape_t;\n value_shape_t_except0.RemoveDim(0);\n if (i == 0) {\n output_shape = value_shape_t;\n output_shape_except0 = value_shape_t_except0;\n OP_REQUIRES(\n ctx, element_shape_except0_.IsCompatibleWith(output_shape_except0),\n errors::InvalidArgument(\n \"TensorArray was passed element_shape_except0 \",\n element_shape_except0_.DebugString(),\n \" but index 0 has (excepting dimension 0) shape: \",\n value_shape_t_except0.DebugString(), \" which does not match.\"));\n } else {\n OP_REQUIRES(ctx, output_shape_except0 == value_shape_t_except0,\n errors::InvalidArgument(\n \"TensorArray has inconsistent shapes. Index 0 has \"\n \"(excepting dimension 0) shape: \",\n output_shape_except0.DebugString(), \" but index \", i,\n \" has (excepting dimension 0) shape: \",\n value_shape_t_except0.DebugString()));\n // Store the previous maximum length as the offset for this tensor.\n output_shape.set_dim(\n 0, output_shape.dim_size(0) + value_shape_t.dim_size(0));\n }\n }", " Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape, &output_tensor));\n ConstMatrixVector input_tensors_flat;\n input_tensors_flat.reserve(values.size());\n for (size_t i = 0; i < values.size(); ++i) {\n const Tensor* value_t = &values[i];\n if (value_t->NumElements() > 0) {\n input_tensors_flat.push_back(MakeUnique<ConstMatrix>(\n value_t->shaped<T, 2>({1, value_t->NumElements()})));\n }\n }", " if (output_shape.num_elements() > 0) {\n auto output_flat =\n output_tensor->shaped<T, 2>({1, output_shape.num_elements()});\n#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n if (std::is_same<Device, GPUDevice>::value) {\n ConcatGPU<T>(ctx, input_tensors_flat, output_tensor, &output_flat);\n return;\n }\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n ConcatCPU<T>(ctx->device(), input_tensors_flat, &output_flat);\n }\n }", " private:\n DataType dtype_;\n PartialTensorShape element_shape_except0_;\n};", "#define REGISTER_CONCAT(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcat\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV2\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<CPUDevice, type>) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV3\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<CPUDevice, type>)", "TF_CALL_POD_STRING_TYPES(REGISTER_CONCAT);\nREGISTER_CONCAT(quint8);\nREGISTER_CONCAT(qint8);\nREGISTER_CONCAT(qint32);", "#undef REGISTER_CONCAT", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcat\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<GPUDevice, type>) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<GPUDevice, type>)", "TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "// A special GPU kernel for int32.\n// TODO(b/25387198): Also enable int32 in device memory. This kernel\n// registration requires all int32 inputs and outputs to be in host memory.\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcat\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"lengths\")\n .HostMemory(\"handle\"),\n TensorArrayConcatOp<CPUDevice, int32>);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV2\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"lengths\")\n .HostMemory(\"handle\"),\n TensorArrayConcatOp<CPUDevice, int32>);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV3\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"lengths\")\n .HostMemory(\"handle\"),\n TensorArrayConcatOp<CPUDevice, int32>);", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// UNPACK and SCATTER *********************************************************", "template <typename Device, typename T, bool LEGACY_UNPACK>\nclass TensorArrayUnpackOrScatterOp : public OpKernel {\n public:\n explicit TensorArrayUnpackOrScatterOp(OpKernelConstruction* context)\n : OpKernel(context) {}", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, true));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n const Tensor* tensor_value;\n OP_REQUIRES_OK(ctx, ctx->input(\"value\", &tensor_value));\n TensorShape element_shape(tensor_value->shape());", " OP_REQUIRES(ctx,\n FastBoundsCheck(element_shape.dim_size(0),\n std::numeric_limits<int32>::max()),\n errors::InvalidArgument(\"tensor dim0 too large to unpack\"));", " OP_REQUIRES(\n ctx, tensor_value->dtype() == tensor_array->ElemType(),\n errors::InvalidArgument(\"TensorArray dtype is \",\n DataTypeString(tensor_array->ElemType()),\n \" but Op is trying to write dtype \",\n DataTypeString(tensor_value->dtype()), \".\"));\n OP_REQUIRES(ctx, element_shape.dims() > 0,\n errors::InvalidArgument(\"Input value for unpack must be at \"\n \"least a vector but received shape: \",\n element_shape.DebugString()));\n int32_t array_size;\n OP_REQUIRES_OK(ctx, tensor_array->Size(&array_size));", " int32_t max_index;\n int32_t num_values;\n std::vector<int32> write_indices;\n if (LEGACY_UNPACK) {\n num_values = element_shape.dim_size(0);\n max_index = num_values - 1;\n write_indices.resize(num_values);\n std::iota(write_indices.begin(), write_indices.end(), 0);\n } else {\n const Tensor* tensor_indices;\n OP_REQUIRES_OK(ctx, ctx->input(\"indices\", &tensor_indices));\n OP_REQUIRES(ctx, TensorShapeUtils::IsVector(tensor_indices->shape()),\n errors::InvalidArgument(\n \"Expected indices to be a vector, but received shape: \",\n tensor_indices->shape().DebugString()));\n OP_REQUIRES(ctx,\n tensor_indices->NumElements() == element_shape.dim_size(0),\n errors::InvalidArgument(\n \"Expected len(indices) == values.shape[0], but saw: \",\n tensor_indices->NumElements(), \" vs. \",\n element_shape.dim_size(0)));\n const auto indices_t = tensor_indices->vec<int32>();\n num_values = tensor_indices->NumElements();\n max_index = (num_values == 0)\n ? -1\n : *std::max_element(indices_t.data(),\n indices_t.data() + num_values);\n write_indices.resize(num_values);\n // Copy into write_indices.\n std::copy(indices_t.data(), indices_t.data() + num_values,\n write_indices.begin());\n }", " bool dynamic_size = tensor_array->HasDynamicSize();", " // If dynamic size, we may have to resize the TensorArray to fit.\n if (dynamic_size && array_size < max_index + 1) {\n array_size = static_cast<int32>(max_index + 1);\n }", " if (LEGACY_UNPACK) {\n OP_REQUIRES(\n ctx, element_shape.dim_size(0) == array_size,\n errors::InvalidArgument(\n \"Input value must have first dimension equal to the array size (\",\n element_shape.dim_size(0), \" vs. \", array_size, \")\"));\n } else {\n OP_REQUIRES(\n ctx, max_index < array_size,\n errors::InvalidArgument(\"Max scatter index must be < array size (\",\n max_index, \" vs. \", array_size, \")\"));\n }\n element_shape.RemoveDim(0);", " auto tensor_value_t = tensor_value->shaped<T, 3>(\n {1, num_values, element_shape.num_elements()});", " Eigen::DSizes<Eigen::DenseIndex, 3> indices{0, 0, 0};\n Eigen::DSizes<Eigen::DenseIndex, 3> sizes{\n 1, 1, static_cast<Eigen::DenseIndex>(element_shape.num_elements())};", " std::vector<Tensor> write_values;\n write_values.reserve(num_values);", " for (int i = 0; i < num_values; ++i) {\n Tensor tensor_value_i;\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(tensor_array->ElemType(),\n element_shape, &tensor_value_i));\n auto tensor_value_i_t =\n tensor_value_i.shaped<T, 3>({1, 1, element_shape.num_elements()});\n indices[1] = i;", " if (element_shape.num_elements() > 0) {\n functor::Split<Device, T, 3>()(ctx->eigen_device<Device>(),\n tensor_value_i_t, tensor_value_t,\n indices, sizes);\n }", " write_values.push_back(tensor_value_i);\n }", " // Record the pack size of the TensorArray.\n if (LEGACY_UNPACK) {\n OP_REQUIRES_OK(ctx, tensor_array->SetMarkedSize(array_size));\n }", " Status s = tensor_array->WriteOrAggregateMany<Device, T>(ctx, write_indices,\n &write_values);\n OP_REQUIRES_OK(ctx, s);\n }\n};", "#define REGISTER_SCATTER_AND_UNPACK(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayUnpack\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArrayUnpackOrScatterOp<CPUDevice, type, \\\n true /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatter\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArrayUnpackOrScatterOp<CPUDevice, type, \\\n false /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatterV2\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"T\"), \\\n TensorArrayUnpackOrScatterOp<CPUDevice, type, \\\n false /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatterV3\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"T\"), \\\n TensorArrayUnpackOrScatterOp<CPUDevice, type, \\\n false /* LEGACY_UNPACK */>);", "TF_CALL_ALL_TYPES(REGISTER_SCATTER_AND_UNPACK);\n#undef REGISTER_SCATTER_AND_UNPACK", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayUnpack\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayUnpackOrScatterOp<GPUDevice, type, \\\n true /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatter\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayUnpackOrScatterOp<GPUDevice, type, \\\n false /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatterV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayUnpackOrScatterOp<GPUDevice, type, \\\n false /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatterV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayUnpackOrScatterOp<GPUDevice, type, \\\n false /* LEGACY_UNPACK */>);", "TF_CALL_int64(REGISTER_GPU);\nTF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// SPLIT *********************************************************************", "template <typename Device, typename T>\nclass TensorArraySplitOp : public OpKernel {\n public:\n explicit TensorArraySplitOp(OpKernelConstruction* context)\n : OpKernel(context) {}", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, true));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n const Tensor* tensor_value;\n OP_REQUIRES_OK(ctx, ctx->input(\"value\", &tensor_value));\n const Tensor* tensor_lengths;\n OP_REQUIRES_OK(ctx, ctx->input(\"lengths\", &tensor_lengths));", " OP_REQUIRES(ctx, TensorShapeUtils::IsVector(tensor_lengths->shape()),\n errors::InvalidArgument(\n \"Expected lengths to be a vector, received shape: \",\n tensor_lengths->shape().DebugString()));\n OP_REQUIRES(ctx,\n FastBoundsCheck(tensor_lengths->NumElements(),\n std::numeric_limits<int32>::max()),\n errors::InvalidArgument(\n \"Expected lengths to have < max int32 entries\"));", " int32_t num_tensors = static_cast<int32>(tensor_lengths->NumElements());\n auto tensor_lengths_t = tensor_lengths->vec<int64_t>();\n std::vector<int64_t> cumulative_lengths;\n cumulative_lengths.reserve(num_tensors);\n int64_t total_length = 0;\n for (int i = 0; i < num_tensors; ++i) {\n total_length += tensor_lengths_t(i);\n cumulative_lengths.push_back(total_length);\n }", " OP_REQUIRES(\n ctx, TensorShapeUtils::IsVectorOrHigher(tensor_value->shape()),\n errors::InvalidArgument(\n \"Expected value to be at least a vector, but received shape: \",\n tensor_value->shape().DebugString()));", " OP_REQUIRES(\n ctx, total_length == tensor_value->shape().dim_size(0),\n errors::InvalidArgument(\"Expected sum of lengths to be equal to \"\n \"values.shape[0], but sum of lengths is \",\n total_length, \" and value's shape is: \",\n tensor_value->shape().DebugString()));\n int64_t elements_per_row =\n (total_length == 0) ? 0 : (tensor_value->NumElements() / total_length);", " int32_t array_size;\n OP_REQUIRES_OK(ctx, tensor_array->Size(&array_size));\n bool dynamic_size = tensor_array->HasDynamicSize();", " std::vector<TensorShape> element_shapes(num_tensors, tensor_value->shape());\n for (int32_t i = 0; i < num_tensors; ++i) {\n element_shapes[i].set_dim(0, tensor_lengths_t(i));\n }", " // If dynamic size, we may have to resize the TensorArray to fit.\n if (dynamic_size && array_size < num_tensors) {\n array_size = num_tensors;\n }", " OP_REQUIRES(\n ctx, array_size == num_tensors,\n errors::InvalidArgument(\n \"TensorArray's size is not equal to the size of lengths (\",\n array_size, \" vs. \", num_tensors, \"), and the TensorArray is not \",\n \"marked as dynamically resizeable\"));", " OP_REQUIRES(\n ctx, tensor_value->dtype() == tensor_array->ElemType(),\n errors::InvalidArgument(\"TensorArray dtype is \",\n DataTypeString(tensor_array->ElemType()),\n \" but Op is trying to write dtype \",\n DataTypeString(tensor_value->dtype()), \".\"));", " auto tensor_value_t =\n tensor_value->shaped<T, 3>({1, total_length, elements_per_row});", " std::vector<Tensor> write_values;\n write_values.reserve(array_size);", " for (int i = 0; i < array_size; ++i) {\n Tensor tensor_value_i;", " int64_t previous_length = (i == 0) ? 0 : cumulative_lengths[i - 1];\n Eigen::DSizes<Eigen::DenseIndex, 3> indices{\n 0, static_cast<Eigen::DenseIndex>(previous_length), 0};\n Eigen::DSizes<Eigen::DenseIndex, 3> sizes{\n 1, static_cast<Eigen::DenseIndex>(tensor_lengths_t(i)),\n static_cast<Eigen::DenseIndex>(elements_per_row)};", " OP_REQUIRES_OK(\n ctx, ctx->allocate_temp(tensor_array->ElemType(), element_shapes[i],\n &tensor_value_i));", " if (tensor_lengths_t(i) > 0) {\n auto tensor_value_i_t = tensor_value_i.shaped<T, 3>(\n {1, tensor_lengths_t(i), elements_per_row});", " functor::Split<Device, T, 3>()(ctx->eigen_device<Device>(),\n tensor_value_i_t, tensor_value_t,\n indices, sizes);\n }", " write_values.push_back(tensor_value_i);\n }", " // Record the concat size of the TensorArray.\n OP_REQUIRES_OK(ctx, tensor_array->SetMarkedSize(array_size));", " std::vector<int32> indices(array_size);\n std::iota(indices.begin(), indices.end(), 0);", " Status s = tensor_array->WriteOrAggregateMany<Device, T>(ctx, indices,\n &write_values);\n OP_REQUIRES_OK(ctx, s);\n }\n};", "#define REGISTER_SPLIT(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArraySplit\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArraySplitOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArraySplitV2\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArraySplitOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArraySplitV3\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArraySplitOp<CPUDevice, type>);", "TF_CALL_ALL_TYPES(REGISTER_SPLIT);\n#undef REGISTER_SPLIT", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArraySplit\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArraySplitOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArraySplitV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArraySplitOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArraySplitV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArraySplitOp<GPUDevice, type>);", "TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// SIZE ***********************************************************************", "// Get the size of the TensorArray\nclass TensorArraySizeOp : public OpKernel {\n public:\n explicit TensorArraySizeOp(OpKernelConstruction* context)\n : OpKernel(context) {}", " void Compute(OpKernelContext* ctx) override {\n TensorArray* tensor_array;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &output));\n OP_REQUIRES_OK(ctx, tensor_array->Size(&(output->scalar<int32>()())));\n }\n};", "REGISTER_KERNEL_BUILDER(Name(\"TensorArraySize\").Device(DEVICE_CPU),\n TensorArraySizeOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArraySizeV2\").Device(DEVICE_CPU),\n TensorArraySizeOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArraySizeV3\").Device(DEVICE_CPU),\n TensorArraySizeOp);", "REGISTER_KERNEL_BUILDER(Name(\"TensorArraySize\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"size\"),\n TensorArraySizeOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArraySizeV2\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"size\"),\n TensorArraySizeOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArraySizeV3\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"size\"),\n TensorArraySizeOp);", "// CLOSE\n// **********************************************************************", "// Delete the TensorArray from its resource container. This enables\n// the user to close and release the resource in the middle of a step/run.\n// TODO(ebrevdo): decide whether closing the grad op should happen\n// here or on the python side.\nclass TensorArrayCloseOp : public OpKernel {\n public:\n explicit TensorArrayCloseOp(OpKernelConstruction* context)\n : OpKernel(context) {}", " void Compute(OpKernelContext* ctx) override {\n TensorArray* tensor_array;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n // Instead of deleting this TA from the ResourceManager, we just\n // clear it away and mark it as closed. The remaining memory\n // consumed store its mutex and handle Tensor. This will be\n // cleared out at the end of the step anyway, so it's fine to keep\n // it around until the end of the step. Further calls to the\n // TensorArray will fail because TensorArray checks internally to\n // see if it is closed or not.\n tensor_array->ClearAndMarkClosed();\n }\n};", "REGISTER_KERNEL_BUILDER(Name(\"TensorArrayClose\").Device(DEVICE_CPU),\n TensorArrayCloseOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayCloseV2\").Device(DEVICE_CPU),\n TensorArrayCloseOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayCloseV3\").Device(DEVICE_CPU),\n TensorArrayCloseOp);", "REGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayClose\").Device(DEVICE_GPU).HostMemory(\"handle\"),\n TensorArrayCloseOp);\nREGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayCloseV2\").Device(DEVICE_GPU).HostMemory(\"handle\"),\n TensorArrayCloseOp);\nREGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayCloseV3\").Device(DEVICE_GPU).HostMemory(\"handle\"),\n TensorArrayCloseOp);", "} // namespace tensorflow" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [85, 1848], "buggy_code_start_loc": [83, 1848], "filenames": ["tensorflow/core/kernels/tensor_array_ops.cc", "tensorflow/python/kernel_tests/data_structures/tensor_array_ops_test.py"], "fixing_code_end_loc": [86, 1865], "fixing_code_start_loc": [83, 1849], "message": "TensorFlow is an open source platform for machine learning. Prior to versions 2.12.0 and 2.11.1, when `ctx->step_containter()` is a null ptr, the Lookup function will be executed with a null pointer. A fix is included in TensorFlow 2.12.0 and 2.11.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "FAC3DE54-93B4-4D6C-9648-B9D416B9770F", "versionEndExcluding": "2.12.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an open source platform for machine learning. Prior to versions 2.12.0 and 2.11.1, when `ctx->step_containter()` is a null ptr, the Lookup function will be executed with a null pointer. A fix is included in TensorFlow 2.12.0 and 2.11.1."}], "evaluatorComment": null, "id": "CVE-2023-25663", "lastModified": "2023-03-30T17:42:24.500", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-25T00:15:07.313", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/tensorflow/tensorflow/commit/239139d2ae6a81ae9ba499ad78b56d9b2931538a"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-64jg-wjww-7c5w"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/239139d2ae6a81ae9ba499ad78b56d9b2931538a"}, "type": "CWE-476"}
230
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at", " http://www.apache.org/licenses/LICENSE-2.0", "Unless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/", "// See docs in ../ops/data_flow_ops.cc.", "#define EIGEN_USE_THREADS", "#include <limits>\n#include <vector>\n// TODO(b/31496047): Fix non-standard include order.\n#include <numeric> // clang-format off", "#include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n#include \"tensorflow/core/framework/bounds_check.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/resource_mgr.h\"\n#include \"tensorflow/core/framework/tensor.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/tensor_util.h\"\n#include \"tensorflow/core/framework/types.h\"\n#include \"tensorflow/core/kernels/concat_lib.h\"\n#include \"tensorflow/core/kernels/split_lib.h\"\n#include \"tensorflow/core/kernels/tensor_array.h\"\n#include \"tensorflow/core/lib/core/errors.h\"\n#include \"tensorflow/core/lib/core/refcount.h\"\n#include \"tensorflow/core/lib/strings/strcat.h\"\n#include \"tensorflow/core/platform/dynamic_annotations.h\"\n#include \"tensorflow/core/platform/logging.h\"\n#include \"tensorflow/core/platform/thread_annotations.h\"\n#include \"tensorflow/core/platform/types.h\"\n#include \"tensorflow/core/util/ptr_util.h\"", "typedef Eigen::ThreadPoolDevice CPUDevice;\n#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM\ntypedef Eigen::GpuDevice GPUDevice;\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// clang-format on", "namespace tensorflow {", "Status GetHandle(OpKernelContext* ctx, string* container, string* ta_handle) {\n {\n Tensor tensor;\n // Assuming that handle is the input at index 0.\n if (IsRefType(ctx->input_dtype(0))) {\n tensor = ctx->mutable_input(0, false);\n } else {\n tensor = ctx->input(0);\n }\n if (tensor.NumElements() != 2) {\n return errors::InvalidArgument(\n \"Tensor array handle must be 2-element vector, but had shape: \",\n tensor.shape().DebugString());\n }\n auto h = tensor.flat<tstring>();\n *container = h(0);\n *ta_handle = h(1);\n }\n return OkStatus();\n}", "Status GetTensorArray(OpKernelContext* ctx, TensorArray** tensor_array) {\n string container;\n string ta_handle;\n if (ctx->input_dtype(0) != DT_RESOURCE) {\n TF_RETURN_IF_ERROR(GetHandle(ctx, &container, &ta_handle));\n ResourceMgr* rm = ctx->resource_manager();\n if (rm == nullptr) return errors::Internal(\"No resource manager.\");", " ScopedStepContainer* sc = ctx->step_container();\n if (sc == nullptr) return errors::Internal(\"No step container.\");\n TF_RETURN_IF_ERROR(sc->Lookup(rm, container + ta_handle, tensor_array));", " return OkStatus();\n } else {\n return LookupResource(ctx, HandleFromInput(ctx, 0), tensor_array);\n }\n}", "Status SetupFlowControlInputs(OpKernelContext* ctx, bool set_output) {\n const Tensor* flow_control;\n TF_RETURN_IF_ERROR(ctx->input(\"flow_in\", &flow_control));\n if (set_output) {\n TF_RETURN_IF_ERROR(ctx->set_output(\"flow_out\", *flow_control));\n }\n return OkStatus();\n}", "// CREATION *******************************************************************", "// Virtual class for shared behavior between TensorArrayOp and\n// TensorArrayGradOp.\nclass TensorArrayCreationOp : public OpKernel {\n public:\n explicit TensorArrayCreationOp(OpKernelConstruction* context)\n : OpKernel(context), device_type_(context->device_type()) {}", " void Compute(OpKernelContext* ctx) override {\n Tensor tensor_array_output_handle;", " AllocatorAttributes alloc_attr;\n alloc_attr.set_on_host(true);\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(\n tensorflow::DT_STRING, tensorflow::TensorShape({2}),\n &tensor_array_output_handle, alloc_attr));\n // Store the handle in a per-step container of the RM.\n ResourceMgr* rm = ctx->resource_manager();\n OP_REQUIRES(ctx, rm != nullptr, errors::Internal(\"No resource manager.\"));", " TensorArray* output_tensor_array;\n OP_REQUIRES_OK(ctx, CreateTensorArray(ctx, rm, &tensor_array_output_handle,\n &output_tensor_array));\n if (IsRefType(ctx->expected_output_dtype(0))) {\n ctx->set_output_ref(0, output_tensor_array->mu(),\n output_tensor_array->handle());\n } else if (ctx->expected_output_dtype(0) == DT_STRING) {\n ctx->set_output(0, *output_tensor_array->handle());\n } else {\n Tensor* handle;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));\n handle->flat<ResourceHandle>()(0) =\n output_tensor_array->resource_handle(ctx);\n }\n if (ctx->num_outputs() == 2) {\n // Create the flow output.\n Tensor* flow;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &flow));\n if (device_type_ == DEVICE_CPU) {\n // Value doesn't matter, but this makes msan not complaint about\n // copying an uninitialized value. To do this on GPU would require\n // a kernel launch or a host->device memcpy, so we avoid that.\n flow->flat<float>()(0) = 0;\n }\n }\n }", " protected:\n virtual Status CreateTensorArray(OpKernelContext* ctx, ResourceMgr* rm,\n Tensor* tensor_array_output_handle,\n TensorArray** output_tensor_array) = 0;", " private:\n const DeviceType device_type_;\n};", "// A per-run local tensor array. The tensor array uses a \"per-step\" resource\n// manager which ensures that correct garbage collection on error or\n// successful completion.\nclass TensorArrayOp : public TensorArrayCreationOp {\n public:\n explicit TensorArrayOp(OpKernelConstruction* context)\n : TensorArrayCreationOp(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"dtype\", &dtype_));\n OP_REQUIRES_OK(context, context->GetAttr(\"element_shape\", &element_shape_));\n OP_REQUIRES_OK(context, context->GetAttr(\"dynamic_size\", &dynamic_size_));\n // The HasAttr check is for backwards compatibility with older op\n // versions which do not have this attribute.\n if (context->HasAttr(\"identical_element_shapes\")) {\n OP_REQUIRES_OK(context, context->GetAttr(\"identical_element_shapes\",\n &identical_element_shapes_));\n } else {\n identical_element_shapes_ = false;\n }\n OP_REQUIRES_OK(context,\n context->GetAttr(\"clear_after_read\", &clear_after_read_));\n OP_REQUIRES_OK(context,\n context->GetAttr(\"tensor_array_name\", &tensor_array_name_));\n if (tensor_array_name_.empty()) tensor_array_name_ = name();\n }", " Status CreateTensorArray(OpKernelContext* ctx, ResourceMgr* rm,\n Tensor* tensor_array_output_handle,\n TensorArray** output_tensor_array) override {\n const Tensor* tensor_size;\n TF_RETURN_IF_ERROR(ctx->input(\"size\", &tensor_size));", " if (!TensorShapeUtils::IsScalar(tensor_size->shape())) {\n return errors::InvalidArgument(\n \"TensorArray size must be scalar, but had shape: \",\n tensor_size->shape().DebugString());\n }\n const int32_t size = tensor_size->scalar<int32>()();\n if (size < 0) {\n return errors::InvalidArgument(\"Size should be >= 0.\");\n }", " auto handle = tensor_array_output_handle->flat<tstring>();\n string unique_tensor_array_name =\n strings::StrCat(tensor_array_name_, \"_\",\n TensorArray::tensor_array_counter.fetch_add(1));\n handle(0) = \"_tensor_arrays\";\n handle(1) = unique_tensor_array_name;", " auto key = strings::StrCat(handle(0), unique_tensor_array_name);", " TensorArray* tensor_array = new TensorArray(\n key, dtype_, *tensor_array_output_handle, size, element_shape_,\n identical_element_shapes_, dynamic_size_,\n false /* multiple_writes_aggregate */, false /* is_grad */,\n -1 /* marked_size */, clear_after_read_);", " TF_RETURN_IF_ERROR(ctx->step_container()->Create(rm, key, tensor_array));", " *output_tensor_array = tensor_array;", " return OkStatus();\n }", " private:\n DataType dtype_;\n PartialTensorShape element_shape_;\n bool identical_element_shapes_;\n bool dynamic_size_;\n bool clear_after_read_;\n string tensor_array_name_; // The name used to create the TensorArray.", " TF_DISALLOW_COPY_AND_ASSIGN(TensorArrayOp);\n};", "REGISTER_KERNEL_BUILDER(Name(\"TensorArray\").Device(DEVICE_CPU), TensorArrayOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayV2\").Device(DEVICE_CPU),\n TensorArrayOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayV3\").Device(DEVICE_CPU),\n TensorArrayOp);", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArray\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"size\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayOp); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"size\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayOp); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"size\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayOp);", "TF_CALL_int64(REGISTER_GPU);\nTF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// GRADIENT *******************************************************************\n// Note that this op may have an optional third input. If present, it represents\n// a shape value. It indicates that element shape of this gradient array is that\n// shape value concatenated with the element shape of the original tensor array.\n// See TensorArrayGradWithShape.\nclass TensorArrayGradOp : public TensorArrayCreationOp {\n public:\n explicit TensorArrayGradOp(OpKernelConstruction* context)\n : TensorArrayCreationOp(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"source\", &source_));\n }", " Status CreateTensorArray(OpKernelContext* ctx, ResourceMgr* rm,\n Tensor* tensor_array_output_handle,\n TensorArray** output_tensor_array) override {\n string container;\n string tensor_array_name;\n if (ctx->input_dtype(0) != DT_RESOURCE) {\n TF_RETURN_IF_ERROR(GetHandle(ctx, &container, &tensor_array_name));\n if (container != \"_tensor_arrays\") {\n return errors::InvalidArgument(\n \"Input container should be '_tensor_arrays', but received '\",\n container, \"'\");\n }\n } else {\n container = \"_tensor_arrays\";\n const auto& resource = ctx->input(0).flat<ResourceHandle>()(0);\n if (StringPiece(resource.name()).substr(0, container.size()) !=\n container) {\n return errors::InvalidArgument(\"Wrong input container. \",\n resource.name());\n }\n tensor_array_name =\n string(StringPiece(resource.name()).substr(container.size()));\n }", " auto output_handle = tensor_array_output_handle->flat<tstring>();\n output_handle(0) = \"_tensor_array_grads\";\n output_handle(1) = strings::StrCat(tensor_array_name, \"@\", source_);", " TensorArray* tensor_array;\n TF_RETURN_IF_ERROR(ctx->step_container()->Lookup(\n rm, strings::StrCat(container, tensor_array_name), &tensor_array));\n core::ScopedUnref unref(tensor_array);", " // Once gradients are being calculated, the forward TensorArray\n // may no longer be resized by new Writes.\n tensor_array->DisableDynamicSize();", " int32_t array_size = 0;\n int32_t marked_size = 0;\n TF_RETURN_IF_ERROR(tensor_array->Size(&array_size));\n TF_RETURN_IF_ERROR(tensor_array->MarkedSize(&marked_size));", " if (array_size < 0) {\n return errors::InvalidArgument(\"ArraySize should be >= 0.\");\n }\n if (!tensor_array->GradientsAllowed()) {\n return errors::InvalidArgument(\n \"Unable to create a gradients TensorArray for \", tensor_array_name,\n \". Perhaps you used the multiple_writes_aggregate flag on a \"\n \"previous write? Gradient calculation is impossible when multiple \"\n \"writes are performed to the same index.\");\n }\n TensorShape shape_to_prepend;\n auto element_shape = PartialTensorShape();\n if (ctx->num_inputs() > 2) {\n TF_RETURN_IF_ERROR(tensor::MakeShape(ctx->input(2), &shape_to_prepend));\n auto ta_element_shape = tensor_array->ElemShape();\n if (!ta_element_shape.unknown_rank()) {\n std::vector<int64_t> dims;\n for (auto dim : shape_to_prepend) {\n dims.push_back(dim.size);\n }\n for (auto dim : ta_element_shape) {\n dims.push_back(dim.size);\n }\n TF_RETURN_IF_ERROR(TensorShapeUtils::MakeShape(\n gtl::ArraySlice<int64_t>(dims), &element_shape));\n }\n } else {\n element_shape = tensor_array->ElemShape();\n }", " const auto key = strings::StrCat(output_handle(0), output_handle(1));\n auto creator = [key, tensor_array, array_size, marked_size, element_shape,\n shape_to_prepend,\n tensor_array_output_handle](TensorArray** ret) -> Status {\n *ret = new TensorArray(\n key, tensor_array->ElemType(), *tensor_array_output_handle,\n array_size, element_shape, tensor_array->HasIdenticalElementShapes(),\n false /* dynamic_size */, true /* multiple_writes_aggregate */,\n true /* is_grad */, marked_size /* marked_size */,\n true /* close_after_read */);\n return (*ret)->CopyShapesFrom(tensor_array, &shape_to_prepend);\n };", " Status s = ctx->step_container()->LookupOrCreate<TensorArray>(\n rm, key, output_tensor_array, creator);\n (*output_tensor_array)->Unref();", " return s;\n }", " private:\n // The gradient source for creating the given\n // gradient TensorArray. This should be unique to each gradients\n // call. Typical values look like \"gradients\", \"gradients_1\", ...\n string source_;", " TF_DISALLOW_COPY_AND_ASSIGN(TensorArrayGradOp);\n};", "REGISTER_KERNEL_BUILDER(Name(\"TensorArrayGrad\").Device(DEVICE_CPU),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradV2\").Device(DEVICE_CPU),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradV3\").Device(DEVICE_CPU),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradWithShape\").Device(DEVICE_CPU),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGrad\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"grad_handle\"),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradV2\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"grad_handle\"),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradV3\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"grad_handle\"),\n TensorArrayGradOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayGradWithShape\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"shape_to_prepend\")\n .HostMemory(\"grad_handle\"),\n TensorArrayGradOp);", "// WRITE **********************************************************************", "template <typename Device, typename T>\nclass TensorArrayWriteOp : public OpKernel {\n public:\n explicit TensorArrayWriteOp(OpKernelConstruction* context)\n : OpKernel(context) {}", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, true));", " const Tensor* tensor_index;\n const Tensor* tensor_value;\n OP_REQUIRES_OK(ctx, ctx->input(\"index\", &tensor_index));\n OP_REQUIRES_OK(ctx, ctx->input(\"value\", &tensor_value));", " OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(tensor_index->shape()),\n errors::InvalidArgument(\n \"TensorArray index must be scalar, but had shape: \",\n tensor_index->shape().DebugString()));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n const int32_t index = tensor_index->scalar<int32>()();\n OP_REQUIRES(\n ctx, tensor_value->dtype() == tensor_array->ElemType(),\n errors::InvalidArgument(\"TensorArray dtype is \",\n DataTypeString(tensor_array->ElemType()),\n \" but Op is trying to write dtype \",\n DataTypeString(tensor_value->dtype()), \".\"));\n Status s =\n tensor_array->WriteOrAggregate<Device, T>(ctx, index, tensor_value);\n OP_REQUIRES_OK(ctx, s);\n }\n};", "#define REGISTER_WRITE(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayWrite\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArrayWriteOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayWriteV2\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArrayWriteOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayWriteV3\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArrayWriteOp<CPUDevice, type>);", "TF_CALL_ALL_TYPES(REGISTER_WRITE);", "#undef REGISTER_WRITE", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayWrite\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayWriteOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayWriteV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayWriteOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayWriteV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayWriteOp<GPUDevice, type>);", "TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// READ ***********************************************************************", "template <typename Device, typename T>\nclass TensorArrayReadOp : public OpKernel {\n public:\n explicit TensorArrayReadOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"dtype\", &dtype_));\n }", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, false));", " const Tensor* tensor_index;\n OP_REQUIRES_OK(ctx, ctx->input(\"index\", &tensor_index));", " OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(tensor_index->shape()),\n errors::InvalidArgument(\n \"TensorArray index must be scalar, but had shape: \",\n tensor_index->shape().DebugString()));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);", " const int32_t index = tensor_index->scalar<int32>()();\n OP_REQUIRES(\n ctx, dtype_ == tensor_array->ElemType(),\n errors::InvalidArgument(\n \"TensorArray dtype is \", DataTypeString(tensor_array->ElemType()),\n \" but Op requested dtype \", DataTypeString(dtype_), \".\"));\n Tensor value;\n Status s = tensor_array->Read<Device, T>(ctx, index, &value);\n OP_REQUIRES_OK(ctx, s);\n ctx->set_output(0, value);\n }", " private:\n DataType dtype_;\n};", "#define REGISTER_READ(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayRead\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayReadOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayReadV2\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayReadOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayReadV3\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayReadOp<CPUDevice, type>);", "TF_CALL_ALL_TYPES(REGISTER_READ)", "#undef REGISTER_READ", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayRead\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayReadOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayReadV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayReadOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayReadV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"handle\") \\\n .HostMemory(\"index\"), \\\n TensorArrayReadOp<GPUDevice, type>);", "TF_CALL_int64(REGISTER_GPU);\nTF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// PACK and GATHER ************************************************************", "// Concatenate the elements in a TensorArray. All elements must be\n// defined and have the same shape.\ntemplate <typename Device, typename T, bool LEGACY_PACK>\nclass TensorArrayPackOrGatherOp : public OpKernel {\n public:\n typedef typename TTypes<T, 2>::ConstMatrix ConstMatrix;\n typedef std::vector<std::unique_ptr<ConstMatrix> > ConstMatrixVector;", " explicit TensorArrayPackOrGatherOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"dtype\", &dtype_));\n OP_REQUIRES_OK(context, context->GetAttr(\"element_shape\", &element_shape_));\n }", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, false));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));", " core::ScopedUnref unref(tensor_array);\n OP_REQUIRES(\n ctx, dtype_ == tensor_array->ElemType(),\n errors::InvalidArgument(\n \"TensorArray dtype is \", DataTypeString(tensor_array->ElemType()),\n \" but Op requested dtype \", DataTypeString(dtype_), \".\"));", " // Ensure new element shape is compatible with the one stored in the\n // TensorArray.\n OP_REQUIRES_OK(ctx, tensor_array->SetElemShape(element_shape_));", " int32_t num_indices;\n std::vector<Tensor> values;\n std::vector<int32> indices;\n if (LEGACY_PACK) {\n OP_REQUIRES_OK(ctx, tensor_array->PackOrConcatSize(&num_indices));\n indices.resize(num_indices);\n std::iota(indices.begin(), indices.end(), 0);\n } else {\n const Tensor* tensor_indices;\n OP_REQUIRES_OK(ctx, ctx->input(\"indices\", &tensor_indices));\n OP_REQUIRES(ctx, TensorShapeUtils::IsVector(tensor_indices->shape()),\n errors::InvalidArgument(\n \"Expected indices to be a vector, but received shape: \",\n tensor_indices->shape().DebugString()));\n const auto indices_t = tensor_indices->vec<int32>();\n num_indices = tensor_indices->NumElements();\n indices.resize(num_indices);\n std::copy(indices_t.data(), indices_t.data() + num_indices,\n indices.begin());\n }", " // If there are no elements to return, return a zero-element Tensor with\n // shape [0] + element_shape_\n if (num_indices == 0) {\n OP_REQUIRES(ctx, element_shape_.IsFullyDefined(),\n errors::Unimplemented(\n \"TensorArray has size zero, but element shape \",\n element_shape_.DebugString(),\n \" is not fully defined. \"\n \"Currently only static shapes are supported when packing \"\n \"zero-size TensorArrays.\"));\n TensorShape empty_shape;\n element_shape_.AsTensorShape(&empty_shape);\n empty_shape.InsertDim(0, 0);\n Tensor* empty_unused;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, empty_shape, &empty_unused));\n return;\n }", " // Read all the Tensors into a vector to keep track of their memory.\n Status s = tensor_array->ReadMany<Device, T>(ctx, indices, &values);\n OP_REQUIRES_OK(ctx, s);", " const Tensor* value_0_t = &values[0];", " OP_REQUIRES(\n ctx, element_shape_.IsCompatibleWith(value_0_t->shape()),\n errors::InvalidArgument(\"TensorArray was passed element_shape \",\n element_shape_.DebugString(),\n \" which does not match the Tensor at index 0: \",\n value_0_t->shape().DebugString()));", " TensorShape output_shape(value_0_t->shape());\n output_shape.InsertDim(0, num_indices);", " Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape, &output_tensor));", " // If output_tensor is empty, there is nothing to concatenate so return it.\n if (output_shape.num_elements() == 0) {\n return;\n }", " ConstMatrixVector input_tensors_flat;\n input_tensors_flat.reserve(num_indices);\n auto output_flat =\n output_tensor->shaped<T, 2>({1, output_shape.num_elements()});", " // Insert the first value\n input_tensors_flat.push_back(MakeUnique<ConstMatrix>(\n value_0_t->shaped<T, 2>({1, value_0_t->NumElements()})));", " for (int i = 1; i < num_indices; ++i) {\n const Tensor* value_t = &values[i];\n OP_REQUIRES(\n ctx, value_0_t->shape() == value_t->shape(),\n errors::InvalidArgument(\n \"TensorArray has inconsistent shapes. Index 0 has shape: \",\n value_0_t->shape().DebugString(), \" but index \", i,\n \" has shape: \", value_t->shape().DebugString()));\n input_tensors_flat.push_back(MakeUnique<ConstMatrix>(\n value_t->shaped<T, 2>({1, value_t->NumElements()})));\n }", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n if (std::is_same<Device, GPUDevice>::value) {\n ConcatGPU<T>(ctx, input_tensors_flat, output_tensor, &output_flat);\n return;\n }\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n ConcatCPU<T>(ctx->device(), input_tensors_flat, &output_flat);\n }", " private:\n DataType dtype_;\n PartialTensorShape element_shape_;\n};", "#define REGISTER_GATHER_AND_PACK(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayPack\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayPackOrGatherOp<CPUDevice, type, true /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGather\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayPackOrGatherOp<CPUDevice, type, false /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGatherV2\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayPackOrGatherOp<CPUDevice, type, false /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGatherV3\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\"), \\\n TensorArrayPackOrGatherOp<CPUDevice, type, false /* LEGACY_PACK */>);", "TF_CALL_POD_STRING_TYPES(REGISTER_GATHER_AND_PACK);\nTF_CALL_variant(REGISTER_GATHER_AND_PACK);\nREGISTER_GATHER_AND_PACK(quint8);\nREGISTER_GATHER_AND_PACK(qint8);\nREGISTER_GATHER_AND_PACK(qint32);", "#undef REGISTER_GATHER_AND_PACK", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayPack\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayPackOrGatherOp<GPUDevice, type, true /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGather\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayPackOrGatherOp<GPUDevice, type, false /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGatherV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayPackOrGatherOp<GPUDevice, type, false /* LEGACY_PACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayGatherV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayPackOrGatherOp<GPUDevice, type, false /* LEGACY_PACK */>);", "TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "// A special GPU kernel for int32.\n// TODO(b/25387198): Also enable int32 in device memory. This kernel\n// registration requires all int32 inputs and outputs to be in host memory.\nREGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayGather\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"indices\")\n .HostMemory(\"handle\"),\n TensorArrayPackOrGatherOp<CPUDevice, int32, false /* LEGACY_PACK */>);\nREGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayGatherV2\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"indices\")\n .HostMemory(\"handle\"),\n TensorArrayPackOrGatherOp<CPUDevice, int32, false /* LEGACY_PACK */>);\nREGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayGatherV3\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"indices\")\n .HostMemory(\"handle\"),\n TensorArrayPackOrGatherOp<CPUDevice, int32, false /* LEGACY_PACK */>);", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// CONCAT *********************************************************************", "// Concatenate the elements in a TensorArray. All elements must be\n// defined and (excepting the first dimension) have the same shape.\ntemplate <typename Device, typename T>\nclass TensorArrayConcatOp : public OpKernel {\n public:\n typedef typename TTypes<T, 2>::ConstMatrix ConstMatrix;\n typedef std::vector<std::unique_ptr<ConstMatrix> > ConstMatrixVector;", " explicit TensorArrayConcatOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"dtype\", &dtype_));\n OP_REQUIRES_OK(context, context->GetAttr(\"element_shape_except0\",\n &element_shape_except0_));\n }", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, false));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n OP_REQUIRES(\n ctx, dtype_ == tensor_array->ElemType(),\n errors::InvalidArgument(\n \"TensorArray dtype is \", DataTypeString(tensor_array->ElemType()),\n \" but Op requested dtype \", DataTypeString(dtype_), \".\"));", " int32_t array_size;\n OP_REQUIRES_OK(ctx, tensor_array->PackOrConcatSize(&array_size));", " // If there are no elements, return a zero-element Tensor with\n // shape [0] + element_shape_except0_\n if (array_size == 0) {\n OP_REQUIRES(\n ctx, element_shape_except0_.IsFullyDefined(),\n errors::Unimplemented(\n \"TensorArray has size zero, but element_shape_except0 \",\n element_shape_except0_.DebugString(),\n \" is not fully defined. \"\n \"Currently only static shapes are supported when concatenating \"\n \"zero-size TensorArrays.\"));\n TensorShape empty_shape;\n element_shape_except0_.AsTensorShape(&empty_shape);\n empty_shape.InsertDim(0, 0);\n Tensor* empty_unused;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, empty_shape, &empty_unused));\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, {0}, &empty_unused));\n return;\n }", " // Read all the Tensors into a vector to keep track of their memory.\n std::vector<Tensor> values;\n std::vector<int32> indices(array_size);\n std::iota(indices.begin(), indices.end(), 0);\n Status s = tensor_array->ReadMany<Device, T>(ctx, indices, &values);\n OP_REQUIRES_OK(ctx, s);", " Tensor* lengths_tensor = nullptr;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(\n 1, TensorShape({static_cast<int64_t>(values.size())}),\n &lengths_tensor));\n auto lengths_tensor_t = lengths_tensor->vec<int64_t>();", " TensorShape output_shape;\n TensorShape output_shape_except0;\n for (std::size_t i = 0; i < values.size(); ++i) {\n TensorShape value_shape_t = values[i].shape();", " OP_REQUIRES(\n ctx, TensorShapeUtils::IsVectorOrHigher(value_shape_t),\n errors::InvalidArgument(\n \"Concat saw a scalar shape at index \", i,\n \" but requires at least vectors. Did you mean to call pack?\"));", " lengths_tensor_t(i) = value_shape_t.dim_size(0);", " TensorShape value_shape_t_except0 = value_shape_t;\n value_shape_t_except0.RemoveDim(0);\n if (i == 0) {\n output_shape = value_shape_t;\n output_shape_except0 = value_shape_t_except0;\n OP_REQUIRES(\n ctx, element_shape_except0_.IsCompatibleWith(output_shape_except0),\n errors::InvalidArgument(\n \"TensorArray was passed element_shape_except0 \",\n element_shape_except0_.DebugString(),\n \" but index 0 has (excepting dimension 0) shape: \",\n value_shape_t_except0.DebugString(), \" which does not match.\"));\n } else {\n OP_REQUIRES(ctx, output_shape_except0 == value_shape_t_except0,\n errors::InvalidArgument(\n \"TensorArray has inconsistent shapes. Index 0 has \"\n \"(excepting dimension 0) shape: \",\n output_shape_except0.DebugString(), \" but index \", i,\n \" has (excepting dimension 0) shape: \",\n value_shape_t_except0.DebugString()));\n // Store the previous maximum length as the offset for this tensor.\n output_shape.set_dim(\n 0, output_shape.dim_size(0) + value_shape_t.dim_size(0));\n }\n }", " Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape, &output_tensor));\n ConstMatrixVector input_tensors_flat;\n input_tensors_flat.reserve(values.size());\n for (size_t i = 0; i < values.size(); ++i) {\n const Tensor* value_t = &values[i];\n if (value_t->NumElements() > 0) {\n input_tensors_flat.push_back(MakeUnique<ConstMatrix>(\n value_t->shaped<T, 2>({1, value_t->NumElements()})));\n }\n }", " if (output_shape.num_elements() > 0) {\n auto output_flat =\n output_tensor->shaped<T, 2>({1, output_shape.num_elements()});\n#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n if (std::is_same<Device, GPUDevice>::value) {\n ConcatGPU<T>(ctx, input_tensors_flat, output_tensor, &output_flat);\n return;\n }\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n ConcatCPU<T>(ctx->device(), input_tensors_flat, &output_flat);\n }\n }", " private:\n DataType dtype_;\n PartialTensorShape element_shape_except0_;\n};", "#define REGISTER_CONCAT(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcat\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV2\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<CPUDevice, type>) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV3\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<CPUDevice, type>)", "TF_CALL_POD_STRING_TYPES(REGISTER_CONCAT);\nREGISTER_CONCAT(quint8);\nREGISTER_CONCAT(qint8);\nREGISTER_CONCAT(qint32);", "#undef REGISTER_CONCAT", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcat\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<GPUDevice, type>) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"dtype\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayConcatOp<GPUDevice, type>)", "TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "// A special GPU kernel for int32.\n// TODO(b/25387198): Also enable int32 in device memory. This kernel\n// registration requires all int32 inputs and outputs to be in host memory.\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcat\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"lengths\")\n .HostMemory(\"handle\"),\n TensorArrayConcatOp<CPUDevice, int32>);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV2\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"lengths\")\n .HostMemory(\"handle\"),\n TensorArrayConcatOp<CPUDevice, int32>);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayConcatV3\")\n .Device(DEVICE_GPU)\n .TypeConstraint<int32>(\"dtype\")\n .HostMemory(\"lengths\")\n .HostMemory(\"handle\"),\n TensorArrayConcatOp<CPUDevice, int32>);", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// UNPACK and SCATTER *********************************************************", "template <typename Device, typename T, bool LEGACY_UNPACK>\nclass TensorArrayUnpackOrScatterOp : public OpKernel {\n public:\n explicit TensorArrayUnpackOrScatterOp(OpKernelConstruction* context)\n : OpKernel(context) {}", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, true));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n const Tensor* tensor_value;\n OP_REQUIRES_OK(ctx, ctx->input(\"value\", &tensor_value));\n TensorShape element_shape(tensor_value->shape());", " OP_REQUIRES(ctx,\n FastBoundsCheck(element_shape.dim_size(0),\n std::numeric_limits<int32>::max()),\n errors::InvalidArgument(\"tensor dim0 too large to unpack\"));", " OP_REQUIRES(\n ctx, tensor_value->dtype() == tensor_array->ElemType(),\n errors::InvalidArgument(\"TensorArray dtype is \",\n DataTypeString(tensor_array->ElemType()),\n \" but Op is trying to write dtype \",\n DataTypeString(tensor_value->dtype()), \".\"));\n OP_REQUIRES(ctx, element_shape.dims() > 0,\n errors::InvalidArgument(\"Input value for unpack must be at \"\n \"least a vector but received shape: \",\n element_shape.DebugString()));\n int32_t array_size;\n OP_REQUIRES_OK(ctx, tensor_array->Size(&array_size));", " int32_t max_index;\n int32_t num_values;\n std::vector<int32> write_indices;\n if (LEGACY_UNPACK) {\n num_values = element_shape.dim_size(0);\n max_index = num_values - 1;\n write_indices.resize(num_values);\n std::iota(write_indices.begin(), write_indices.end(), 0);\n } else {\n const Tensor* tensor_indices;\n OP_REQUIRES_OK(ctx, ctx->input(\"indices\", &tensor_indices));\n OP_REQUIRES(ctx, TensorShapeUtils::IsVector(tensor_indices->shape()),\n errors::InvalidArgument(\n \"Expected indices to be a vector, but received shape: \",\n tensor_indices->shape().DebugString()));\n OP_REQUIRES(ctx,\n tensor_indices->NumElements() == element_shape.dim_size(0),\n errors::InvalidArgument(\n \"Expected len(indices) == values.shape[0], but saw: \",\n tensor_indices->NumElements(), \" vs. \",\n element_shape.dim_size(0)));\n const auto indices_t = tensor_indices->vec<int32>();\n num_values = tensor_indices->NumElements();\n max_index = (num_values == 0)\n ? -1\n : *std::max_element(indices_t.data(),\n indices_t.data() + num_values);\n write_indices.resize(num_values);\n // Copy into write_indices.\n std::copy(indices_t.data(), indices_t.data() + num_values,\n write_indices.begin());\n }", " bool dynamic_size = tensor_array->HasDynamicSize();", " // If dynamic size, we may have to resize the TensorArray to fit.\n if (dynamic_size && array_size < max_index + 1) {\n array_size = static_cast<int32>(max_index + 1);\n }", " if (LEGACY_UNPACK) {\n OP_REQUIRES(\n ctx, element_shape.dim_size(0) == array_size,\n errors::InvalidArgument(\n \"Input value must have first dimension equal to the array size (\",\n element_shape.dim_size(0), \" vs. \", array_size, \")\"));\n } else {\n OP_REQUIRES(\n ctx, max_index < array_size,\n errors::InvalidArgument(\"Max scatter index must be < array size (\",\n max_index, \" vs. \", array_size, \")\"));\n }\n element_shape.RemoveDim(0);", " auto tensor_value_t = tensor_value->shaped<T, 3>(\n {1, num_values, element_shape.num_elements()});", " Eigen::DSizes<Eigen::DenseIndex, 3> indices{0, 0, 0};\n Eigen::DSizes<Eigen::DenseIndex, 3> sizes{\n 1, 1, static_cast<Eigen::DenseIndex>(element_shape.num_elements())};", " std::vector<Tensor> write_values;\n write_values.reserve(num_values);", " for (int i = 0; i < num_values; ++i) {\n Tensor tensor_value_i;\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(tensor_array->ElemType(),\n element_shape, &tensor_value_i));\n auto tensor_value_i_t =\n tensor_value_i.shaped<T, 3>({1, 1, element_shape.num_elements()});\n indices[1] = i;", " if (element_shape.num_elements() > 0) {\n functor::Split<Device, T, 3>()(ctx->eigen_device<Device>(),\n tensor_value_i_t, tensor_value_t,\n indices, sizes);\n }", " write_values.push_back(tensor_value_i);\n }", " // Record the pack size of the TensorArray.\n if (LEGACY_UNPACK) {\n OP_REQUIRES_OK(ctx, tensor_array->SetMarkedSize(array_size));\n }", " Status s = tensor_array->WriteOrAggregateMany<Device, T>(ctx, write_indices,\n &write_values);\n OP_REQUIRES_OK(ctx, s);\n }\n};", "#define REGISTER_SCATTER_AND_UNPACK(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayUnpack\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArrayUnpackOrScatterOp<CPUDevice, type, \\\n true /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatter\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArrayUnpackOrScatterOp<CPUDevice, type, \\\n false /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatterV2\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"T\"), \\\n TensorArrayUnpackOrScatterOp<CPUDevice, type, \\\n false /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatterV3\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<type>(\"T\"), \\\n TensorArrayUnpackOrScatterOp<CPUDevice, type, \\\n false /* LEGACY_UNPACK */>);", "TF_CALL_ALL_TYPES(REGISTER_SCATTER_AND_UNPACK);\n#undef REGISTER_SCATTER_AND_UNPACK", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayUnpack\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayUnpackOrScatterOp<GPUDevice, type, \\\n true /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatter\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayUnpackOrScatterOp<GPUDevice, type, \\\n false /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatterV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayUnpackOrScatterOp<GPUDevice, type, \\\n false /* LEGACY_UNPACK */>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArrayScatterV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"indices\") \\\n .HostMemory(\"handle\"), \\\n TensorArrayUnpackOrScatterOp<GPUDevice, type, \\\n false /* LEGACY_UNPACK */>);", "TF_CALL_int64(REGISTER_GPU);\nTF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// SPLIT *********************************************************************", "template <typename Device, typename T>\nclass TensorArraySplitOp : public OpKernel {\n public:\n explicit TensorArraySplitOp(OpKernelConstruction* context)\n : OpKernel(context) {}", " void Compute(OpKernelContext* ctx) override {\n OP_REQUIRES_OK(ctx, SetupFlowControlInputs(ctx, true));", " TensorArray* tensor_array = nullptr;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n const Tensor* tensor_value;\n OP_REQUIRES_OK(ctx, ctx->input(\"value\", &tensor_value));\n const Tensor* tensor_lengths;\n OP_REQUIRES_OK(ctx, ctx->input(\"lengths\", &tensor_lengths));", " OP_REQUIRES(ctx, TensorShapeUtils::IsVector(tensor_lengths->shape()),\n errors::InvalidArgument(\n \"Expected lengths to be a vector, received shape: \",\n tensor_lengths->shape().DebugString()));\n OP_REQUIRES(ctx,\n FastBoundsCheck(tensor_lengths->NumElements(),\n std::numeric_limits<int32>::max()),\n errors::InvalidArgument(\n \"Expected lengths to have < max int32 entries\"));", " int32_t num_tensors = static_cast<int32>(tensor_lengths->NumElements());\n auto tensor_lengths_t = tensor_lengths->vec<int64_t>();\n std::vector<int64_t> cumulative_lengths;\n cumulative_lengths.reserve(num_tensors);\n int64_t total_length = 0;\n for (int i = 0; i < num_tensors; ++i) {\n total_length += tensor_lengths_t(i);\n cumulative_lengths.push_back(total_length);\n }", " OP_REQUIRES(\n ctx, TensorShapeUtils::IsVectorOrHigher(tensor_value->shape()),\n errors::InvalidArgument(\n \"Expected value to be at least a vector, but received shape: \",\n tensor_value->shape().DebugString()));", " OP_REQUIRES(\n ctx, total_length == tensor_value->shape().dim_size(0),\n errors::InvalidArgument(\"Expected sum of lengths to be equal to \"\n \"values.shape[0], but sum of lengths is \",\n total_length, \" and value's shape is: \",\n tensor_value->shape().DebugString()));\n int64_t elements_per_row =\n (total_length == 0) ? 0 : (tensor_value->NumElements() / total_length);", " int32_t array_size;\n OP_REQUIRES_OK(ctx, tensor_array->Size(&array_size));\n bool dynamic_size = tensor_array->HasDynamicSize();", " std::vector<TensorShape> element_shapes(num_tensors, tensor_value->shape());\n for (int32_t i = 0; i < num_tensors; ++i) {\n element_shapes[i].set_dim(0, tensor_lengths_t(i));\n }", " // If dynamic size, we may have to resize the TensorArray to fit.\n if (dynamic_size && array_size < num_tensors) {\n array_size = num_tensors;\n }", " OP_REQUIRES(\n ctx, array_size == num_tensors,\n errors::InvalidArgument(\n \"TensorArray's size is not equal to the size of lengths (\",\n array_size, \" vs. \", num_tensors, \"), and the TensorArray is not \",\n \"marked as dynamically resizeable\"));", " OP_REQUIRES(\n ctx, tensor_value->dtype() == tensor_array->ElemType(),\n errors::InvalidArgument(\"TensorArray dtype is \",\n DataTypeString(tensor_array->ElemType()),\n \" but Op is trying to write dtype \",\n DataTypeString(tensor_value->dtype()), \".\"));", " auto tensor_value_t =\n tensor_value->shaped<T, 3>({1, total_length, elements_per_row});", " std::vector<Tensor> write_values;\n write_values.reserve(array_size);", " for (int i = 0; i < array_size; ++i) {\n Tensor tensor_value_i;", " int64_t previous_length = (i == 0) ? 0 : cumulative_lengths[i - 1];\n Eigen::DSizes<Eigen::DenseIndex, 3> indices{\n 0, static_cast<Eigen::DenseIndex>(previous_length), 0};\n Eigen::DSizes<Eigen::DenseIndex, 3> sizes{\n 1, static_cast<Eigen::DenseIndex>(tensor_lengths_t(i)),\n static_cast<Eigen::DenseIndex>(elements_per_row)};", " OP_REQUIRES_OK(\n ctx, ctx->allocate_temp(tensor_array->ElemType(), element_shapes[i],\n &tensor_value_i));", " if (tensor_lengths_t(i) > 0) {\n auto tensor_value_i_t = tensor_value_i.shaped<T, 3>(\n {1, tensor_lengths_t(i), elements_per_row});", " functor::Split<Device, T, 3>()(ctx->eigen_device<Device>(),\n tensor_value_i_t, tensor_value_t,\n indices, sizes);\n }", " write_values.push_back(tensor_value_i);\n }", " // Record the concat size of the TensorArray.\n OP_REQUIRES_OK(ctx, tensor_array->SetMarkedSize(array_size));", " std::vector<int32> indices(array_size);\n std::iota(indices.begin(), indices.end(), 0);", " Status s = tensor_array->WriteOrAggregateMany<Device, T>(ctx, indices,\n &write_values);\n OP_REQUIRES_OK(ctx, s);\n }\n};", "#define REGISTER_SPLIT(type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArraySplit\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArraySplitOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArraySplitV2\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArraySplitOp<CPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"TensorArraySplitV3\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n TensorArraySplitOp<CPUDevice, type>);", "TF_CALL_ALL_TYPES(REGISTER_SPLIT);\n#undef REGISTER_SPLIT", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#define REGISTER_GPU(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArraySplit\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArraySplitOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArraySplitV2\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArraySplitOp<GPUDevice, type>); \\\n REGISTER_KERNEL_BUILDER(Name(\"TensorArraySplitV3\") \\\n .Device(DEVICE_GPU) \\\n .TypeConstraint<type>(\"T\") \\\n .HostMemory(\"lengths\") \\\n .HostMemory(\"handle\"), \\\n TensorArraySplitOp<GPUDevice, type>);", "TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);\nTF_CALL_COMPLEX_TYPES(REGISTER_GPU);\n#undef REGISTER_GPU", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// SIZE ***********************************************************************", "// Get the size of the TensorArray\nclass TensorArraySizeOp : public OpKernel {\n public:\n explicit TensorArraySizeOp(OpKernelConstruction* context)\n : OpKernel(context) {}", " void Compute(OpKernelContext* ctx) override {\n TensorArray* tensor_array;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &output));\n OP_REQUIRES_OK(ctx, tensor_array->Size(&(output->scalar<int32>()())));\n }\n};", "REGISTER_KERNEL_BUILDER(Name(\"TensorArraySize\").Device(DEVICE_CPU),\n TensorArraySizeOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArraySizeV2\").Device(DEVICE_CPU),\n TensorArraySizeOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArraySizeV3\").Device(DEVICE_CPU),\n TensorArraySizeOp);", "REGISTER_KERNEL_BUILDER(Name(\"TensorArraySize\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"size\"),\n TensorArraySizeOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArraySizeV2\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"size\"),\n TensorArraySizeOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArraySizeV3\")\n .Device(DEVICE_GPU)\n .HostMemory(\"handle\")\n .HostMemory(\"size\"),\n TensorArraySizeOp);", "// CLOSE\n// **********************************************************************", "// Delete the TensorArray from its resource container. This enables\n// the user to close and release the resource in the middle of a step/run.\n// TODO(ebrevdo): decide whether closing the grad op should happen\n// here or on the python side.\nclass TensorArrayCloseOp : public OpKernel {\n public:\n explicit TensorArrayCloseOp(OpKernelConstruction* context)\n : OpKernel(context) {}", " void Compute(OpKernelContext* ctx) override {\n TensorArray* tensor_array;\n OP_REQUIRES_OK(ctx, GetTensorArray(ctx, &tensor_array));\n core::ScopedUnref unref(tensor_array);\n // Instead of deleting this TA from the ResourceManager, we just\n // clear it away and mark it as closed. The remaining memory\n // consumed store its mutex and handle Tensor. This will be\n // cleared out at the end of the step anyway, so it's fine to keep\n // it around until the end of the step. Further calls to the\n // TensorArray will fail because TensorArray checks internally to\n // see if it is closed or not.\n tensor_array->ClearAndMarkClosed();\n }\n};", "REGISTER_KERNEL_BUILDER(Name(\"TensorArrayClose\").Device(DEVICE_CPU),\n TensorArrayCloseOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayCloseV2\").Device(DEVICE_CPU),\n TensorArrayCloseOp);\nREGISTER_KERNEL_BUILDER(Name(\"TensorArrayCloseV3\").Device(DEVICE_CPU),\n TensorArrayCloseOp);", "REGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayClose\").Device(DEVICE_GPU).HostMemory(\"handle\"),\n TensorArrayCloseOp);\nREGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayCloseV2\").Device(DEVICE_GPU).HostMemory(\"handle\"),\n TensorArrayCloseOp);\nREGISTER_KERNEL_BUILDER(\n Name(\"TensorArrayCloseV3\").Device(DEVICE_GPU).HostMemory(\"handle\"),\n TensorArrayCloseOp);", "} // namespace tensorflow" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [85, 1848], "buggy_code_start_loc": [83, 1848], "filenames": ["tensorflow/core/kernels/tensor_array_ops.cc", "tensorflow/python/kernel_tests/data_structures/tensor_array_ops_test.py"], "fixing_code_end_loc": [86, 1865], "fixing_code_start_loc": [83, 1849], "message": "TensorFlow is an open source platform for machine learning. Prior to versions 2.12.0 and 2.11.1, when `ctx->step_containter()` is a null ptr, the Lookup function will be executed with a null pointer. A fix is included in TensorFlow 2.12.0 and 2.11.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "FAC3DE54-93B4-4D6C-9648-B9D416B9770F", "versionEndExcluding": "2.12.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an open source platform for machine learning. Prior to versions 2.12.0 and 2.11.1, when `ctx->step_containter()` is a null ptr, the Lookup function will be executed with a null pointer. A fix is included in TensorFlow 2.12.0 and 2.11.1."}], "evaluatorComment": null, "id": "CVE-2023-25663", "lastModified": "2023-03-30T17:42:24.500", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-25T00:15:07.313", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/tensorflow/tensorflow/commit/239139d2ae6a81ae9ba499ad78b56d9b2931538a"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-64jg-wjww-7c5w"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/239139d2ae6a81ae9ba499ad78b56d9b2931538a"}, "type": "CWE-476"}
230
Determine whether the {function_name} code is vulnerable or not.
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a 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, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.ops.tensor_array_ops.\"\"\"", "import numpy as np", "from tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session as session_lib\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import control_flow_util\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.ops import gen_data_flow_ops\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import tensor_array_grad\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nimport tensorflow.python.ops.nn_grad # pylint: disable=unused-import\nfrom tensorflow.python.platform import test", "\ndef _make_converter(tf_dtype):\n def _converter(x):\n if tf_dtype == dtypes.string:\n # In Python3, np.str_ is unicode, while we always want bytes\n return np.asarray(x).astype(\"|S\")\n x = np.asarray(x).astype(tf_dtype.as_numpy_dtype)\n if tf_dtype.is_complex:\n # Add a non-zero imaginary component to x.\n x -= 1j * x\n return x\n return _converter", "\ndef _make_ta(size, name, dtype=dtypes.float32, infer_shape=False):\n return tensor_array_ops.TensorArray(\n dtype=dtype, tensor_array_name=name, size=size, infer_shape=infer_shape)", "\n@test_util.run_all_in_graph_and_eager_modes\n@test_util.with_control_flow_v2\nclass TensorArrayTest(test.TestCase):", " @classmethod\n def setUpClass(cls):\n super(TensorArrayTest, cls).setUpClass()\n cls._workers, _ = test.create_local_cluster(num_workers=3, num_ps=0)", " @classmethod\n def tearDownClass(cls):\n super(TensorArrayTest, cls).tearDownClass()\n session_lib.Session.reset(cls._workers[0].target)", " @test_util.run_in_graph_and_eager_modes\n def testTensorArrayWriteRead(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)", " w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [[1.0]])\n w2 = w1.write(2, -3.0)", " r0 = w2.read(0)\n r1 = w2.read(1)\n r2 = w2.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual([[4.0, 5.0]], d0)\n self.assertAllEqual([[1.0]], d1)\n self.assertAllEqual(-3.0, d2)", " def _testTensorArrayWritePack(self, tf_dtype):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=tf_dtype, tensor_array_name=\"foo\", size=3)", " convert = _make_converter(tf_dtype)", " w0 = ta.write(0, convert([[4.0, 5.0]]))\n w1 = w0.write(1, convert([[6.0, 7.0]]))\n w2 = w1.write(2, convert([[8.0, 9.0]]))", " c0 = w2.stack()", " c0 = self.evaluate(c0)\n self.assertAllEqual(\n convert([[[4.0, 5.0]], [[6.0, 7.0]], [[8.0, 9.0]]]), c0)", " def _testTensorArrayWritePackMaybeLegacy(self):\n self._testTensorArrayWritePack(dtypes.float32)\n self._testTensorArrayWritePack(dtypes.float64)\n self._testTensorArrayWritePack(dtypes.int32)\n self._testTensorArrayWritePack(dtypes.int64)\n self._testTensorArrayWritePack(dtypes.complex64)\n self._testTensorArrayWritePack(dtypes.complex128)\n self._testTensorArrayWritePack(dtypes.string)", " def testTensorArrayWritePack(self):\n self._testTensorArrayWritePackMaybeLegacy()", " def testEmptyTensorArrayPack(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)", " empty_element = np.zeros((0, 1), dtype=np.float32)\n w0 = ta.write(0, empty_element)\n w1 = w0.write(1, empty_element)\n w2 = w1.write(2, empty_element)", " c0 = w2.stack()", " c0 = self.evaluate(c0)\n self.assertAllEqual([3, 0, 1], c0.shape)", " def testTensorArrayWriteConcatInParallel(self):\n with self.session():", " def _concat_1():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.int32, size=2, infer_shape=False)\n w0 = ta.write(0, constant_op.constant([1]))\n w1 = w0.write(1, constant_op.constant([],\n shape=(0,),\n dtype=dtypes.int32))\n return w1.concat()", " def _concat_2():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.int32, size=3, infer_shape=False)\n w0 = ta.write(0, constant_op.constant([8]))\n w1 = w0.write(1, constant_op.constant([],\n shape=(0,),\n dtype=dtypes.int32))\n w2 = w1.write(2, constant_op.constant([9]))\n return w2.concat()", " def _write(index, output):\n elements = control_flow_ops.cond(\n math_ops.less(index, 3), _concat_1, _concat_2)\n return (index + 1, output.write(index, elements))", " num_iterations = 6\n init_state = (0,\n tensor_array_ops.TensorArray(\n dtype=dtypes.int32,\n size=num_iterations,\n infer_shape=False))\n _, final_state = control_flow_ops.while_loop(\n lambda i, _: i < num_iterations, _write, init_state)", " c0 = final_state.concat()", " c0 = self.evaluate(c0)\n self.assertAllEqual([1, 1, 1, 8, 9, 8, 9, 8, 9], c0)", " def _testTensorArrayWriteConcat(self, tf_dtype):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=tf_dtype, tensor_array_name=\"foo\", size=3, infer_shape=False)", " convert = _make_converter(tf_dtype)", " w0 = ta.write(0, convert([[4.0, 5.0], [104.0, 105.0], [204.0, 205.0]]))\n w1 = w0.write(1, convert([[6.0, 7.0], [106.0, 107.0]]))\n w2 = w1.write(2, convert([[8.0, 9.0]]))", " c0 = w2.concat()", " c0 = self.evaluate(c0)\n self.assertAllEqual(\n convert([[4.0, 5.0], [104.0, 105.0], [204.0, 205.0], [6.0, 7.0],\n [106.0, 107.0], [8.0, 9.0]]), c0)", " @test_util.deprecated_graph_mode_only\n def testTensorArrayWriteConcat(self):\n self._testTensorArrayWriteConcat(dtypes.float32)\n self._testTensorArrayWriteConcat(dtypes.float64)\n self._testTensorArrayWriteConcat(dtypes.int32)\n self._testTensorArrayWriteConcat(dtypes.int64)\n self._testTensorArrayWriteConcat(dtypes.complex64)\n self._testTensorArrayWriteConcat(dtypes.complex128)\n self._testTensorArrayWriteConcat(dtypes.string)", " def _testTensorArrayReadOrPackNotAllValuesAvailableFillsZeros(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n element_shape=tensor_shape.TensorShape([1, 2]))\n self.assertAllEqual([[0.0, 0.0]], self.evaluate(ta.read(0)))\n self.assertAllEqual([[[0.0, 0.0]], [[4.0, 5.0]], [[0.0, 0.0]]],\n self.evaluate(ta.write(1, [[4.0, 5.0]]).stack()))\n self.assertAllEqual([[0.0, 0.0], [4.0, 5.0], [0.0, 0.0]],\n self.evaluate(ta.write(1, [[4.0, 5.0]]).concat()))", " @test_util.run_v1_only(\"b/122324791\")\n def testTensorArrayReadOrPackNotAllValuesAvailableFillsZeros(self):\n self._testTensorArrayReadOrPackNotAllValuesAvailableFillsZeros()", " def _testTensorArrayReadOrPackNotAllValuesAvailableInferShapeFillsZeros(self):\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3)\n self.assertAllEqual(\n [[0.0, 0.0]], self.evaluate(ta.write(1, [[4.0, 5.0]]).read(0)))\n self.assertAllEqual([[[0.0, 0.0]], [[4.0, 5.0]], [[0.0, 0.0]]],\n self.evaluate(ta.write(1, [[4.0, 5.0]]).stack()))\n self.assertAllEqual([[0.0, 0.0], [4.0, 5.0], [0.0, 0.0]],\n self.evaluate(ta.write(1, [[4.0, 5.0]]).concat()))", " @test_util.run_v1_only(\"b/122324791\")\n def testTensorArrayReadOrPackNotAllValuesAvailableInferShapeFillsZeros(self):\n self._testTensorArrayReadOrPackNotAllValuesAvailableInferShapeFillsZeros()", " @test_util.run_v1_only(\"Uses placeholders\")\n def testSkipEagerTensorArrayReadUninitializedInferShapeFillsZeros(self):\n with self.cached_session() as sess:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3)\n val = array_ops.placeholder(dtypes.float32)\n self.assertAllEqual(\n [[0.0, 0.0]], sess.run(ta.write(1, val).read(0), {val: [[4.0, 5.0]]}))", " def _testTensorArrayUnpackRead(self, tf_dtype):\n with self.cached_session():\n convert = _make_converter(tf_dtype)", " ta = _make_ta(3, \"foo\", dtype=tf_dtype)\n # Unpack a vector into scalars\n w0 = ta.unstack(convert([1.0, 2.0, 3.0]))\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert(1.0), d0)\n self.assertAllEqual(convert(2.0), d1)\n self.assertAllEqual(convert(3.0), d2)", " # Unpack a matrix into vectors\n w1 = ta.unstack(convert([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]]))\n r0 = w1.read(0)\n r1 = w1.read(1)\n r2 = w1.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert([1.0, 1.1]), d0)\n self.assertAllEqual(convert([2.0, 2.1]), d1)\n self.assertAllEqual(convert([3.0, 3.1]), d2)", " # Try unpacking an empty matrix, which should not cause an error.\n w2 = ta.unstack(convert([[], [], []]))\n r0 = w2.read(0)\n r1 = w2.read(1)\n r2 = w2.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert([]), d0)\n self.assertAllEqual(convert([]), d1)\n self.assertAllEqual(convert([]), d2)", " def _testTensorArrayUnpackReadMaybeLegacy(self):\n self._testTensorArrayUnpackRead(dtypes.float32)\n self._testTensorArrayUnpackRead(dtypes.float64)\n self._testTensorArrayUnpackRead(dtypes.int32)\n self._testTensorArrayUnpackRead(dtypes.int64)\n self._testTensorArrayUnpackRead(dtypes.complex64)\n self._testTensorArrayUnpackRead(dtypes.complex128)\n self._testTensorArrayUnpackRead(dtypes.string)\n self._testTensorArrayUnpackRead(dtypes.bfloat16)", " def testTensorArrayUnpackRead(self):\n self._testTensorArrayUnpackReadMaybeLegacy()", " def _testTensorArraySplitRead(self, tf_dtype):\n with self.cached_session():\n convert = _make_converter(tf_dtype)", " # Split an empty vector\n ta = _make_ta(3, \"foo\", dtype=tf_dtype)\n lengths = constant_op.constant([0, 0, 0])\n w0 = ta.split(convert([]), lengths=lengths)\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert([]), d0)\n self.assertAllEqual(convert([]), d1)\n self.assertAllEqual(convert([]), d2)", " # Split a vector\n lengths = constant_op.constant([2, 0, 1])\n w0 = ta.split(convert([1.0, 2.0, 3.0]), lengths=lengths)\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert([1.0, 2.0]), d0)\n self.assertAllEqual(convert([]), d1)\n self.assertAllEqual(convert([3.0]), d2)", " # Split a matrix\n lengths = constant_op.constant([2, 0, 1])\n w0 = ta.split(\n convert([[1.0, 101.0], [2.0, 201.0], [3.0, 301.0]]), lengths=lengths)\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert([[1.0, 101.0], [2.0, 201.0]]), d0)\n self.assertAllEqual(convert([]).reshape(0, 2), d1)\n self.assertAllEqual(convert([[3.0, 301.0]]), d2)", " @test_util.deprecated_graph_mode_only\n def testTensorArraySplitRead(self):\n self._testTensorArraySplitRead(dtypes.float32)\n self._testTensorArraySplitRead(dtypes.float64)\n self._testTensorArraySplitRead(dtypes.int32)\n self._testTensorArraySplitRead(dtypes.int64)\n self._testTensorArraySplitRead(dtypes.complex64)\n self._testTensorArraySplitRead(dtypes.complex128)\n self._testTensorArraySplitRead(dtypes.string)\n self._testTensorArraySplitRead(dtypes.bfloat16)", " @test_util.disable_control_flow_v2(\"v2 does not support TensorArray.grad.\")\n @test_util.run_v1_only(\"v2 does not support TensorArray.grad.\")\n def testSkipEagerTensorGradArrayWriteRead(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)\n g_ta = ta.grad(\"grad\")", " w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [[1.0]])\n w2 = w1.write(2, -3.0)", " g_w0 = g_ta.write(0, [[5.0, 6.0]])\n g_w1 = g_w0.write(1, [[2.0]])\n g_w2 = g_w1.write(2, -2.0)", " r0 = w2.read(0)\n r1 = w2.read(1)\n r2 = w2.read(2)", " g_r0 = g_w2.read(0)\n g_r1 = g_w2.read(1)\n g_r2 = g_w2.read(2)", " d0, d1, d2, g_d0, g_d1, g_d2 = session.run([r0, r1, r2, g_r0, g_r1, g_r2])\n self.assertAllEqual([[4.0, 5.0]], d0)\n self.assertAllEqual([[1.0]], d1)\n self.assertAllEqual(-3.0, d2)\n self.assertAllEqual([[5.0, 6.0]], g_d0)\n self.assertAllEqual([[2.0]], g_d1)\n self.assertAllEqual(-2.0, g_d2)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradGrad(self):\n if not control_flow_util.ENABLE_CONTROL_FLOW_V2:\n self.skipTest(\"Legacy TensorArray does not support double derivatives.\")\n with self.test_session() as session:\n x = constant_op.constant(4.0)", " ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=1,\n infer_shape=False)\n w0 = ta.write(0, x)\n r0 = w0.read(0)\n y = r0 * r0", " g1 = gradients_impl.gradients(ys=[y], xs=[x])\n g2 = gradients_impl.gradients(ys=[g1], xs=[x])\n self.assertAllEqual([2.0], session.run(g2))", " @test_util.disable_control_flow_v2(\"v2 does not support TensorArray.grad.\")\n @test_util.run_v1_only(\"v2 does not support TensorArray.grad.\")\n def testSkipEagerTensorGradArrayDynamicWriteRead(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True,\n infer_shape=False)", " w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [[1.0]])\n w2 = w1.write(2, -3.0)", " g_ta = w2.grad(\"grad\") # Get gradient array here so we know the shape", " s = w2.size()\n g_s = g_ta.size()", " g_w0 = g_ta.write(0, [[5.0, 6.0]])\n g_w1 = g_w0.write(1, [[2.0]])\n g_w2 = g_w1.write(2, -2.0)", " r0 = w2.read(0)\n r1 = w2.read(1)\n r2 = w2.read(2)", " g_r0 = g_w2.read(0)\n g_r1 = g_w2.read(1)\n g_r2 = g_w2.read(2)", " d0, d1, d2, g_d0, g_d1, g_d2, vs, g_vs = session.run(\n [r0, r1, r2, g_r0, g_r1, g_r2, s, g_s])\n self.assertAllEqual([[4.0, 5.0]], d0)\n self.assertAllEqual([[1.0]], d1)\n self.assertAllEqual(-3.0, d2)\n self.assertAllEqual([[5.0, 6.0]], g_d0)\n self.assertAllEqual([[2.0]], g_d1)\n self.assertAllEqual(-2.0, g_d2)\n self.assertAllEqual(3, vs)\n self.assertAllEqual(3, g_vs)", " @test_util.disable_control_flow_v2(\"v2 does not support TensorArray.grad.\")\n @test_util.run_v1_only(\"v2 does not support TensorArray.grad.\")\n def testSkipEagerTensorGradAccessTwiceReceiveSameObject(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n g_ta_0 = ta.grad(\"grad\")\n g_ta_1 = ta.grad(\"grad\")", " with ops.control_dependencies([g_ta_0.write(0, [[4.0, 5.0]]).flow]):\n # Write with one gradient handle, read with another copy of it\n r1_0 = g_ta_1.read(0)", " t_g_ta_0, t_g_ta_1, d_r1_0 = session.run(\n [g_ta_0.handle.op, g_ta_1.handle.op, r1_0])\n self.assertAllEqual(t_g_ta_0, t_g_ta_1)\n self.assertAllEqual([[4.0, 5.0]], d_r1_0)", " def testTensorArrayWriteWrongIndexOrDataTypeFails(self):\n with self.session():\n ta = _make_ta(3, \"foo\", dtype=dtypes.float32)\n # TODO(b/129870929): Remove the last 2 checks (runtime checks) after\n # back back from preferred_dtype= to dtype= in convert_to_tensor. Also\n # restrict error check to only TypeError.\n error_msg_regex = (\n \"(\"\n \"Expected float32, got 'wrong_type_scalar' of type 'str' instead.\"\n \"|\"\n \"Cannot convert provided value to EagerTensor. Provided value: \"\n \"wrong_type_scalar Requested dtype: float\"\n \"|\"\n \"TensorArray dtype is float.* but Op is trying to write dtype string\"\n \"|\"\n \"Invalid data types; op elements string but list elements float\"\n \")\")\n with self.assertRaisesRegex((TypeError, errors.InvalidArgumentError),\n error_msg_regex):\n self.evaluate(ta.write(0, \"wrong_type_scalar\").flow)", " if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not context.executing_eagerly()):\n error_msg = \"Trying to modify element -1 in a list with 3 elements.\"\n else:\n error_msg = \"index -1\"\n with self.assertRaisesOpError(error_msg):\n self.evaluate(ta.write(-1, 3.0).flow)", " if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not context.executing_eagerly()):\n error_msg = \"Trying to modify element 3 in a list with 3 elements\"\n else:\n error_msg = (\"Tried to write to index 3 but array is not \"\n \"resizeable and size is: 3\")\n # Test reading from too large an index\n with self.assertRaisesOpError(error_msg):\n self.evaluate(ta.write(3, 3.0).flow)", " def testTensorArrayReadWrongIndexOrDataTypeFails(self):\n with self.session():\n ta = _make_ta(3, \"foo\", dtype=dtypes.float32)", " w0 = ta.write(0, [[4.0, 5.0]])", " # Test reading wrong datatype (only possible when constructing graphs).\n if (not context.executing_eagerly() and\n not control_flow_util.ENABLE_CONTROL_FLOW_V2):\n r0_bad = gen_data_flow_ops.tensor_array_read_v3(\n handle=w0.handle, index=0, dtype=dtypes.float64, flow_in=w0.flow)\n with self.assertRaisesOpError(\n \"TensorArray dtype is float but Op requested dtype double.\"):\n self.evaluate(r0_bad)", " if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not context.executing_eagerly()):\n error_msg = \"Trying to access element -1 in a list with 3 elements.\"\n else:\n error_msg = \"index -1\"\n # Test reading from a negative index, which is not allowed\n with self.assertRaisesOpError(error_msg):\n self.evaluate(ta.read(-1))", " if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not context.executing_eagerly()):\n error_msg = \"Trying to access element 3 in a list with 3 elements.\"\n else:\n error_msg = \"Tried to read from index 3 but array size is: 3\"\n # Test reading from too large an index\n with self.assertRaisesOpError(error_msg):\n self.evaluate(ta.read(3))", " @test_util.disable_control_flow_v2(\"v2 allows multiple writes.\")\n @test_util.run_v1_only(\"v2 allows multiple writes.\")\n def testSkipEagerTensorArrayWriteMultipleFails(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)", " with self.assertRaisesOpError(\n \"Could not write to TensorArray index 2 because \"\n \"it has already been written to.\"):\n self.evaluate(ta.write(2, 3.0).write(2, 3.0).flow)", " def testTensorArrayConcatIncompatibleShapesFails(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)", " w1 = ta.write(0, 3.0)\n w2 = w1.write(1, 4.0)\n w3 = w2.write(2, [3.0])", " with self.assertRaisesOpError(\n \"Concat saw a scalar shape at index 0 but requires at least vectors\"):\n self.evaluate(w3.concat())", " ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)", " w1 = ta.write(0, [3.0])\n w2 = w1.write(1, [4.0])\n w3 = w2.write(2, [[3.0]])", " # The exact error messages differ between eager execution and graph\n # construction as the former bubbles up the error from array_op.concat.\n error_msg = (\"Incompatible ranks\"\n if control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not context.executing_eagerly() else \"shape\")\n with self.assertRaisesRegex(errors.InvalidArgumentError, error_msg):\n self.evaluate(w3.concat())", " def testTensorArraySplitIncompatibleShapesFails(self):\n with self.session():\n in_eager_mode = context.executing_eagerly()\n ta = _make_ta(3, \"foo\")\n with self.assertRaisesOpError(\n r\"Expected lengths to be a vector, received shape: \\[\\]\"):\n if in_eager_mode:\n self.evaluate(ta.split([1.0, 2.0, 3.0], 1))\n else:\n lengths = array_ops.placeholder(dtypes.int64)\n ta.split([1.0, 2.0, 3.0], lengths).flow.eval(feed_dict={lengths: 1})", " error_msg = (\"Unused values in tensor. Length of tensor: 3 Values used: 1\"\n if control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not in_eager_mode else\n r\"Expected sum of lengths to be equal to values.shape\\[0\\], \"\n r\"but sum of lengths is 1 and value's shape is: \\[3\\]\")\n with self.assertRaisesOpError(error_msg):\n self.evaluate(ta.split([1.0, 2.0, 3.0], [1]).flow)", " ta = _make_ta(1, \"baz\")\n if control_flow_util.ENABLE_CONTROL_FLOW_V2 and not in_eager_mode:\n with self.assertRaisesRegex(\n ValueError, \"Shape must be at least rank 1 but is rank 0\"):\n self.evaluate(ta.split(1.0, [1]).flow)\n else:\n with self.assertRaisesOpError(\n r\"Expected value to be at least a vector, but received shape: \\[\\]\"\n ):\n self.evaluate(ta.split(1.0, [1]).flow)", " if not control_flow_util.ENABLE_CONTROL_FLOW_V2 or in_eager_mode:\n ta = _make_ta(2, \"buz\")\n with self.assertRaisesOpError(\n r\"TensorArray's size is not equal to the size of lengths \"\n r\"\\(2 vs. 1\\), and the TensorArray is not marked as \"\n r\"dynamically resizeable\"):\n self.evaluate(ta.split([1.0], [1]).flow)", " def _testTensorArrayWriteGradientAddMultipleAdds(self, dtype):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtype, tensor_array_name=\"foo\", size=3, infer_shape=False)\n ta_grad = ta.grad(\"grad\")", " c = lambda x: np.asarray(x, dtype=dtype.as_numpy_dtype)", " w0 = ta.write(2, c(3.0))\n w1 = w0.write(2, c(4.0))", " w0_grad = ta_grad.write(2, c(3.0))\n w1_grad = w0_grad.write(2, c(4.0))\n w2_grad = w1_grad.write(2, c(5.0))", " # Assert that aggregation works correctly\n self.assertAllEqual(c(12.00), w2_grad.read(2))", " # Assert that if multiple_writes_aggregate is not enabled,\n # multiple writes raise an exception.\n with self.assertRaisesOpError(\n r\"TensorArray foo_.*: Could not write to TensorArray index 2 because \"\n r\"it has already been written to.\"):\n self.evaluate(w1.flow)", " # Using differing shapes causes an exception\n wb0_grad = ta_grad.write(1, c(1.0))\n wb1_grad = wb0_grad.write(1, c([1.0]))", " with self.assertRaisesOpError(\n r\"Could not aggregate to TensorArray index 1 because the \"\n r\"existing shape is \\[\\] but the new input shape is \\[1\\]\"):\n self.evaluate(wb1_grad.flow)", " @test_util.disable_control_flow_v2(\"v2 does not support TensorArray.grad.\")\n @test_util.run_v1_only(\"v2 does not support TensorArray.grad.\")\n def testSkipEagerTensorArrayWriteGradientAddMultipleAdds(self):\n for dtype in (dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64,\n dtypes.complex64, dtypes.complex128):\n self._testTensorArrayWriteGradientAddMultipleAdds(dtype)", " @test_util.disable_control_flow_v2(\"Low level legacy TA op test.\")\n @test_util.run_v1_only(\"Low level legacy TA op test.\")\n def testSkipEagerTensorArrayGradWithShapeKnownElementShape(self):\n with self.session() as sess:\n ta = tensor_array_ops.TensorArray(\n size=3,\n dtype=dtypes.float32,\n element_shape=tensor_shape.TensorShape([2, 3]))\n handle, flow = data_flow_ops.tensor_array_grad_with_shape(\n handle=ta.handle,\n flow_in=ta.flow,\n shape_to_prepend=tensor_shape.TensorShape([4, 5]),\n source=\"source\")\n ta_grad = tensor_array_ops.TensorArray(\n dtypes.float32, handle=handle, flow=flow)\n value = array_ops.placeholder(dtypes.float32)\n ta_grad = ta_grad.write(0, value)\n read_value = ta_grad.read(0)", " # Make sure shape inference worked.\n self.assertAllEqual([None, None, 2, 3], read_value.shape.as_list())\n # Writing with wrong shape should not work.\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Could not write to TensorArray\"):\n fed_value = np.random.random([2, 3])\n sess.run(read_value, feed_dict={value: fed_value})\n # Writing with correct shape should work.\n fed_value = np.random.random([4, 5, 2, 3])\n self.assertAllClose(fed_value,\n sess.run(read_value, feed_dict={value: fed_value}))", " @test_util.disable_control_flow_v2(\"Low level legacy TA op test.\")\n @test_util.run_v1_only(\"Low level legacy TA op test.\")\n def testSkipEagerTensorArrayGradWithShapeUnknownElementShape(self):\n with self.session() as sess:\n ta = tensor_array_ops.TensorArray(\n size=3, dtype=dtypes.float32,\n element_shape=None) # Note that element_shape is unknown\n handle, flow = data_flow_ops.tensor_array_grad_with_shape(\n handle=ta.handle,\n flow_in=ta.flow,\n shape_to_prepend=tensor_shape.TensorShape([4, 5]),\n source=\"source\")\n ta_grad = tensor_array_ops.TensorArray(\n dtypes.float32, handle=handle, flow=flow)\n value = array_ops.placeholder(dtypes.float32)\n ta_grad = ta_grad.write(0, value)\n read_value = ta_grad.read(0)", " # Make sure shape inference worked.\n self.assertIsNone(read_value.shape.ndims)\n # Write with some shape and check read value.\n fed_value = np.random.random([4, 5, 7])\n self.assertAllClose(fed_value,\n sess.run(read_value, feed_dict={value: fed_value}))", " def testMultiTensorArray(self):\n with self.session():\n h1 = tensor_array_ops.TensorArray(\n size=1, dtype=dtypes.float32, tensor_array_name=\"foo\")\n w1 = h1.write(0, 4.0)\n r1 = w1.read(0)", " h2 = tensor_array_ops.TensorArray(\n size=1, dtype=dtypes.float32, tensor_array_name=\"bar\")", " w2 = h2.write(0, 5.0)\n r2 = w2.read(0)\n r = r1 + r2\n val = self.evaluate(r)\n self.assertAllClose(9.0, val)", " def _testTensorArrayGradientWriteReadType(self, dtype):\n with self.cached_session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.as_dtype(dtype),\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)", " c = lambda x: np.array(x, dtype=dtype)", " value_0 = constant_op.constant(c([[4.0, 5.0]]))\n value_1 = constant_op.constant(c(3.0))", " w0 = ta.write(0, value_0)\n w1 = w0.write(1, value_1)\n r0 = w1.read(0)\n r1 = w1.read(1)\n r0_2 = w1.read(0)", " # Test individual components' gradients\n grad_just_r0 = gradients_impl.gradients(\n ys=[r0], xs=[value_0], grad_ys=[c([[2.0, 3.0]])])\n grad_just_r0_vals = session.run(grad_just_r0)\n self.assertAllEqual(c([[2.0, 3.0]]), grad_just_r0_vals[0])", " grad_r0_r0_2 = gradients_impl.gradients(\n ys=[r0, r0_2],\n xs=[value_0],\n grad_ys=[c([[2.0, 3.0]]), c([[1.0, -1.0]])])\n grad_r0_r0_2_vals = session.run(grad_r0_r0_2)\n self.assertAllEqual(c([[3.0, 2.0]]), grad_r0_r0_2_vals[0])", " grad_just_r1 = gradients_impl.gradients(\n ys=[r1], xs=[value_1], grad_ys=[c(-2.0)])\n grad_just_r1_vals = session.run(grad_just_r1)\n self.assertAllEqual(c(-2.0), grad_just_r1_vals[0])", " # Test combined gradients\n grad = gradients_impl.gradients(\n ys=[r0, r0_2, r1],\n xs=[value_0, value_1],\n grad_ys=[c([[2.0, 3.0]]), c([[1.0, -1.0]]), c(-2.0)])\n grad_vals = session.run(grad)\n self.assertEqual(len(grad_vals), 2)\n self.assertAllEqual(c([[3.0, 2.0]]), grad_vals[0])\n self.assertAllEqual(c(-2.0), grad_vals[1])", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradientWriteRead(self):\n for dtype in (np.float32, np.float64, np.complex64, np.complex128):\n self._testTensorArrayGradientWriteReadType(dtype)", " def _testTensorArrayGradientWritePackConcatAndRead(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=2,\n clear_after_read=False)", " value_0 = constant_op.constant([-1.0, 1.0])\n value_1 = constant_op.constant([-10.0, 10.0])", " w0 = ta.write(0, value_0)\n w1 = w0.write(1, value_1)\n p0 = w1.stack()\n r0 = w1.read(0)\n s0 = w1.concat()", " # Test gradient accumulation between read(0), pack(), and concat()\n with ops.control_dependencies([p0, r0, s0]):\n grad_r = gradients_impl.gradients(\n ys=[p0, r0, s0],\n xs=[value_0, value_1],\n grad_ys=[\n [[2.0, 3.0], [4.0, 5.0]], # pack gradient\n [-0.5, 1.5], # read(0) gradient\n [20.0, 30.0, 40.0, 50.0]\n ]) # concat gradient\n grad_vals = self.evaluate(grad_r) # 2 + 2 entries", " self.assertAllClose([2.0 - 0.5 + 20.0, 3.0 + 1.5 + 30.0], grad_vals[0])\n self.assertAllEqual([4.0 + 40.0, 5.0 + 50.0], grad_vals[1])", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradientWritePackConcatAndRead(self):\n self._testTensorArrayGradientWritePackConcatAndRead()", " @test_util.disable_control_flow_v2(\"v2 does not support clear_after_read.\")\n @test_util.run_v1_only(\"v2 does not support clear_after_read.\")\n def testTensorArrayReadTwice(self):\n with self.session():\n value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])", " ta_readonce = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=2)", " w_readonce = ta_readonce.unstack(value)\n r0_readonce = w_readonce.read(0)", " with self.assertRaisesOpError(\n r\"Could not read index 0 twice because it was cleared after a \"\n r\"previous read \\(perhaps try setting clear_after_read = false\\?\\)\"):\n with ops.control_dependencies([r0_readonce]):\n self.evaluate(w_readonce.read(0))", " ta_readtwice = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=2,\n clear_after_read=False)\n w_readtwice = ta_readtwice.unstack(value)\n r0_readtwice = w_readtwice.read(0)\n with ops.control_dependencies([r0_readtwice]):\n r1_readtwice = w_readtwice.read(0)", " self.assertAllEqual([1.0, -1.0], self.evaluate(r1_readtwice))", " def _testTensorArrayGradientUnpackRead(self):\n with self.cached_session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=2,\n clear_after_read=False)", " value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])", " w = ta.unstack(value)\n r0 = w.read(0)\n r0_1 = w.read(0)\n r1 = w.read(1)", " # Test combined gradients + aggregation of read(0)\n grad = gradients_impl.gradients(\n ys=[r0, r0_1, r1],\n xs=[value],\n grad_ys=[[2.0, 3.0], [-1.5, 1.5], [4.0, 5.0]])\n grad_vals = session.run(grad)", " self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([[2.0 - 1.5, 3.0 + 1.5], [4.0, 5.0]], grad_vals[0])", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradientUnpackRead(self):\n self._testTensorArrayGradientUnpackRead()", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradientSplitConcat(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=2,\n infer_shape=False)", " value = constant_op.constant(\n [[1.0, -1.0], [10.0, -10.0], [100.0, -100.0]])", " w = ta.split(value, [2, 1])\n r = w.concat()", " # Test combined gradients\n grad = gradients_impl.gradients(\n ys=[r],\n xs=[value],\n grad_ys=[[[2.0, -2.0], [20.0, -20.0], [200.0, -200.0]]])\n grad_vals = session.run(grad)", " self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([[2.0, -2.0], [20.0, -20.0], [200.0, -200.0]],\n grad_vals[0])", " def _testTensorArrayGradientDynamicUnpackRead(self):\n with self.cached_session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True)", " value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])", " w = ta.unstack(value)\n r0 = w.read(0)\n r1 = w.read(1)", " # Test combined gradients + aggregation of read(0)\n grad = gradients_impl.gradients(\n ys=[r0, r1], xs=[value], grad_ys=[[2.0, 3.0], [4.0, 5.0]])\n grad_vals = session.run(grad)", " self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([[2.0, 3.0], [4.0, 5.0]], grad_vals[0])", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradientDynamicUnpackRead(self):\n self._testTensorArrayGradientDynamicUnpackRead()", " def testCloseTensorArray(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n self.evaluate(ta.close())", " def testSizeTensorArray(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n s = ta.size()\n self.assertAllEqual(3, self.evaluate(s))", " def testWriteCloseTensorArray(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)\n w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [3.0])\n self.evaluate(w1.close()) # Expected to run without problems", " def _testWhileLoopWritePackGradients(self, dynamic_size, dtype):\n np_dtype = dtype.as_numpy_dtype\n with self.cached_session():", " def func(v0, state0, var):\n ta = tensor_array_ops.TensorArray(\n dtype=dtype,\n tensor_array_name=\"foo\",\n size=0 if dynamic_size else 3,\n dynamic_size=dynamic_size)\n time_0 = array_ops.identity(0)", " def body(time, ta_t, state):\n sliced = array_ops.slice(\n v0, begin=array_ops.stack([time, 0]), size=[1, -1])\n sliced = array_ops.squeeze(sliced)\n out = sliced + var + state\n state += sliced\n ta_t = ta_t.write(time, out)\n return (time + 1, ta_t, state)", " (unused_0, h_final, unused_2) = control_flow_ops.while_loop(\n cond=lambda time, unused_1, unused_2: time < 3,\n body=body,\n loop_vars=(time_0, ta, state0),\n shape_invariants=(time_0.get_shape(), tensor_shape.unknown_shape(),\n tensor_shape.unknown_shape()),\n parallel_iterations=3)\n vout = h_final.stack()\n return vout", " v0 = array_ops.identity(np.arange(3 * 5, dtype=np_dtype).reshape(3, 5))\n state0 = array_ops.identity(np.array([1] * 5, dtype=np_dtype))\n init_val = np.arange(100, 105, dtype=np_dtype)\n var = variable_scope.get_variable(\n \"var\",\n shape=init_val.shape,\n dtype=np_dtype,\n initializer=init_ops.constant_initializer(init_val))", " vout = func(v0, state0, var)\n grad_val = -np.arange(3 * 5, dtype=np_dtype).reshape(3, 5)\n if context.executing_eagerly():\n grad_fn = backprop.gradients_function(func)\n v0_grad, state0_grad, var_grad = grad_fn(v0, state0, var, dy=grad_val)\n else:\n v0_grad = gradients_impl.gradients([vout], [v0], [grad_val])[0]\n state0_grad = gradients_impl.gradients([vout], [state0], [grad_val])[0]\n var_grad = gradients_impl.gradients([vout], [var], [grad_val])[0]\n self.evaluate(variables.global_variables_initializer())", " state0_t, var_t, v0_t, vout_t, v0_grad_t, var_grad_t, state0_grad_t = (\n self.evaluate(\n ([state0, var, v0, vout, v0_grad, var_grad, state0_grad])))\n just_v0_grad_t = self.evaluate(v0_grad)", " # state = [ state0 | state0 + v0[0] | state0 + v0[0] + v0[1] ]\n # vout = [ v0[0] + var + state[0] |\n # v0[1] + var + state[1] |\n # v0[2] + var + state[2] ]\n # = [ v0[0] + var + state0 |\n # v0[1] + var + state0 + v0[0] |\n # v0[2] + var + state0 + v0[0] + v0[1] ]\n #\n # d(vout[0])/d(v0) = [1 | 0 | 0 ]\n # d(vout[1])/d(v0) = [1 | 1 | 0 ]\n # d(vout[2])/d(v0) = [1 | 1 | 1 ]\n # d(vout)/d(var) = [1 | 1 | 1]\n # d(vout)/d(state0) = [ 1 | 1 | 1 ]", " state_per_time = np.array(\n [state0_t, state0_t + v0_t[0, :], state0_t + v0_t[0, :] + v0_t[1, :]])", " # Compare forward prop\n self.assertAllClose(v0_t + var_t + state_per_time, vout_t)", " # Compare backward prop\n expected_v0_grad_t = np.array([\n grad_val[0, :] + grad_val[1, :] + grad_val[2, :],\n grad_val[1, :] + grad_val[2, :], grad_val[2, :]\n ])", " self.assertAllEqual(expected_v0_grad_t, v0_grad_t)\n self.assertAllEqual(expected_v0_grad_t, just_v0_grad_t)\n self.assertAllClose(grad_val.sum(axis=0), var_grad_t)\n self.assertAllClose(grad_val.sum(axis=0), state0_grad_t)", " def testWhileLoopWritePackGradients(self):\n self._testWhileLoopWritePackGradients(\n dynamic_size=False, dtype=dtypes.float32)\n # TODO(ebrevdo): re-enable when While supports non-float32 gradients.\n # self._testWhileLoopWritePackGradients(\n # dynamic_size=False, dtype=tf.int64)", " @test_util.run_deprecated_v1\n def testSkipEagerWhileLoopDynamicWritePackGradients(self):\n self._testWhileLoopWritePackGradients(\n dynamic_size=True, dtype=dtypes.float32)", " def testGradSerialTwoLoops(self):\n with self.session():", " def loop(x):\n num_steps = 100\n acc = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n size=num_steps,\n clear_after_read=False,\n element_shape=tensor_shape.TensorShape([]))\n i = constant_op.constant(0, name=\"i\")", " c = lambda i, acc: i < 5", " def b(i, acc):\n x1 = control_flow_ops.cond(\n math_ops.equal(i, 0), lambda: x,\n lambda: math_ops.multiply(acc.read(i - 1), 2.0))\n return i + 1, acc.write(i, x1)", " i1, acc1 = control_flow_ops.while_loop(c, b, [i, acc])", " z = constant_op.constant(0.0)", " def fn(i, acc):\n return i + 1, acc.write(i, z)", " _, acc2 = control_flow_ops.while_loop(lambda i, acc: i < num_steps, fn,\n [i1, acc1])", " r = acc2.stack()\n return r", " x = constant_op.constant(2.0, name=\"x\")\n if context.executing_eagerly():\n grad = backprop.gradients_function(loop)(x)[0]\n else:\n grad = gradients_impl.gradients(loop(x), [x])[0]\n self.assertAllClose(31.0, self.evaluate(grad))", " def testShapeAfterWhileLoop(self):\n size = 10\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=size)\n _, ta = control_flow_ops.while_loop(\n lambda i, _: i < size,\n lambda i, ta: (i + 1, ta.write(i, [[0.]])), [0, ta],\n parallel_iterations=1)\n self.assertIsNotNone(ta.element_shape.dims)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerSumOfTwoReadVariablesWithoutRepeatGrad(self):\n with self.session() as session:\n a = array_ops.identity(\n np.arange(\n 3 * 5, dtype=np.float32).reshape(3, 5) + 1)\n b = array_ops.identity(\n np.arange(\n 3 * 5, dtype=np.float32).reshape(3, 5) + 1 + 3 * 5)\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)\n ta = ta.write(0, a, name=\"write_a\")\n ta = ta.write(1, b, name=\"write_b\")\n c = (\n ta.read(\n 0, name=\"read_a_0\") + # a + b\n ta.read(\n 1, name=\"read_b_0\"))\n g0 = -(np.arange(3 * 5, dtype=np.float32).reshape(3, 5) + 1)\n grad_a = gradients_impl.gradients([c], [a], [g0])[0] # d(a+b)/da = 1\n grad_b = gradients_impl.gradients([c], [b], [g0])[0] # d(a+b)/db = 1", " # Test gradients calculated individually\n grad_a_t, = session.run([grad_a])\n self.assertAllEqual(grad_a_t, g0)", " grad_b_t, = session.run([grad_b])\n self.assertAllEqual(grad_b_t, g0)", " # Test gradients calculated jointly\n joint_grad_a_t, joint_grad_b_t = session.run([grad_a, grad_b])\n self.assertAllEqual(joint_grad_a_t, g0)\n self.assertAllEqual(joint_grad_b_t, g0)", " def _grad_source_for_name(self, name):\n return tensor_array_grad._GetGradSource(constant_op.constant(0, name=name))", " @test_util.deprecated_graph_mode_only\n def testSkipEagerGetGradSource_Invalid(self):\n with self.assertRaises(ValueError):\n self._grad_source_for_name(\"\")\n with self.assertRaises(ValueError):\n self._grad_source_for_name(\"foo\")\n with self.assertRaises(ValueError):\n self._grad_source_for_name(\"foo/bar\")", " @test_util.deprecated_graph_mode_only\n def testSkipEagerGetGradSource_NoEnclosingScope(self):\n self.assertEqual(\"gradients:0\", self._grad_source_for_name(\"gradients\"))\n self.assertEqual(\"gradients_0:0\", self._grad_source_for_name(\"gradients_0\"))\n self.assertEqual(\"gradients\", self._grad_source_for_name(\"gradients/foo\"))\n self.assertEqual(\"gradients_0\",\n self._grad_source_for_name(\"gradients_0/foo\"))\n self.assertEqual(\"gradients\",\n self._grad_source_for_name(\"gradients/foo/bar\"))\n self.assertEqual(\"gradients_0\",\n self._grad_source_for_name(\"gradients_0/foo/bar\"))", " @test_util.deprecated_graph_mode_only\n def testSkipEagerGetGradSource_EnclosingScope(self):\n self.assertEqual(\"foo/gradients:0\",\n self._grad_source_for_name(\"foo/gradients\"))\n self.assertEqual(\"foo/gradients_0:0\",\n self._grad_source_for_name(\"foo/gradients_0\"))\n self.assertEqual(\"foo/gradients\",\n self._grad_source_for_name(\"foo/gradients/bar\"))\n self.assertEqual(\"foo/gradients_0\",\n self._grad_source_for_name(\"foo/gradients_0/bar\"))\n self.assertEqual(\"foo/bar/gradients\",\n self._grad_source_for_name(\"foo/bar/gradients/baz\"))\n self.assertEqual(\"foo/bar/gradients_0\",\n self._grad_source_for_name(\"foo/bar/gradients_0/baz\"))", " @test_util.deprecated_graph_mode_only\n def testSkipEagerGetGradSource_NestedUsesInnermost(self):\n self.assertEqual(\n \"foo/gradients/bar/gradients_0\",\n self._grad_source_for_name(\"foo/gradients/bar/gradients_0/baz\"))", " @test_util.deprecated_graph_mode_only\n def testSkipEagerWriteShape(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n c0 = constant_op.constant([4.0, 5.0])\n w0 = ta.write(0, c0)\n r0 = w0.read(0)\n self.assertAllEqual(c0.get_shape(), r0.get_shape())", " ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n c1 = constant_op.constant([6.0, 7.0])\n w1 = w0.write(1, c1)\n r0 = w1.read(0)\n r1 = w1.read(1)\n self.assertAllEqual(c0.get_shape(), r0.get_shape())\n self.assertAllEqual(c1.get_shape(), r1.get_shape())", " ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n c2 = constant_op.constant([4.0, 5.0, 6.0])\n with self.assertRaises(ValueError):\n w0.write(0, c2)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerPartlyUnknownShape(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=6)", " c0 = array_ops.placeholder(dtypes.float32, [None, None, None, 3])\n w0 = ta.write(0, c0)\n r0 = w0.read(0)\n self.assertAllEqual([None, None, None, 3], r0.get_shape().as_list())", " c1 = array_ops.placeholder(dtypes.float32, [None, None, None, 3])\n w1 = w0.write(1, c1)\n r1 = w1.read(0)\n self.assertAllEqual([None, None, None, 3], r1.get_shape().as_list())", " # Writing less specific shape (doesn't change type.)\n c2 = array_ops.placeholder(dtypes.float32, [None, None, None, None])\n w2 = w1.write(2, c2)\n r2 = w2.read(0)\n self.assertAllEqual([None, None, None, 3], r2.get_shape().as_list())", " # Writing more specific shape in one dimension and less specific in\n # another.\n c3 = array_ops.placeholder(dtypes.float32, [None, None, 2, None])\n w3 = w2.write(3, c3)\n r3 = w3.read(0)\n self.assertAllEqual([None, None, 2, 3], r3.get_shape().as_list())", " # Writing partly defined shape using TensorArray.scatter.\n c4 = array_ops.placeholder(dtypes.float32, [2, None, 4, 2, 3])\n w4 = w3.scatter([4, 5], c4)\n r4 = w4.read(0)\n self.assertAllEqual([None, 4, 2, 3], r4.get_shape().as_list())", " # Writing fully defined shape using TensorArray.split.\n c5 = array_ops.placeholder(dtypes.float32, [10, 4, 2, 3])\n w5 = w4.split(c5, constant_op.constant([5, 5]))\n r5 = w5.read(0)\n self.assertAllEqual([5, 4, 2, 3], r5.get_shape().as_list())", " def _testUnpackShape(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True,\n infer_shape=True)\n value = constant_op.constant(\n [[1.0, -1.0], [10.0, -10.0], [100.0, -100.0]])\n w0 = ta.unstack(value)\n r0 = w0.read(0)\n self.assertAllEqual((2,), r0.get_shape())", " c1 = constant_op.constant([4.0, 5.0])\n w1 = w0.write(3, c1)", " if not control_flow_util.ENABLE_CONTROL_FLOW_V2:\n # TensorArray v2 does not support clear_after_read.\n with self.assertRaisesOpError(\n r\"Could not read index 0 twice because it was cleared after a \"\n r\"previous read \\(perhaps try setting clear_after_read = false\\?\\)\"\n ):\n with ops.control_dependencies([r0]):\n self.evaluate(w1.read(0))", " r1 = w1.read(1)\n self.assertAllEqual(c1.get_shape(), r1.shape)", " c2 = constant_op.constant([4.0, 5.0, 6.0])\n with self.assertRaises(ValueError):\n w1.write(4, c2)", " def testUnpackShape(self):\n self._testUnpackShape()", " @test_util.deprecated_graph_mode_only\n def testSplitShape(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True,\n infer_shape=True)\n value = constant_op.constant([[1.0, -1.0], [2.0, -2.0], [3.0, -3.0]])\n w0 = ta.split(value, [1, 1, 1])\n r0 = w0.read(0)\n self.assertAllEqual((1, 2), r0.get_shape())", " ta1 = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo1\",\n size=0,\n dynamic_size=True,\n infer_shape=True)\n w0 = ta1.split(value, [1, 2])\n r0 = w0.read(0)\n if context.executing_eagerly():\n self.assertEqual((1, 2), r0.get_shape())\n self.assertEqual((2, 2), w0.read(1).get_shape())\n else:\n self.assertEqual(r0.get_shape().ndims, None)\n if not control_flow_util.ENABLE_CONTROL_FLOW_V2:\n self.assertEqual(\n tensor_shape.TensorShape(\n ta1.handle.op.get_attr(\"element_shape\")).ndims, None)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerWriteUnknownShape(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=True)\n c0 = array_ops.placeholder(dtypes.float32)\n w0 = ta.write(0, c0)\n r0 = w0.read(0)\n self.assertAllEqual(r0.get_shape(), tensor_shape.unknown_shape())", " def _testGradientWhenNotAllComponentsRead(self):\n with self.cached_session() as session:\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)\n x = constant_op.constant([2.0, 3.0])\n w = ta.unstack(x)\n r0 = w.read(0)\n # calculate (dr0/dx0, dr0/dx1). since r0 = x0, gradients are (1, 0).\n grad_r0 = gradients_impl.gradients(ys=[r0], xs=[x], grad_ys=[1.0])\n grad_r0_vals = session.run(grad_r0)[0]\n self.assertAllEqual(grad_r0_vals, [1.0, 0.0])", " @test_util.deprecated_graph_mode_only\n def testSkipEagerGradientWhenNotAllComponentsRead(self):\n self._testGradientWhenNotAllComponentsRead()", " @test_util.deprecated_graph_mode_only\n def testSkipEagerWriteButNotAllComponentsReadGrad(self):\n with self.cached_session() as session:\n x0 = constant_op.constant(5.0)\n x1 = constant_op.constant(10.0)\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=2).write(0, x0).write(1, x1)\n r0 = ta.read(0)\n # calculate (dr0/dx0, dr0/dx1). since r0 = x0, gradients are (1, 0).\n grad_r0_x1 = gradients_impl.gradients(ys=[r0], xs=[x0, x1], grad_ys=[1.0])\n grad_r0_x1_vals = session.run(grad_r0_x1)\n self.assertAllEqual(grad_r0_x1_vals, [1.0, 0.0])", " def _testTensorArrayUnpackDynamic(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=3, dynamic_size=True)\n x = constant_op.constant([1.0, 2.0, 3.0])\n w0 = ta.unstack(x)\n w1 = w0.write(3, 4.0)\n r = w1.stack()\n self.assertAllEqual(np.array([1.0, 2.0, 3.0, 4.0]), self.evaluate(r))\n grad = gradients_impl.gradients(ys=[r], xs=[x])\n self.assertAllEqual(np.array([1.0, 1.0, 1.0]), self.evaluate(grad)[0])", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArrayUnpackDynamic(self):\n self._testTensorArrayUnpackDynamic()", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArraySplitDynamic(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=3, dynamic_size=True)\n x = constant_op.constant([1.0, 2.0, 3.0])\n w0 = ta.split(x, [1, 1, 1])\n w1 = w0.write(3, [4.0])\n r = w1.concat()\n self.assertAllEqual(np.array([1.0, 2.0, 3.0, 4.0]), self.evaluate(r))\n grad = gradients_impl.gradients(ys=[r], xs=[x])\n self.assertAllEqual(np.array([1.0, 1.0, 1.0]), self.evaluate(grad)[0])", " def testStackShape(self):", " @def_function.function\n def ta_stack():\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=3)\n x = constant_op.constant([1.0, 2.0, 3.0])\n ta = ta.write(0, x)\n t = ta.stack()\n self.assertEqual(t.shape.as_list(), [3, 3])\n return t", " ta_stack()", " def testReadShape(self):", " @def_function.function\n def ta_read():\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=3)\n x = constant_op.constant([1.0, 2.0, 3.0])\n ta = ta.write(0, x)\n t = ta.read(0)\n self.assertEqual(t.shape.as_list(), [3])\n return t", " ta_read()", " def testGatherShape(self):", " def ta_gather(indices):\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=3)\n x = constant_op.constant([1.0, 2.0, 3.0])\n ta = ta.write(0, x)\n t = ta.gather(indices)\n self.assertEqual(t.shape.as_list(), [first_dim, 3])\n return t", " # This propagates shape of `indices` when compiling ta_gather.\n ta_gather_with_known_indices_shape = def_function.function(ta_gather)\n first_dim = 1\n ta_gather_with_known_indices_shape([0])", " # Here were force the shape of `indices` to be [None] during ta_gather's\n # compilation.\n ta_gather_with_unknown_indices_shape = def_function.function(\n ta_gather,\n input_signature=[\n tensor_spec.TensorSpec(dtype=dtypes.int32, shape=[None])\n ])\n first_dim = None\n ta_gather_with_unknown_indices_shape([0])", " def _testTensorArrayEvalEmpty(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=0, dynamic_size=False, infer_shape=False)\n v2_msg = (\"Tried to stack elements of an empty list with \"\n \"non-fully-defined element_shape\")\n v1_msg = (\n \"TensorArray has size zero, but element shape <unknown> is not \"\n \"fully defined. Currently only static shapes are supported when \"\n \"packing zero-size TensorArrays.\")\n with self.assertRaisesOpError(\n v2_msg if control_flow_util.ENABLE_CONTROL_FLOW_V2 else v1_msg):\n ta.stack().eval()", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArrayEvalEmpty(self):\n self._testTensorArrayEvalEmpty()", " # this test is ill-defined for Eager mode --- unpacking an empty tensor\n # gives an empty list / there is not equivalent of \"mark_used\" in Eager\n def _testTensorArrayEvalEmptyWithDefault(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=0, dynamic_size=False, infer_shape=True)\n self.assertEqual(0, ta.size().eval())\n # Don't actually perform the pack. This stores the static shape.\n if control_flow_util.ENABLE_CONTROL_FLOW_V2:\n ta = ta.unstack(array_ops.zeros([0, 3, 5]))\n else:\n ta.unstack(array_ops.zeros([0, 3, 5])).mark_used()\n packed = ta.stack()\n concatenated = ta.concat()\n self.assertAllEqual([0, 3, 5], self.evaluate(packed).shape)\n # Concatenating zero tensors along their first dimension gives a\n # first dimension of zero\n self.assertAllEqual([0, 5], self.evaluate(concatenated).shape)", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArrayEvalEmptyWithDefault(self):\n self._testTensorArrayEvalEmptyWithDefault()", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArrayScatterReadAndGradients(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True)", " indices = constant_op.constant([1, 8])\n value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])", " w = ta.scatter(indices, value)\n r0 = w.read(1)\n r1 = w.read(8)", " # Test combined gradients + aggregation of read(0)\n grad = gradients_impl.gradients(\n ys=[r0, r1], xs=[value], grad_ys=[[2.0, 3.0], [4.0, 5.0]])\n read_vals, grad_vals = session.run([[r0, r1], grad])", " self.assertEqual(len(read_vals), 2)\n self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([1.0, -1.0], read_vals[0])\n self.assertAllEqual([10.0, -10.0], read_vals[1])\n self.assertAllEqual([[2.0, 3.0], [4.0, 5.0]], grad_vals[0])", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArrayScatterPartialReadAndGradients(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True)", " indices = constant_op.constant([1, 8])\n value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])", " w = ta.scatter(indices, value)\n r0 = w.read(1)", " # Test combined gradients + aggregation of read(0)\n grad = gradients_impl.gradients(\n ys=[r0], xs=[value], grad_ys=[[2.0, 3.0]])[0]\n read_val, grad_val = session.run([r0, grad])", " self.assertAllEqual([1.0, -1.0], read_val)\n self.assertAllEqual([[2.0, 3.0], [0.0, 0.0]], grad_val)", " def testScatterIntoExistingList(self):\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=5)", " ta = ta.scatter(indices=[3, 4], value=array_ops.ones([2]))\n self.assertAllEqual(ta.stack(), [0., 0., 0., 1., 1.])", " ta = ta.scatter(indices=[1], value=array_ops.ones([1]))\n self.assertAllEqual(ta.stack(), [0., 1., 0., 1., 1.])", " ta = ta.scatter(indices=[0, 2], value=[5., 6.])\n self.assertAllEqual(ta.stack(), [5., 1., 6., 1., 1.])", " @test_util.run_v1_only(\"b/118890905\")\n def testTensorArrayWriteGatherAndGradients(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True)", " def func(values):\n indices = constant_op.constant([1, 8])\n w = ta.unstack(values)\n g = w.gather(indices)\n return g", " values = constant_op.constant([[1.0 * x, -1.0 * x] for x in range(10)])\n g = func(values)\n grad_ys = [[[2.0, 3.0], [4.0, 5.0]]]\n # Test combined gradients + aggregation of read(0)\n if context.executing_eagerly():\n g_vals = [g]\n grad_vals = backprop.gradients_function(func)(\n values, dy=constant_op.constant(grad_ys[0], dtype=dtypes.float32))\n else:\n grad = gradients_impl.gradients(ys=[g], xs=[values], grad_ys=grad_ys)\n g_vals, grad_vals = session.run([[g], grad])", " # Gradients for 8 of the 10 unread components are zero.\n expected_grad = np.zeros((10, 2))\n expected_grad[1] = [2.0, 3.0]\n expected_grad[8] = [4.0, 5.0]", " self.assertEqual(len(g_vals), 1)\n self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([[1.0, -1.0], [8.0, -8.0]], g_vals[0])\n self.assertAllEqual(expected_grad, grad_vals[0])", " @test_util.disable_control_flow_v2(\"colocate_with not supported in v2.\")\n @test_util.run_v1_only(\"b/120545219\")\n def testSkipEagerTensorArrayGetsDeviceFromFirstWrite(self):\n with ops.device(\"/job:worker/task:0/cpu:0\"):\n # this initial device will be ignored.\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)\n with ops.device(\"/job:worker/task:1/cpu:0\"):\n # the first write sets the op's device.\n ta = ta.write(0, 1.0)\n with ops.device(\"/job:worker/task:2/cpu:0\"):\n # subsequent writes do not modify the op's device.\n ta = ta.write(1, 1.0)", " # The gradient TA will sit on the same device as the forward TA.\n ta_grad = ta.grad(\"grad\")\n flows = [ta.flow, ta_grad.flow]", " # Similar tests for unpack and split\n with ops.device(\"/job:worker/task:0/cpu:0\"):\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=3)\n with ops.device(\"/job:worker/task:1/cpu:0\"):\n ta = ta.unstack([1.0, 2.0])\n with ops.device(\"/job:worker/task:2/cpu:0\"):\n ta = ta.write(2, 3.0)\n flows.append(ta.flow)", " with ops.device(\"/job:worker/task:0/cpu:0\"):\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)\n with ops.device(\"/job:worker/task:1/cpu:0\"):\n ta = ta.split([1.0, 2.0], [1, 1])\n flows.append(ta.flow)", " session = session_lib.Session(self._workers[0].target)", " run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE)\n run_metadata = config_pb2.RunMetadata()", " session.run(flows, options=run_options, run_metadata=run_metadata)\n self.assertTrue(run_metadata.HasField(\"step_stats\"))\n dev_stats = {d.device: d.node_stats\n for d in run_metadata.step_stats.dev_stats}\n for d in dev_stats:\n if \"/task:1/\" in d:\n self.assertTrue(\n [s for s in dev_stats[d] if \"/TensorArray\" in s.node_name])\n elif \"/host:CPU\" not in d:\n self.assertFalse(\n [s for s in dev_stats[d] if \"/TensorArray\" in s.node_name])", " @test_util.disable_control_flow_v2(\"colocate_with not supported in v2.\")\n @test_util.run_v1_only(\"b/120545219\")\n def testSkipEagerTensorArrayGetsDeviceFromFirstWriteInWhileLoop(self):\n with ops.device(\"/job:worker/task:0/cpu:0\"):\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)", " def _body(i, ta_i):\n with ops.device(\"/job:worker/task:1/cpu:0\"):\n return i + 1, ta_i.write(i, constant_op.constant(0.0))", " _, ta_out = control_flow_ops.while_loop(\n lambda i, ta: i < 2, _body, loop_vars=[0, ta])", " session = session_lib.Session(self._workers[0].target)", " run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE)\n run_metadata = config_pb2.RunMetadata()", " session.run(ta_out.flow, options=run_options, run_metadata=run_metadata)\n self.assertTrue(run_metadata.HasField(\"step_stats\"))\n dev_stats = {d.device: d.node_stats\n for d in run_metadata.step_stats.dev_stats}\n for d in dev_stats:\n if \"/task:1/\" in d:\n self.assertTrue(\n [s for s in dev_stats[d] if \"TensorArray\" == s.node_name])\n else:\n self.assertFalse(\n [s for s in dev_stats[d] if \"TensorArray\" == s.node_name])", " @test_util.disable_control_flow_v2(\"colocate_with not supported in v2.\")\n @test_util.run_v1_only(\"b/120545219\")\n def testSkipEagerTensorArrayDisabledColocateWithFirstWriteCall(self):\n with ops.device(\"/job:worker/task:0/cpu:0\"):\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=2, colocate_with_first_write_call=False)", " def _body(i, ta_i):\n with ops.device(\"/job:worker/task:1/cpu:0\"):\n return i + 1, ta_i.write(i, constant_op.constant(0.0))", " _, ta_out = control_flow_ops.while_loop(\n lambda i, ta: i < 2, _body, loop_vars=[0, ta])", " session = session_lib.Session(self._workers[0].target)", " run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE)\n run_metadata = config_pb2.RunMetadata()", " session.run(ta_out.flow, options=run_options, run_metadata=run_metadata)\n self.assertTrue(run_metadata.HasField(\"step_stats\"))\n dev_stats = {d.device: list(d.node_stats)\n for d in run_metadata.step_stats.dev_stats}\n for d in dev_stats:\n if \"/task:0/\" in d and \"CPU\" in d: # Skip any GPU node stats\n self.assertTrue(\n [s for s in dev_stats[d] if \"TensorArray\" == s.node_name])\n else:\n self.assertFalse(\n [s for s in dev_stats[d] if \"TensorArray\" == s.node_name])", " def testTensorArrayIdentity(self):\n with self.session():\n ta0 = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2,\n infer_shape=False)\n ta1 = tensor_array_ops.TensorArray(dtype=dtypes.int32, size=4,\n infer_shape=True)", " ta0 = ta0.write(0, 0.)\n ta1 = ta1.write(0, 1)", " v0 = variable_scope.get_variable(\n \"v0\", shape=(), initializer=init_ops.zeros_initializer())\n v1 = variable_scope.get_variable(\n \"v1\", shape=(), initializer=init_ops.zeros_initializer())", " with ops.control_dependencies([v0.assign_add(1)]):\n ta0 = ta0.identity()", " with ops.control_dependencies([v1.assign_add(1)]):\n ta1 = ta1.identity()", " read0 = ta0.read(0)\n read1 = ta1.read(0)", " size0 = ta0.size()\n size1 = ta1.size()", " # Tests correct properties on new TensorArrays.\n self.assertEqual(dtypes.float32, ta0.dtype)\n self.assertEqual(dtypes.int32, ta1.dtype)\n if context.executing_eagerly():\n self.assertEqual(tensor_shape.TensorShape([]), read0.get_shape())\n else:\n self.assertEqual(tensor_shape.unknown_shape(), read0.get_shape())\n self.assertEqual(tensor_shape.TensorShape([]), read1.get_shape())", " if not context.executing_eagerly():\n self.evaluate(variables.global_variables_initializer())", " read0_v, read1_v, size0_v, size1_v = self.evaluate((read0, read1, size0,\n size1))", " # Tests that the control dependencies was added and executed.\n self.assertEqual(1, self.evaluate(v0))\n self.assertEqual(1, self.evaluate(v1))", " # Tests correct TensorArray.\n self.assertEqual(read0_v, 0)\n self.assertEqual(read1_v, 1)\n self.assertEqual(size0_v, 2)\n self.assertEqual(size1_v, 4)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradYsInCorrectScope(self):\n n_time = 1\n n_dim = 1\n x = constant_op.constant([[1.42]])\n dy = constant_op.constant([[2.42]])", " ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=n_time, element_shape=[n_dim])\n for t in range(n_time):\n ta = ta.write(index=t, value=x[t])\n y = ta.stack()\n # dy is outside of the gradients name scope; tf.gradients must\n # wrap it in the correct name scope.\n dx, = gradients_impl.gradients(ys=[y], xs=[x], grad_ys=[dy])\n with self.cached_session():\n vdx, vdy = self.evaluate([dx, dy])\n self.assertAllClose(vdx, vdy)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayInt64GPU(self):\n if not test.is_gpu_available():\n return\n with self.session(force_gpu=True) as sess:\n value = array_ops.placeholder(dtypes.int64)\n ta = tensor_array_ops.TensorArray(dtype=dtypes.int64, size=2)\n ta = ta.scatter([0, 1], value)\n r0 = ta.read(0)\n r1 = ta.read(1)\n v0, v1 = sess.run([r0, r1], feed_dict={value: [-3, 100]})\n self.assertAllEqual(v0, -3)\n self.assertAllEqual(v1, 100)", " @test_util.deprecated_graph_mode_only\n def testTensorArrayScatterBfloat16GPU(self):\n if not test.is_gpu_available():\n return\n with self.session(force_gpu=True) as sess:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.bfloat16, tensor_array_name=\"foo\", size=5)\n ta = ta.scatter(\n indices=[3, 4], value=array_ops.ones([2], dtype=dtypes.bfloat16))\n self.assertAllEqual(ta.stack(), [0., 0., 0., 1., 1.])", " def testInferShapeFalseValid(self):\n ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=3, infer_shape=False, element_shape=[None, 10, 20])\n ta = ta.write(0, array_ops.ones([50, 10, 20]))\n ta = ta.write(1, array_ops.ones([50, 10, 20]))\n ta = ta.write(2, array_ops.ones([1, 10, 20]))\n ta = ta.concat()", " correct = np.ones([101, 10, 20])", " self.assertAllEqual(ta, correct)", " def testInferShapeFalseInvalid(self):\n ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=2, infer_shape=False, element_shape=[None, 10, 20])\n ta = ta.write(0, array_ops.ones([50, 10, 20]))", " with self.assertRaises(ValueError):\n ta = ta.write(1, array_ops.ones([1, 20, 20]))", " def testInferShapeTrue(self):\n ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=3, infer_shape=True, element_shape=[None, 10, 20])\n self.assertAllEqual((None, 10, 20), ta.element_shape.as_list())\n ta = ta.write(0, array_ops.ones([50, 10, 20]))\n self.assertAllEqual((50, 10, 20), ta.element_shape.as_list())\n ta = ta.write(1, array_ops.ones([50, 10, 20]))\n with self.assertRaises(ValueError):\n ta = ta.write(\n 2, array_ops.ones([1, 10, 20])\n ) # Inconsistent shapes: saw (1, 10, 20) but expected (50, 10, 20)", " def testStackShapeOnEmpty(self):\n ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=0, element_shape=(5, 10), dynamic_size=True)\n self.assertAllEqual([0, 5, 10], self.evaluate(ta.stack()).shape)", " @test_util.run_deprecated_v1\n def testSkipEagerStackOnPartiallyDefinedShape(self):\n ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=0, element_shape=(5, None), dynamic_size=True)\n self.assertEqual([None, 5, None], ta.stack().shape.as_list())", " def testStackShapeOnStaticSize(self):\n ta = tensor_array_ops.TensorArray(dtypes.float32, size=42)\n ta = ta.write(0, [0])\n self.assertEqual([42, 1], ta.stack().shape.as_list())\n", "", "\nclass TensorArrayBenchmark(test.Benchmark):", " def _tensorArrayWriteInWhile(self):\n size = 10000\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=size)\n (_, ta) = control_flow_ops.while_loop(\n lambda i, _: i < size,\n lambda i, ta: (i + 1, ta.write(i, 0.)), [0, ta],\n parallel_iterations=1)\n return ta.stack()", " def _benchmarkWriteInWhile(self):\n ops.reset_default_graph()\n op = self._tensorArrayWriteInWhile()\n self.run_op_benchmark(session_lib.Session(), op)", " def benchmarkWriteInWhile(self):\n self._benchmarkWriteInWhile()", " @test_util.enable_control_flow_v2\n def benchmarkWriteInWhileWithControlFlowV2(self):\n self._benchmarkWriteInWhile()", " def benchmarkWriteInDatasetMapFn(self):\n ds = dataset_ops.Dataset.from_tensors(array_ops.zeros([10])).repeat()\n ds = ds.map(lambda _: self._tensorArrayWriteInWhile())\n op = ds.make_one_shot_iterator().get_next()\n self.run_op_benchmark(session_lib.Session(), op)", " def benchmarkWriteInDatasetParallelMapFn(self):\n ds = dataset_ops.Dataset.from_tensors(array_ops.zeros([10])).repeat()\n ds = ds.map(lambda _: self._tensorArrayWriteInWhile(), num_parallel_calls=2)\n op = ds.make_one_shot_iterator().get_next()\n self.run_op_benchmark(session_lib.Session(), op)", "\nif __name__ == \"__main__\":\n test.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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
PreciseBugs
{"buggy_code_end_loc": [85, 1848], "buggy_code_start_loc": [83, 1848], "filenames": ["tensorflow/core/kernels/tensor_array_ops.cc", "tensorflow/python/kernel_tests/data_structures/tensor_array_ops_test.py"], "fixing_code_end_loc": [86, 1865], "fixing_code_start_loc": [83, 1849], "message": "TensorFlow is an open source platform for machine learning. Prior to versions 2.12.0 and 2.11.1, when `ctx->step_containter()` is a null ptr, the Lookup function will be executed with a null pointer. A fix is included in TensorFlow 2.12.0 and 2.11.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "FAC3DE54-93B4-4D6C-9648-B9D416B9770F", "versionEndExcluding": "2.12.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an open source platform for machine learning. Prior to versions 2.12.0 and 2.11.1, when `ctx->step_containter()` is a null ptr, the Lookup function will be executed with a null pointer. A fix is included in TensorFlow 2.12.0 and 2.11.1."}], "evaluatorComment": null, "id": "CVE-2023-25663", "lastModified": "2023-03-30T17:42:24.500", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-25T00:15:07.313", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/tensorflow/tensorflow/commit/239139d2ae6a81ae9ba499ad78b56d9b2931538a"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-64jg-wjww-7c5w"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/239139d2ae6a81ae9ba499ad78b56d9b2931538a"}, "type": "CWE-476"}
230
Determine whether the {function_name} code is vulnerable or not.
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a 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, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.ops.tensor_array_ops.\"\"\"", "import numpy as np", "from tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session as session_lib\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import control_flow_util\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.ops import gen_data_flow_ops\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import tensor_array_grad\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nimport tensorflow.python.ops.nn_grad # pylint: disable=unused-import\nfrom tensorflow.python.platform import test", "\ndef _make_converter(tf_dtype):\n def _converter(x):\n if tf_dtype == dtypes.string:\n # In Python3, np.str_ is unicode, while we always want bytes\n return np.asarray(x).astype(\"|S\")\n x = np.asarray(x).astype(tf_dtype.as_numpy_dtype)\n if tf_dtype.is_complex:\n # Add a non-zero imaginary component to x.\n x -= 1j * x\n return x\n return _converter", "\ndef _make_ta(size, name, dtype=dtypes.float32, infer_shape=False):\n return tensor_array_ops.TensorArray(\n dtype=dtype, tensor_array_name=name, size=size, infer_shape=infer_shape)", "\n@test_util.run_all_in_graph_and_eager_modes\n@test_util.with_control_flow_v2\nclass TensorArrayTest(test.TestCase):", " @classmethod\n def setUpClass(cls):\n super(TensorArrayTest, cls).setUpClass()\n cls._workers, _ = test.create_local_cluster(num_workers=3, num_ps=0)", " @classmethod\n def tearDownClass(cls):\n super(TensorArrayTest, cls).tearDownClass()\n session_lib.Session.reset(cls._workers[0].target)", " @test_util.run_in_graph_and_eager_modes\n def testTensorArrayWriteRead(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)", " w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [[1.0]])\n w2 = w1.write(2, -3.0)", " r0 = w2.read(0)\n r1 = w2.read(1)\n r2 = w2.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual([[4.0, 5.0]], d0)\n self.assertAllEqual([[1.0]], d1)\n self.assertAllEqual(-3.0, d2)", " def _testTensorArrayWritePack(self, tf_dtype):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=tf_dtype, tensor_array_name=\"foo\", size=3)", " convert = _make_converter(tf_dtype)", " w0 = ta.write(0, convert([[4.0, 5.0]]))\n w1 = w0.write(1, convert([[6.0, 7.0]]))\n w2 = w1.write(2, convert([[8.0, 9.0]]))", " c0 = w2.stack()", " c0 = self.evaluate(c0)\n self.assertAllEqual(\n convert([[[4.0, 5.0]], [[6.0, 7.0]], [[8.0, 9.0]]]), c0)", " def _testTensorArrayWritePackMaybeLegacy(self):\n self._testTensorArrayWritePack(dtypes.float32)\n self._testTensorArrayWritePack(dtypes.float64)\n self._testTensorArrayWritePack(dtypes.int32)\n self._testTensorArrayWritePack(dtypes.int64)\n self._testTensorArrayWritePack(dtypes.complex64)\n self._testTensorArrayWritePack(dtypes.complex128)\n self._testTensorArrayWritePack(dtypes.string)", " def testTensorArrayWritePack(self):\n self._testTensorArrayWritePackMaybeLegacy()", " def testEmptyTensorArrayPack(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)", " empty_element = np.zeros((0, 1), dtype=np.float32)\n w0 = ta.write(0, empty_element)\n w1 = w0.write(1, empty_element)\n w2 = w1.write(2, empty_element)", " c0 = w2.stack()", " c0 = self.evaluate(c0)\n self.assertAllEqual([3, 0, 1], c0.shape)", " def testTensorArrayWriteConcatInParallel(self):\n with self.session():", " def _concat_1():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.int32, size=2, infer_shape=False)\n w0 = ta.write(0, constant_op.constant([1]))\n w1 = w0.write(1, constant_op.constant([],\n shape=(0,),\n dtype=dtypes.int32))\n return w1.concat()", " def _concat_2():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.int32, size=3, infer_shape=False)\n w0 = ta.write(0, constant_op.constant([8]))\n w1 = w0.write(1, constant_op.constant([],\n shape=(0,),\n dtype=dtypes.int32))\n w2 = w1.write(2, constant_op.constant([9]))\n return w2.concat()", " def _write(index, output):\n elements = control_flow_ops.cond(\n math_ops.less(index, 3), _concat_1, _concat_2)\n return (index + 1, output.write(index, elements))", " num_iterations = 6\n init_state = (0,\n tensor_array_ops.TensorArray(\n dtype=dtypes.int32,\n size=num_iterations,\n infer_shape=False))\n _, final_state = control_flow_ops.while_loop(\n lambda i, _: i < num_iterations, _write, init_state)", " c0 = final_state.concat()", " c0 = self.evaluate(c0)\n self.assertAllEqual([1, 1, 1, 8, 9, 8, 9, 8, 9], c0)", " def _testTensorArrayWriteConcat(self, tf_dtype):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=tf_dtype, tensor_array_name=\"foo\", size=3, infer_shape=False)", " convert = _make_converter(tf_dtype)", " w0 = ta.write(0, convert([[4.0, 5.0], [104.0, 105.0], [204.0, 205.0]]))\n w1 = w0.write(1, convert([[6.0, 7.0], [106.0, 107.0]]))\n w2 = w1.write(2, convert([[8.0, 9.0]]))", " c0 = w2.concat()", " c0 = self.evaluate(c0)\n self.assertAllEqual(\n convert([[4.0, 5.0], [104.0, 105.0], [204.0, 205.0], [6.0, 7.0],\n [106.0, 107.0], [8.0, 9.0]]), c0)", " @test_util.deprecated_graph_mode_only\n def testTensorArrayWriteConcat(self):\n self._testTensorArrayWriteConcat(dtypes.float32)\n self._testTensorArrayWriteConcat(dtypes.float64)\n self._testTensorArrayWriteConcat(dtypes.int32)\n self._testTensorArrayWriteConcat(dtypes.int64)\n self._testTensorArrayWriteConcat(dtypes.complex64)\n self._testTensorArrayWriteConcat(dtypes.complex128)\n self._testTensorArrayWriteConcat(dtypes.string)", " def _testTensorArrayReadOrPackNotAllValuesAvailableFillsZeros(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n element_shape=tensor_shape.TensorShape([1, 2]))\n self.assertAllEqual([[0.0, 0.0]], self.evaluate(ta.read(0)))\n self.assertAllEqual([[[0.0, 0.0]], [[4.0, 5.0]], [[0.0, 0.0]]],\n self.evaluate(ta.write(1, [[4.0, 5.0]]).stack()))\n self.assertAllEqual([[0.0, 0.0], [4.0, 5.0], [0.0, 0.0]],\n self.evaluate(ta.write(1, [[4.0, 5.0]]).concat()))", " @test_util.run_v1_only(\"b/122324791\")\n def testTensorArrayReadOrPackNotAllValuesAvailableFillsZeros(self):\n self._testTensorArrayReadOrPackNotAllValuesAvailableFillsZeros()", " def _testTensorArrayReadOrPackNotAllValuesAvailableInferShapeFillsZeros(self):\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3)\n self.assertAllEqual(\n [[0.0, 0.0]], self.evaluate(ta.write(1, [[4.0, 5.0]]).read(0)))\n self.assertAllEqual([[[0.0, 0.0]], [[4.0, 5.0]], [[0.0, 0.0]]],\n self.evaluate(ta.write(1, [[4.0, 5.0]]).stack()))\n self.assertAllEqual([[0.0, 0.0], [4.0, 5.0], [0.0, 0.0]],\n self.evaluate(ta.write(1, [[4.0, 5.0]]).concat()))", " @test_util.run_v1_only(\"b/122324791\")\n def testTensorArrayReadOrPackNotAllValuesAvailableInferShapeFillsZeros(self):\n self._testTensorArrayReadOrPackNotAllValuesAvailableInferShapeFillsZeros()", " @test_util.run_v1_only(\"Uses placeholders\")\n def testSkipEagerTensorArrayReadUninitializedInferShapeFillsZeros(self):\n with self.cached_session() as sess:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3)\n val = array_ops.placeholder(dtypes.float32)\n self.assertAllEqual(\n [[0.0, 0.0]], sess.run(ta.write(1, val).read(0), {val: [[4.0, 5.0]]}))", " def _testTensorArrayUnpackRead(self, tf_dtype):\n with self.cached_session():\n convert = _make_converter(tf_dtype)", " ta = _make_ta(3, \"foo\", dtype=tf_dtype)\n # Unpack a vector into scalars\n w0 = ta.unstack(convert([1.0, 2.0, 3.0]))\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert(1.0), d0)\n self.assertAllEqual(convert(2.0), d1)\n self.assertAllEqual(convert(3.0), d2)", " # Unpack a matrix into vectors\n w1 = ta.unstack(convert([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]]))\n r0 = w1.read(0)\n r1 = w1.read(1)\n r2 = w1.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert([1.0, 1.1]), d0)\n self.assertAllEqual(convert([2.0, 2.1]), d1)\n self.assertAllEqual(convert([3.0, 3.1]), d2)", " # Try unpacking an empty matrix, which should not cause an error.\n w2 = ta.unstack(convert([[], [], []]))\n r0 = w2.read(0)\n r1 = w2.read(1)\n r2 = w2.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert([]), d0)\n self.assertAllEqual(convert([]), d1)\n self.assertAllEqual(convert([]), d2)", " def _testTensorArrayUnpackReadMaybeLegacy(self):\n self._testTensorArrayUnpackRead(dtypes.float32)\n self._testTensorArrayUnpackRead(dtypes.float64)\n self._testTensorArrayUnpackRead(dtypes.int32)\n self._testTensorArrayUnpackRead(dtypes.int64)\n self._testTensorArrayUnpackRead(dtypes.complex64)\n self._testTensorArrayUnpackRead(dtypes.complex128)\n self._testTensorArrayUnpackRead(dtypes.string)\n self._testTensorArrayUnpackRead(dtypes.bfloat16)", " def testTensorArrayUnpackRead(self):\n self._testTensorArrayUnpackReadMaybeLegacy()", " def _testTensorArraySplitRead(self, tf_dtype):\n with self.cached_session():\n convert = _make_converter(tf_dtype)", " # Split an empty vector\n ta = _make_ta(3, \"foo\", dtype=tf_dtype)\n lengths = constant_op.constant([0, 0, 0])\n w0 = ta.split(convert([]), lengths=lengths)\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert([]), d0)\n self.assertAllEqual(convert([]), d1)\n self.assertAllEqual(convert([]), d2)", " # Split a vector\n lengths = constant_op.constant([2, 0, 1])\n w0 = ta.split(convert([1.0, 2.0, 3.0]), lengths=lengths)\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert([1.0, 2.0]), d0)\n self.assertAllEqual(convert([]), d1)\n self.assertAllEqual(convert([3.0]), d2)", " # Split a matrix\n lengths = constant_op.constant([2, 0, 1])\n w0 = ta.split(\n convert([[1.0, 101.0], [2.0, 201.0], [3.0, 301.0]]), lengths=lengths)\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)", " d0, d1, d2 = self.evaluate([r0, r1, r2])\n self.assertAllEqual(convert([[1.0, 101.0], [2.0, 201.0]]), d0)\n self.assertAllEqual(convert([]).reshape(0, 2), d1)\n self.assertAllEqual(convert([[3.0, 301.0]]), d2)", " @test_util.deprecated_graph_mode_only\n def testTensorArraySplitRead(self):\n self._testTensorArraySplitRead(dtypes.float32)\n self._testTensorArraySplitRead(dtypes.float64)\n self._testTensorArraySplitRead(dtypes.int32)\n self._testTensorArraySplitRead(dtypes.int64)\n self._testTensorArraySplitRead(dtypes.complex64)\n self._testTensorArraySplitRead(dtypes.complex128)\n self._testTensorArraySplitRead(dtypes.string)\n self._testTensorArraySplitRead(dtypes.bfloat16)", " @test_util.disable_control_flow_v2(\"v2 does not support TensorArray.grad.\")\n @test_util.run_v1_only(\"v2 does not support TensorArray.grad.\")\n def testSkipEagerTensorGradArrayWriteRead(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)\n g_ta = ta.grad(\"grad\")", " w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [[1.0]])\n w2 = w1.write(2, -3.0)", " g_w0 = g_ta.write(0, [[5.0, 6.0]])\n g_w1 = g_w0.write(1, [[2.0]])\n g_w2 = g_w1.write(2, -2.0)", " r0 = w2.read(0)\n r1 = w2.read(1)\n r2 = w2.read(2)", " g_r0 = g_w2.read(0)\n g_r1 = g_w2.read(1)\n g_r2 = g_w2.read(2)", " d0, d1, d2, g_d0, g_d1, g_d2 = session.run([r0, r1, r2, g_r0, g_r1, g_r2])\n self.assertAllEqual([[4.0, 5.0]], d0)\n self.assertAllEqual([[1.0]], d1)\n self.assertAllEqual(-3.0, d2)\n self.assertAllEqual([[5.0, 6.0]], g_d0)\n self.assertAllEqual([[2.0]], g_d1)\n self.assertAllEqual(-2.0, g_d2)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradGrad(self):\n if not control_flow_util.ENABLE_CONTROL_FLOW_V2:\n self.skipTest(\"Legacy TensorArray does not support double derivatives.\")\n with self.test_session() as session:\n x = constant_op.constant(4.0)", " ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=1,\n infer_shape=False)\n w0 = ta.write(0, x)\n r0 = w0.read(0)\n y = r0 * r0", " g1 = gradients_impl.gradients(ys=[y], xs=[x])\n g2 = gradients_impl.gradients(ys=[g1], xs=[x])\n self.assertAllEqual([2.0], session.run(g2))", " @test_util.disable_control_flow_v2(\"v2 does not support TensorArray.grad.\")\n @test_util.run_v1_only(\"v2 does not support TensorArray.grad.\")\n def testSkipEagerTensorGradArrayDynamicWriteRead(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True,\n infer_shape=False)", " w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [[1.0]])\n w2 = w1.write(2, -3.0)", " g_ta = w2.grad(\"grad\") # Get gradient array here so we know the shape", " s = w2.size()\n g_s = g_ta.size()", " g_w0 = g_ta.write(0, [[5.0, 6.0]])\n g_w1 = g_w0.write(1, [[2.0]])\n g_w2 = g_w1.write(2, -2.0)", " r0 = w2.read(0)\n r1 = w2.read(1)\n r2 = w2.read(2)", " g_r0 = g_w2.read(0)\n g_r1 = g_w2.read(1)\n g_r2 = g_w2.read(2)", " d0, d1, d2, g_d0, g_d1, g_d2, vs, g_vs = session.run(\n [r0, r1, r2, g_r0, g_r1, g_r2, s, g_s])\n self.assertAllEqual([[4.0, 5.0]], d0)\n self.assertAllEqual([[1.0]], d1)\n self.assertAllEqual(-3.0, d2)\n self.assertAllEqual([[5.0, 6.0]], g_d0)\n self.assertAllEqual([[2.0]], g_d1)\n self.assertAllEqual(-2.0, g_d2)\n self.assertAllEqual(3, vs)\n self.assertAllEqual(3, g_vs)", " @test_util.disable_control_flow_v2(\"v2 does not support TensorArray.grad.\")\n @test_util.run_v1_only(\"v2 does not support TensorArray.grad.\")\n def testSkipEagerTensorGradAccessTwiceReceiveSameObject(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n g_ta_0 = ta.grad(\"grad\")\n g_ta_1 = ta.grad(\"grad\")", " with ops.control_dependencies([g_ta_0.write(0, [[4.0, 5.0]]).flow]):\n # Write with one gradient handle, read with another copy of it\n r1_0 = g_ta_1.read(0)", " t_g_ta_0, t_g_ta_1, d_r1_0 = session.run(\n [g_ta_0.handle.op, g_ta_1.handle.op, r1_0])\n self.assertAllEqual(t_g_ta_0, t_g_ta_1)\n self.assertAllEqual([[4.0, 5.0]], d_r1_0)", " def testTensorArrayWriteWrongIndexOrDataTypeFails(self):\n with self.session():\n ta = _make_ta(3, \"foo\", dtype=dtypes.float32)\n # TODO(b/129870929): Remove the last 2 checks (runtime checks) after\n # back back from preferred_dtype= to dtype= in convert_to_tensor. Also\n # restrict error check to only TypeError.\n error_msg_regex = (\n \"(\"\n \"Expected float32, got 'wrong_type_scalar' of type 'str' instead.\"\n \"|\"\n \"Cannot convert provided value to EagerTensor. Provided value: \"\n \"wrong_type_scalar Requested dtype: float\"\n \"|\"\n \"TensorArray dtype is float.* but Op is trying to write dtype string\"\n \"|\"\n \"Invalid data types; op elements string but list elements float\"\n \")\")\n with self.assertRaisesRegex((TypeError, errors.InvalidArgumentError),\n error_msg_regex):\n self.evaluate(ta.write(0, \"wrong_type_scalar\").flow)", " if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not context.executing_eagerly()):\n error_msg = \"Trying to modify element -1 in a list with 3 elements.\"\n else:\n error_msg = \"index -1\"\n with self.assertRaisesOpError(error_msg):\n self.evaluate(ta.write(-1, 3.0).flow)", " if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not context.executing_eagerly()):\n error_msg = \"Trying to modify element 3 in a list with 3 elements\"\n else:\n error_msg = (\"Tried to write to index 3 but array is not \"\n \"resizeable and size is: 3\")\n # Test reading from too large an index\n with self.assertRaisesOpError(error_msg):\n self.evaluate(ta.write(3, 3.0).flow)", " def testTensorArrayReadWrongIndexOrDataTypeFails(self):\n with self.session():\n ta = _make_ta(3, \"foo\", dtype=dtypes.float32)", " w0 = ta.write(0, [[4.0, 5.0]])", " # Test reading wrong datatype (only possible when constructing graphs).\n if (not context.executing_eagerly() and\n not control_flow_util.ENABLE_CONTROL_FLOW_V2):\n r0_bad = gen_data_flow_ops.tensor_array_read_v3(\n handle=w0.handle, index=0, dtype=dtypes.float64, flow_in=w0.flow)\n with self.assertRaisesOpError(\n \"TensorArray dtype is float but Op requested dtype double.\"):\n self.evaluate(r0_bad)", " if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not context.executing_eagerly()):\n error_msg = \"Trying to access element -1 in a list with 3 elements.\"\n else:\n error_msg = \"index -1\"\n # Test reading from a negative index, which is not allowed\n with self.assertRaisesOpError(error_msg):\n self.evaluate(ta.read(-1))", " if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not context.executing_eagerly()):\n error_msg = \"Trying to access element 3 in a list with 3 elements.\"\n else:\n error_msg = \"Tried to read from index 3 but array size is: 3\"\n # Test reading from too large an index\n with self.assertRaisesOpError(error_msg):\n self.evaluate(ta.read(3))", " @test_util.disable_control_flow_v2(\"v2 allows multiple writes.\")\n @test_util.run_v1_only(\"v2 allows multiple writes.\")\n def testSkipEagerTensorArrayWriteMultipleFails(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)", " with self.assertRaisesOpError(\n \"Could not write to TensorArray index 2 because \"\n \"it has already been written to.\"):\n self.evaluate(ta.write(2, 3.0).write(2, 3.0).flow)", " def testTensorArrayConcatIncompatibleShapesFails(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)", " w1 = ta.write(0, 3.0)\n w2 = w1.write(1, 4.0)\n w3 = w2.write(2, [3.0])", " with self.assertRaisesOpError(\n \"Concat saw a scalar shape at index 0 but requires at least vectors\"):\n self.evaluate(w3.concat())", " ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)", " w1 = ta.write(0, [3.0])\n w2 = w1.write(1, [4.0])\n w3 = w2.write(2, [[3.0]])", " # The exact error messages differ between eager execution and graph\n # construction as the former bubbles up the error from array_op.concat.\n error_msg = (\"Incompatible ranks\"\n if control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not context.executing_eagerly() else \"shape\")\n with self.assertRaisesRegex(errors.InvalidArgumentError, error_msg):\n self.evaluate(w3.concat())", " def testTensorArraySplitIncompatibleShapesFails(self):\n with self.session():\n in_eager_mode = context.executing_eagerly()\n ta = _make_ta(3, \"foo\")\n with self.assertRaisesOpError(\n r\"Expected lengths to be a vector, received shape: \\[\\]\"):\n if in_eager_mode:\n self.evaluate(ta.split([1.0, 2.0, 3.0], 1))\n else:\n lengths = array_ops.placeholder(dtypes.int64)\n ta.split([1.0, 2.0, 3.0], lengths).flow.eval(feed_dict={lengths: 1})", " error_msg = (\"Unused values in tensor. Length of tensor: 3 Values used: 1\"\n if control_flow_util.ENABLE_CONTROL_FLOW_V2 and\n not in_eager_mode else\n r\"Expected sum of lengths to be equal to values.shape\\[0\\], \"\n r\"but sum of lengths is 1 and value's shape is: \\[3\\]\")\n with self.assertRaisesOpError(error_msg):\n self.evaluate(ta.split([1.0, 2.0, 3.0], [1]).flow)", " ta = _make_ta(1, \"baz\")\n if control_flow_util.ENABLE_CONTROL_FLOW_V2 and not in_eager_mode:\n with self.assertRaisesRegex(\n ValueError, \"Shape must be at least rank 1 but is rank 0\"):\n self.evaluate(ta.split(1.0, [1]).flow)\n else:\n with self.assertRaisesOpError(\n r\"Expected value to be at least a vector, but received shape: \\[\\]\"\n ):\n self.evaluate(ta.split(1.0, [1]).flow)", " if not control_flow_util.ENABLE_CONTROL_FLOW_V2 or in_eager_mode:\n ta = _make_ta(2, \"buz\")\n with self.assertRaisesOpError(\n r\"TensorArray's size is not equal to the size of lengths \"\n r\"\\(2 vs. 1\\), and the TensorArray is not marked as \"\n r\"dynamically resizeable\"):\n self.evaluate(ta.split([1.0], [1]).flow)", " def _testTensorArrayWriteGradientAddMultipleAdds(self, dtype):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtype, tensor_array_name=\"foo\", size=3, infer_shape=False)\n ta_grad = ta.grad(\"grad\")", " c = lambda x: np.asarray(x, dtype=dtype.as_numpy_dtype)", " w0 = ta.write(2, c(3.0))\n w1 = w0.write(2, c(4.0))", " w0_grad = ta_grad.write(2, c(3.0))\n w1_grad = w0_grad.write(2, c(4.0))\n w2_grad = w1_grad.write(2, c(5.0))", " # Assert that aggregation works correctly\n self.assertAllEqual(c(12.00), w2_grad.read(2))", " # Assert that if multiple_writes_aggregate is not enabled,\n # multiple writes raise an exception.\n with self.assertRaisesOpError(\n r\"TensorArray foo_.*: Could not write to TensorArray index 2 because \"\n r\"it has already been written to.\"):\n self.evaluate(w1.flow)", " # Using differing shapes causes an exception\n wb0_grad = ta_grad.write(1, c(1.0))\n wb1_grad = wb0_grad.write(1, c([1.0]))", " with self.assertRaisesOpError(\n r\"Could not aggregate to TensorArray index 1 because the \"\n r\"existing shape is \\[\\] but the new input shape is \\[1\\]\"):\n self.evaluate(wb1_grad.flow)", " @test_util.disable_control_flow_v2(\"v2 does not support TensorArray.grad.\")\n @test_util.run_v1_only(\"v2 does not support TensorArray.grad.\")\n def testSkipEagerTensorArrayWriteGradientAddMultipleAdds(self):\n for dtype in (dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64,\n dtypes.complex64, dtypes.complex128):\n self._testTensorArrayWriteGradientAddMultipleAdds(dtype)", " @test_util.disable_control_flow_v2(\"Low level legacy TA op test.\")\n @test_util.run_v1_only(\"Low level legacy TA op test.\")\n def testSkipEagerTensorArrayGradWithShapeKnownElementShape(self):\n with self.session() as sess:\n ta = tensor_array_ops.TensorArray(\n size=3,\n dtype=dtypes.float32,\n element_shape=tensor_shape.TensorShape([2, 3]))\n handle, flow = data_flow_ops.tensor_array_grad_with_shape(\n handle=ta.handle,\n flow_in=ta.flow,\n shape_to_prepend=tensor_shape.TensorShape([4, 5]),\n source=\"source\")\n ta_grad = tensor_array_ops.TensorArray(\n dtypes.float32, handle=handle, flow=flow)\n value = array_ops.placeholder(dtypes.float32)\n ta_grad = ta_grad.write(0, value)\n read_value = ta_grad.read(0)", " # Make sure shape inference worked.\n self.assertAllEqual([None, None, 2, 3], read_value.shape.as_list())\n # Writing with wrong shape should not work.\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Could not write to TensorArray\"):\n fed_value = np.random.random([2, 3])\n sess.run(read_value, feed_dict={value: fed_value})\n # Writing with correct shape should work.\n fed_value = np.random.random([4, 5, 2, 3])\n self.assertAllClose(fed_value,\n sess.run(read_value, feed_dict={value: fed_value}))", " @test_util.disable_control_flow_v2(\"Low level legacy TA op test.\")\n @test_util.run_v1_only(\"Low level legacy TA op test.\")\n def testSkipEagerTensorArrayGradWithShapeUnknownElementShape(self):\n with self.session() as sess:\n ta = tensor_array_ops.TensorArray(\n size=3, dtype=dtypes.float32,\n element_shape=None) # Note that element_shape is unknown\n handle, flow = data_flow_ops.tensor_array_grad_with_shape(\n handle=ta.handle,\n flow_in=ta.flow,\n shape_to_prepend=tensor_shape.TensorShape([4, 5]),\n source=\"source\")\n ta_grad = tensor_array_ops.TensorArray(\n dtypes.float32, handle=handle, flow=flow)\n value = array_ops.placeholder(dtypes.float32)\n ta_grad = ta_grad.write(0, value)\n read_value = ta_grad.read(0)", " # Make sure shape inference worked.\n self.assertIsNone(read_value.shape.ndims)\n # Write with some shape and check read value.\n fed_value = np.random.random([4, 5, 7])\n self.assertAllClose(fed_value,\n sess.run(read_value, feed_dict={value: fed_value}))", " def testMultiTensorArray(self):\n with self.session():\n h1 = tensor_array_ops.TensorArray(\n size=1, dtype=dtypes.float32, tensor_array_name=\"foo\")\n w1 = h1.write(0, 4.0)\n r1 = w1.read(0)", " h2 = tensor_array_ops.TensorArray(\n size=1, dtype=dtypes.float32, tensor_array_name=\"bar\")", " w2 = h2.write(0, 5.0)\n r2 = w2.read(0)\n r = r1 + r2\n val = self.evaluate(r)\n self.assertAllClose(9.0, val)", " def _testTensorArrayGradientWriteReadType(self, dtype):\n with self.cached_session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.as_dtype(dtype),\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)", " c = lambda x: np.array(x, dtype=dtype)", " value_0 = constant_op.constant(c([[4.0, 5.0]]))\n value_1 = constant_op.constant(c(3.0))", " w0 = ta.write(0, value_0)\n w1 = w0.write(1, value_1)\n r0 = w1.read(0)\n r1 = w1.read(1)\n r0_2 = w1.read(0)", " # Test individual components' gradients\n grad_just_r0 = gradients_impl.gradients(\n ys=[r0], xs=[value_0], grad_ys=[c([[2.0, 3.0]])])\n grad_just_r0_vals = session.run(grad_just_r0)\n self.assertAllEqual(c([[2.0, 3.0]]), grad_just_r0_vals[0])", " grad_r0_r0_2 = gradients_impl.gradients(\n ys=[r0, r0_2],\n xs=[value_0],\n grad_ys=[c([[2.0, 3.0]]), c([[1.0, -1.0]])])\n grad_r0_r0_2_vals = session.run(grad_r0_r0_2)\n self.assertAllEqual(c([[3.0, 2.0]]), grad_r0_r0_2_vals[0])", " grad_just_r1 = gradients_impl.gradients(\n ys=[r1], xs=[value_1], grad_ys=[c(-2.0)])\n grad_just_r1_vals = session.run(grad_just_r1)\n self.assertAllEqual(c(-2.0), grad_just_r1_vals[0])", " # Test combined gradients\n grad = gradients_impl.gradients(\n ys=[r0, r0_2, r1],\n xs=[value_0, value_1],\n grad_ys=[c([[2.0, 3.0]]), c([[1.0, -1.0]]), c(-2.0)])\n grad_vals = session.run(grad)\n self.assertEqual(len(grad_vals), 2)\n self.assertAllEqual(c([[3.0, 2.0]]), grad_vals[0])\n self.assertAllEqual(c(-2.0), grad_vals[1])", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradientWriteRead(self):\n for dtype in (np.float32, np.float64, np.complex64, np.complex128):\n self._testTensorArrayGradientWriteReadType(dtype)", " def _testTensorArrayGradientWritePackConcatAndRead(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=2,\n clear_after_read=False)", " value_0 = constant_op.constant([-1.0, 1.0])\n value_1 = constant_op.constant([-10.0, 10.0])", " w0 = ta.write(0, value_0)\n w1 = w0.write(1, value_1)\n p0 = w1.stack()\n r0 = w1.read(0)\n s0 = w1.concat()", " # Test gradient accumulation between read(0), pack(), and concat()\n with ops.control_dependencies([p0, r0, s0]):\n grad_r = gradients_impl.gradients(\n ys=[p0, r0, s0],\n xs=[value_0, value_1],\n grad_ys=[\n [[2.0, 3.0], [4.0, 5.0]], # pack gradient\n [-0.5, 1.5], # read(0) gradient\n [20.0, 30.0, 40.0, 50.0]\n ]) # concat gradient\n grad_vals = self.evaluate(grad_r) # 2 + 2 entries", " self.assertAllClose([2.0 - 0.5 + 20.0, 3.0 + 1.5 + 30.0], grad_vals[0])\n self.assertAllEqual([4.0 + 40.0, 5.0 + 50.0], grad_vals[1])", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradientWritePackConcatAndRead(self):\n self._testTensorArrayGradientWritePackConcatAndRead()", " @test_util.disable_control_flow_v2(\"v2 does not support clear_after_read.\")\n @test_util.run_v1_only(\"v2 does not support clear_after_read.\")\n def testTensorArrayReadTwice(self):\n with self.session():\n value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])", " ta_readonce = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=2)", " w_readonce = ta_readonce.unstack(value)\n r0_readonce = w_readonce.read(0)", " with self.assertRaisesOpError(\n r\"Could not read index 0 twice because it was cleared after a \"\n r\"previous read \\(perhaps try setting clear_after_read = false\\?\\)\"):\n with ops.control_dependencies([r0_readonce]):\n self.evaluate(w_readonce.read(0))", " ta_readtwice = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=2,\n clear_after_read=False)\n w_readtwice = ta_readtwice.unstack(value)\n r0_readtwice = w_readtwice.read(0)\n with ops.control_dependencies([r0_readtwice]):\n r1_readtwice = w_readtwice.read(0)", " self.assertAllEqual([1.0, -1.0], self.evaluate(r1_readtwice))", " def _testTensorArrayGradientUnpackRead(self):\n with self.cached_session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=2,\n clear_after_read=False)", " value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])", " w = ta.unstack(value)\n r0 = w.read(0)\n r0_1 = w.read(0)\n r1 = w.read(1)", " # Test combined gradients + aggregation of read(0)\n grad = gradients_impl.gradients(\n ys=[r0, r0_1, r1],\n xs=[value],\n grad_ys=[[2.0, 3.0], [-1.5, 1.5], [4.0, 5.0]])\n grad_vals = session.run(grad)", " self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([[2.0 - 1.5, 3.0 + 1.5], [4.0, 5.0]], grad_vals[0])", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradientUnpackRead(self):\n self._testTensorArrayGradientUnpackRead()", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradientSplitConcat(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=2,\n infer_shape=False)", " value = constant_op.constant(\n [[1.0, -1.0], [10.0, -10.0], [100.0, -100.0]])", " w = ta.split(value, [2, 1])\n r = w.concat()", " # Test combined gradients\n grad = gradients_impl.gradients(\n ys=[r],\n xs=[value],\n grad_ys=[[[2.0, -2.0], [20.0, -20.0], [200.0, -200.0]]])\n grad_vals = session.run(grad)", " self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([[2.0, -2.0], [20.0, -20.0], [200.0, -200.0]],\n grad_vals[0])", " def _testTensorArrayGradientDynamicUnpackRead(self):\n with self.cached_session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True)", " value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])", " w = ta.unstack(value)\n r0 = w.read(0)\n r1 = w.read(1)", " # Test combined gradients + aggregation of read(0)\n grad = gradients_impl.gradients(\n ys=[r0, r1], xs=[value], grad_ys=[[2.0, 3.0], [4.0, 5.0]])\n grad_vals = session.run(grad)", " self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([[2.0, 3.0], [4.0, 5.0]], grad_vals[0])", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradientDynamicUnpackRead(self):\n self._testTensorArrayGradientDynamicUnpackRead()", " def testCloseTensorArray(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n self.evaluate(ta.close())", " def testSizeTensorArray(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n s = ta.size()\n self.assertAllEqual(3, self.evaluate(s))", " def testWriteCloseTensorArray(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=False)\n w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [3.0])\n self.evaluate(w1.close()) # Expected to run without problems", " def _testWhileLoopWritePackGradients(self, dynamic_size, dtype):\n np_dtype = dtype.as_numpy_dtype\n with self.cached_session():", " def func(v0, state0, var):\n ta = tensor_array_ops.TensorArray(\n dtype=dtype,\n tensor_array_name=\"foo\",\n size=0 if dynamic_size else 3,\n dynamic_size=dynamic_size)\n time_0 = array_ops.identity(0)", " def body(time, ta_t, state):\n sliced = array_ops.slice(\n v0, begin=array_ops.stack([time, 0]), size=[1, -1])\n sliced = array_ops.squeeze(sliced)\n out = sliced + var + state\n state += sliced\n ta_t = ta_t.write(time, out)\n return (time + 1, ta_t, state)", " (unused_0, h_final, unused_2) = control_flow_ops.while_loop(\n cond=lambda time, unused_1, unused_2: time < 3,\n body=body,\n loop_vars=(time_0, ta, state0),\n shape_invariants=(time_0.get_shape(), tensor_shape.unknown_shape(),\n tensor_shape.unknown_shape()),\n parallel_iterations=3)\n vout = h_final.stack()\n return vout", " v0 = array_ops.identity(np.arange(3 * 5, dtype=np_dtype).reshape(3, 5))\n state0 = array_ops.identity(np.array([1] * 5, dtype=np_dtype))\n init_val = np.arange(100, 105, dtype=np_dtype)\n var = variable_scope.get_variable(\n \"var\",\n shape=init_val.shape,\n dtype=np_dtype,\n initializer=init_ops.constant_initializer(init_val))", " vout = func(v0, state0, var)\n grad_val = -np.arange(3 * 5, dtype=np_dtype).reshape(3, 5)\n if context.executing_eagerly():\n grad_fn = backprop.gradients_function(func)\n v0_grad, state0_grad, var_grad = grad_fn(v0, state0, var, dy=grad_val)\n else:\n v0_grad = gradients_impl.gradients([vout], [v0], [grad_val])[0]\n state0_grad = gradients_impl.gradients([vout], [state0], [grad_val])[0]\n var_grad = gradients_impl.gradients([vout], [var], [grad_val])[0]\n self.evaluate(variables.global_variables_initializer())", " state0_t, var_t, v0_t, vout_t, v0_grad_t, var_grad_t, state0_grad_t = (\n self.evaluate(\n ([state0, var, v0, vout, v0_grad, var_grad, state0_grad])))\n just_v0_grad_t = self.evaluate(v0_grad)", " # state = [ state0 | state0 + v0[0] | state0 + v0[0] + v0[1] ]\n # vout = [ v0[0] + var + state[0] |\n # v0[1] + var + state[1] |\n # v0[2] + var + state[2] ]\n # = [ v0[0] + var + state0 |\n # v0[1] + var + state0 + v0[0] |\n # v0[2] + var + state0 + v0[0] + v0[1] ]\n #\n # d(vout[0])/d(v0) = [1 | 0 | 0 ]\n # d(vout[1])/d(v0) = [1 | 1 | 0 ]\n # d(vout[2])/d(v0) = [1 | 1 | 1 ]\n # d(vout)/d(var) = [1 | 1 | 1]\n # d(vout)/d(state0) = [ 1 | 1 | 1 ]", " state_per_time = np.array(\n [state0_t, state0_t + v0_t[0, :], state0_t + v0_t[0, :] + v0_t[1, :]])", " # Compare forward prop\n self.assertAllClose(v0_t + var_t + state_per_time, vout_t)", " # Compare backward prop\n expected_v0_grad_t = np.array([\n grad_val[0, :] + grad_val[1, :] + grad_val[2, :],\n grad_val[1, :] + grad_val[2, :], grad_val[2, :]\n ])", " self.assertAllEqual(expected_v0_grad_t, v0_grad_t)\n self.assertAllEqual(expected_v0_grad_t, just_v0_grad_t)\n self.assertAllClose(grad_val.sum(axis=0), var_grad_t)\n self.assertAllClose(grad_val.sum(axis=0), state0_grad_t)", " def testWhileLoopWritePackGradients(self):\n self._testWhileLoopWritePackGradients(\n dynamic_size=False, dtype=dtypes.float32)\n # TODO(ebrevdo): re-enable when While supports non-float32 gradients.\n # self._testWhileLoopWritePackGradients(\n # dynamic_size=False, dtype=tf.int64)", " @test_util.run_deprecated_v1\n def testSkipEagerWhileLoopDynamicWritePackGradients(self):\n self._testWhileLoopWritePackGradients(\n dynamic_size=True, dtype=dtypes.float32)", " def testGradSerialTwoLoops(self):\n with self.session():", " def loop(x):\n num_steps = 100\n acc = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n size=num_steps,\n clear_after_read=False,\n element_shape=tensor_shape.TensorShape([]))\n i = constant_op.constant(0, name=\"i\")", " c = lambda i, acc: i < 5", " def b(i, acc):\n x1 = control_flow_ops.cond(\n math_ops.equal(i, 0), lambda: x,\n lambda: math_ops.multiply(acc.read(i - 1), 2.0))\n return i + 1, acc.write(i, x1)", " i1, acc1 = control_flow_ops.while_loop(c, b, [i, acc])", " z = constant_op.constant(0.0)", " def fn(i, acc):\n return i + 1, acc.write(i, z)", " _, acc2 = control_flow_ops.while_loop(lambda i, acc: i < num_steps, fn,\n [i1, acc1])", " r = acc2.stack()\n return r", " x = constant_op.constant(2.0, name=\"x\")\n if context.executing_eagerly():\n grad = backprop.gradients_function(loop)(x)[0]\n else:\n grad = gradients_impl.gradients(loop(x), [x])[0]\n self.assertAllClose(31.0, self.evaluate(grad))", " def testShapeAfterWhileLoop(self):\n size = 10\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=size)\n _, ta = control_flow_ops.while_loop(\n lambda i, _: i < size,\n lambda i, ta: (i + 1, ta.write(i, [[0.]])), [0, ta],\n parallel_iterations=1)\n self.assertIsNotNone(ta.element_shape.dims)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerSumOfTwoReadVariablesWithoutRepeatGrad(self):\n with self.session() as session:\n a = array_ops.identity(\n np.arange(\n 3 * 5, dtype=np.float32).reshape(3, 5) + 1)\n b = array_ops.identity(\n np.arange(\n 3 * 5, dtype=np.float32).reshape(3, 5) + 1 + 3 * 5)\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)\n ta = ta.write(0, a, name=\"write_a\")\n ta = ta.write(1, b, name=\"write_b\")\n c = (\n ta.read(\n 0, name=\"read_a_0\") + # a + b\n ta.read(\n 1, name=\"read_b_0\"))\n g0 = -(np.arange(3 * 5, dtype=np.float32).reshape(3, 5) + 1)\n grad_a = gradients_impl.gradients([c], [a], [g0])[0] # d(a+b)/da = 1\n grad_b = gradients_impl.gradients([c], [b], [g0])[0] # d(a+b)/db = 1", " # Test gradients calculated individually\n grad_a_t, = session.run([grad_a])\n self.assertAllEqual(grad_a_t, g0)", " grad_b_t, = session.run([grad_b])\n self.assertAllEqual(grad_b_t, g0)", " # Test gradients calculated jointly\n joint_grad_a_t, joint_grad_b_t = session.run([grad_a, grad_b])\n self.assertAllEqual(joint_grad_a_t, g0)\n self.assertAllEqual(joint_grad_b_t, g0)", " def _grad_source_for_name(self, name):\n return tensor_array_grad._GetGradSource(constant_op.constant(0, name=name))", " @test_util.deprecated_graph_mode_only\n def testSkipEagerGetGradSource_Invalid(self):\n with self.assertRaises(ValueError):\n self._grad_source_for_name(\"\")\n with self.assertRaises(ValueError):\n self._grad_source_for_name(\"foo\")\n with self.assertRaises(ValueError):\n self._grad_source_for_name(\"foo/bar\")", " @test_util.deprecated_graph_mode_only\n def testSkipEagerGetGradSource_NoEnclosingScope(self):\n self.assertEqual(\"gradients:0\", self._grad_source_for_name(\"gradients\"))\n self.assertEqual(\"gradients_0:0\", self._grad_source_for_name(\"gradients_0\"))\n self.assertEqual(\"gradients\", self._grad_source_for_name(\"gradients/foo\"))\n self.assertEqual(\"gradients_0\",\n self._grad_source_for_name(\"gradients_0/foo\"))\n self.assertEqual(\"gradients\",\n self._grad_source_for_name(\"gradients/foo/bar\"))\n self.assertEqual(\"gradients_0\",\n self._grad_source_for_name(\"gradients_0/foo/bar\"))", " @test_util.deprecated_graph_mode_only\n def testSkipEagerGetGradSource_EnclosingScope(self):\n self.assertEqual(\"foo/gradients:0\",\n self._grad_source_for_name(\"foo/gradients\"))\n self.assertEqual(\"foo/gradients_0:0\",\n self._grad_source_for_name(\"foo/gradients_0\"))\n self.assertEqual(\"foo/gradients\",\n self._grad_source_for_name(\"foo/gradients/bar\"))\n self.assertEqual(\"foo/gradients_0\",\n self._grad_source_for_name(\"foo/gradients_0/bar\"))\n self.assertEqual(\"foo/bar/gradients\",\n self._grad_source_for_name(\"foo/bar/gradients/baz\"))\n self.assertEqual(\"foo/bar/gradients_0\",\n self._grad_source_for_name(\"foo/bar/gradients_0/baz\"))", " @test_util.deprecated_graph_mode_only\n def testSkipEagerGetGradSource_NestedUsesInnermost(self):\n self.assertEqual(\n \"foo/gradients/bar/gradients_0\",\n self._grad_source_for_name(\"foo/gradients/bar/gradients_0/baz\"))", " @test_util.deprecated_graph_mode_only\n def testSkipEagerWriteShape(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n c0 = constant_op.constant([4.0, 5.0])\n w0 = ta.write(0, c0)\n r0 = w0.read(0)\n self.assertAllEqual(c0.get_shape(), r0.get_shape())", " ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n c1 = constant_op.constant([6.0, 7.0])\n w1 = w0.write(1, c1)\n r0 = w1.read(0)\n r1 = w1.read(1)\n self.assertAllEqual(c0.get_shape(), r0.get_shape())\n self.assertAllEqual(c1.get_shape(), r1.get_shape())", " ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=3)\n c2 = constant_op.constant([4.0, 5.0, 6.0])\n with self.assertRaises(ValueError):\n w0.write(0, c2)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerPartlyUnknownShape(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=6)", " c0 = array_ops.placeholder(dtypes.float32, [None, None, None, 3])\n w0 = ta.write(0, c0)\n r0 = w0.read(0)\n self.assertAllEqual([None, None, None, 3], r0.get_shape().as_list())", " c1 = array_ops.placeholder(dtypes.float32, [None, None, None, 3])\n w1 = w0.write(1, c1)\n r1 = w1.read(0)\n self.assertAllEqual([None, None, None, 3], r1.get_shape().as_list())", " # Writing less specific shape (doesn't change type.)\n c2 = array_ops.placeholder(dtypes.float32, [None, None, None, None])\n w2 = w1.write(2, c2)\n r2 = w2.read(0)\n self.assertAllEqual([None, None, None, 3], r2.get_shape().as_list())", " # Writing more specific shape in one dimension and less specific in\n # another.\n c3 = array_ops.placeholder(dtypes.float32, [None, None, 2, None])\n w3 = w2.write(3, c3)\n r3 = w3.read(0)\n self.assertAllEqual([None, None, 2, 3], r3.get_shape().as_list())", " # Writing partly defined shape using TensorArray.scatter.\n c4 = array_ops.placeholder(dtypes.float32, [2, None, 4, 2, 3])\n w4 = w3.scatter([4, 5], c4)\n r4 = w4.read(0)\n self.assertAllEqual([None, 4, 2, 3], r4.get_shape().as_list())", " # Writing fully defined shape using TensorArray.split.\n c5 = array_ops.placeholder(dtypes.float32, [10, 4, 2, 3])\n w5 = w4.split(c5, constant_op.constant([5, 5]))\n r5 = w5.read(0)\n self.assertAllEqual([5, 4, 2, 3], r5.get_shape().as_list())", " def _testUnpackShape(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True,\n infer_shape=True)\n value = constant_op.constant(\n [[1.0, -1.0], [10.0, -10.0], [100.0, -100.0]])\n w0 = ta.unstack(value)\n r0 = w0.read(0)\n self.assertAllEqual((2,), r0.get_shape())", " c1 = constant_op.constant([4.0, 5.0])\n w1 = w0.write(3, c1)", " if not control_flow_util.ENABLE_CONTROL_FLOW_V2:\n # TensorArray v2 does not support clear_after_read.\n with self.assertRaisesOpError(\n r\"Could not read index 0 twice because it was cleared after a \"\n r\"previous read \\(perhaps try setting clear_after_read = false\\?\\)\"\n ):\n with ops.control_dependencies([r0]):\n self.evaluate(w1.read(0))", " r1 = w1.read(1)\n self.assertAllEqual(c1.get_shape(), r1.shape)", " c2 = constant_op.constant([4.0, 5.0, 6.0])\n with self.assertRaises(ValueError):\n w1.write(4, c2)", " def testUnpackShape(self):\n self._testUnpackShape()", " @test_util.deprecated_graph_mode_only\n def testSplitShape(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True,\n infer_shape=True)\n value = constant_op.constant([[1.0, -1.0], [2.0, -2.0], [3.0, -3.0]])\n w0 = ta.split(value, [1, 1, 1])\n r0 = w0.read(0)\n self.assertAllEqual((1, 2), r0.get_shape())", " ta1 = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo1\",\n size=0,\n dynamic_size=True,\n infer_shape=True)\n w0 = ta1.split(value, [1, 2])\n r0 = w0.read(0)\n if context.executing_eagerly():\n self.assertEqual((1, 2), r0.get_shape())\n self.assertEqual((2, 2), w0.read(1).get_shape())\n else:\n self.assertEqual(r0.get_shape().ndims, None)\n if not control_flow_util.ENABLE_CONTROL_FLOW_V2:\n self.assertEqual(\n tensor_shape.TensorShape(\n ta1.handle.op.get_attr(\"element_shape\")).ndims, None)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerWriteUnknownShape(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=3,\n infer_shape=True)\n c0 = array_ops.placeholder(dtypes.float32)\n w0 = ta.write(0, c0)\n r0 = w0.read(0)\n self.assertAllEqual(r0.get_shape(), tensor_shape.unknown_shape())", " def _testGradientWhenNotAllComponentsRead(self):\n with self.cached_session() as session:\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)\n x = constant_op.constant([2.0, 3.0])\n w = ta.unstack(x)\n r0 = w.read(0)\n # calculate (dr0/dx0, dr0/dx1). since r0 = x0, gradients are (1, 0).\n grad_r0 = gradients_impl.gradients(ys=[r0], xs=[x], grad_ys=[1.0])\n grad_r0_vals = session.run(grad_r0)[0]\n self.assertAllEqual(grad_r0_vals, [1.0, 0.0])", " @test_util.deprecated_graph_mode_only\n def testSkipEagerGradientWhenNotAllComponentsRead(self):\n self._testGradientWhenNotAllComponentsRead()", " @test_util.deprecated_graph_mode_only\n def testSkipEagerWriteButNotAllComponentsReadGrad(self):\n with self.cached_session() as session:\n x0 = constant_op.constant(5.0)\n x1 = constant_op.constant(10.0)\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=2).write(0, x0).write(1, x1)\n r0 = ta.read(0)\n # calculate (dr0/dx0, dr0/dx1). since r0 = x0, gradients are (1, 0).\n grad_r0_x1 = gradients_impl.gradients(ys=[r0], xs=[x0, x1], grad_ys=[1.0])\n grad_r0_x1_vals = session.run(grad_r0_x1)\n self.assertAllEqual(grad_r0_x1_vals, [1.0, 0.0])", " def _testTensorArrayUnpackDynamic(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=3, dynamic_size=True)\n x = constant_op.constant([1.0, 2.0, 3.0])\n w0 = ta.unstack(x)\n w1 = w0.write(3, 4.0)\n r = w1.stack()\n self.assertAllEqual(np.array([1.0, 2.0, 3.0, 4.0]), self.evaluate(r))\n grad = gradients_impl.gradients(ys=[r], xs=[x])\n self.assertAllEqual(np.array([1.0, 1.0, 1.0]), self.evaluate(grad)[0])", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArrayUnpackDynamic(self):\n self._testTensorArrayUnpackDynamic()", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArraySplitDynamic(self):\n with self.session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=3, dynamic_size=True)\n x = constant_op.constant([1.0, 2.0, 3.0])\n w0 = ta.split(x, [1, 1, 1])\n w1 = w0.write(3, [4.0])\n r = w1.concat()\n self.assertAllEqual(np.array([1.0, 2.0, 3.0, 4.0]), self.evaluate(r))\n grad = gradients_impl.gradients(ys=[r], xs=[x])\n self.assertAllEqual(np.array([1.0, 1.0, 1.0]), self.evaluate(grad)[0])", " def testStackShape(self):", " @def_function.function\n def ta_stack():\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=3)\n x = constant_op.constant([1.0, 2.0, 3.0])\n ta = ta.write(0, x)\n t = ta.stack()\n self.assertEqual(t.shape.as_list(), [3, 3])\n return t", " ta_stack()", " def testReadShape(self):", " @def_function.function\n def ta_read():\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=3)\n x = constant_op.constant([1.0, 2.0, 3.0])\n ta = ta.write(0, x)\n t = ta.read(0)\n self.assertEqual(t.shape.as_list(), [3])\n return t", " ta_read()", " def testGatherShape(self):", " def ta_gather(indices):\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=3)\n x = constant_op.constant([1.0, 2.0, 3.0])\n ta = ta.write(0, x)\n t = ta.gather(indices)\n self.assertEqual(t.shape.as_list(), [first_dim, 3])\n return t", " # This propagates shape of `indices` when compiling ta_gather.\n ta_gather_with_known_indices_shape = def_function.function(ta_gather)\n first_dim = 1\n ta_gather_with_known_indices_shape([0])", " # Here were force the shape of `indices` to be [None] during ta_gather's\n # compilation.\n ta_gather_with_unknown_indices_shape = def_function.function(\n ta_gather,\n input_signature=[\n tensor_spec.TensorSpec(dtype=dtypes.int32, shape=[None])\n ])\n first_dim = None\n ta_gather_with_unknown_indices_shape([0])", " def _testTensorArrayEvalEmpty(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=0, dynamic_size=False, infer_shape=False)\n v2_msg = (\"Tried to stack elements of an empty list with \"\n \"non-fully-defined element_shape\")\n v1_msg = (\n \"TensorArray has size zero, but element shape <unknown> is not \"\n \"fully defined. Currently only static shapes are supported when \"\n \"packing zero-size TensorArrays.\")\n with self.assertRaisesOpError(\n v2_msg if control_flow_util.ENABLE_CONTROL_FLOW_V2 else v1_msg):\n ta.stack().eval()", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArrayEvalEmpty(self):\n self._testTensorArrayEvalEmpty()", " # this test is ill-defined for Eager mode --- unpacking an empty tensor\n # gives an empty list / there is not equivalent of \"mark_used\" in Eager\n def _testTensorArrayEvalEmptyWithDefault(self):\n with self.cached_session():\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=0, dynamic_size=False, infer_shape=True)\n self.assertEqual(0, ta.size().eval())\n # Don't actually perform the pack. This stores the static shape.\n if control_flow_util.ENABLE_CONTROL_FLOW_V2:\n ta = ta.unstack(array_ops.zeros([0, 3, 5]))\n else:\n ta.unstack(array_ops.zeros([0, 3, 5])).mark_used()\n packed = ta.stack()\n concatenated = ta.concat()\n self.assertAllEqual([0, 3, 5], self.evaluate(packed).shape)\n # Concatenating zero tensors along their first dimension gives a\n # first dimension of zero\n self.assertAllEqual([0, 5], self.evaluate(concatenated).shape)", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArrayEvalEmptyWithDefault(self):\n self._testTensorArrayEvalEmptyWithDefault()", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArrayScatterReadAndGradients(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True)", " indices = constant_op.constant([1, 8])\n value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])", " w = ta.scatter(indices, value)\n r0 = w.read(1)\n r1 = w.read(8)", " # Test combined gradients + aggregation of read(0)\n grad = gradients_impl.gradients(\n ys=[r0, r1], xs=[value], grad_ys=[[2.0, 3.0], [4.0, 5.0]])\n read_vals, grad_vals = session.run([[r0, r1], grad])", " self.assertEqual(len(read_vals), 2)\n self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([1.0, -1.0], read_vals[0])\n self.assertAllEqual([10.0, -10.0], read_vals[1])\n self.assertAllEqual([[2.0, 3.0], [4.0, 5.0]], grad_vals[0])", " @test_util.run_deprecated_v1\n def testSkipEagerTensorArrayScatterPartialReadAndGradients(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True)", " indices = constant_op.constant([1, 8])\n value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])", " w = ta.scatter(indices, value)\n r0 = w.read(1)", " # Test combined gradients + aggregation of read(0)\n grad = gradients_impl.gradients(\n ys=[r0], xs=[value], grad_ys=[[2.0, 3.0]])[0]\n read_val, grad_val = session.run([r0, grad])", " self.assertAllEqual([1.0, -1.0], read_val)\n self.assertAllEqual([[2.0, 3.0], [0.0, 0.0]], grad_val)", " def testScatterIntoExistingList(self):\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, tensor_array_name=\"foo\", size=5)", " ta = ta.scatter(indices=[3, 4], value=array_ops.ones([2]))\n self.assertAllEqual(ta.stack(), [0., 0., 0., 1., 1.])", " ta = ta.scatter(indices=[1], value=array_ops.ones([1]))\n self.assertAllEqual(ta.stack(), [0., 1., 0., 1., 1.])", " ta = ta.scatter(indices=[0, 2], value=[5., 6.])\n self.assertAllEqual(ta.stack(), [5., 1., 6., 1., 1.])", " @test_util.run_v1_only(\"b/118890905\")\n def testTensorArrayWriteGatherAndGradients(self):\n with self.session() as session:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name=\"foo\",\n size=0,\n dynamic_size=True)", " def func(values):\n indices = constant_op.constant([1, 8])\n w = ta.unstack(values)\n g = w.gather(indices)\n return g", " values = constant_op.constant([[1.0 * x, -1.0 * x] for x in range(10)])\n g = func(values)\n grad_ys = [[[2.0, 3.0], [4.0, 5.0]]]\n # Test combined gradients + aggregation of read(0)\n if context.executing_eagerly():\n g_vals = [g]\n grad_vals = backprop.gradients_function(func)(\n values, dy=constant_op.constant(grad_ys[0], dtype=dtypes.float32))\n else:\n grad = gradients_impl.gradients(ys=[g], xs=[values], grad_ys=grad_ys)\n g_vals, grad_vals = session.run([[g], grad])", " # Gradients for 8 of the 10 unread components are zero.\n expected_grad = np.zeros((10, 2))\n expected_grad[1] = [2.0, 3.0]\n expected_grad[8] = [4.0, 5.0]", " self.assertEqual(len(g_vals), 1)\n self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([[1.0, -1.0], [8.0, -8.0]], g_vals[0])\n self.assertAllEqual(expected_grad, grad_vals[0])", " @test_util.disable_control_flow_v2(\"colocate_with not supported in v2.\")\n @test_util.run_v1_only(\"b/120545219\")\n def testSkipEagerTensorArrayGetsDeviceFromFirstWrite(self):\n with ops.device(\"/job:worker/task:0/cpu:0\"):\n # this initial device will be ignored.\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)\n with ops.device(\"/job:worker/task:1/cpu:0\"):\n # the first write sets the op's device.\n ta = ta.write(0, 1.0)\n with ops.device(\"/job:worker/task:2/cpu:0\"):\n # subsequent writes do not modify the op's device.\n ta = ta.write(1, 1.0)", " # The gradient TA will sit on the same device as the forward TA.\n ta_grad = ta.grad(\"grad\")\n flows = [ta.flow, ta_grad.flow]", " # Similar tests for unpack and split\n with ops.device(\"/job:worker/task:0/cpu:0\"):\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=3)\n with ops.device(\"/job:worker/task:1/cpu:0\"):\n ta = ta.unstack([1.0, 2.0])\n with ops.device(\"/job:worker/task:2/cpu:0\"):\n ta = ta.write(2, 3.0)\n flows.append(ta.flow)", " with ops.device(\"/job:worker/task:0/cpu:0\"):\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)\n with ops.device(\"/job:worker/task:1/cpu:0\"):\n ta = ta.split([1.0, 2.0], [1, 1])\n flows.append(ta.flow)", " session = session_lib.Session(self._workers[0].target)", " run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE)\n run_metadata = config_pb2.RunMetadata()", " session.run(flows, options=run_options, run_metadata=run_metadata)\n self.assertTrue(run_metadata.HasField(\"step_stats\"))\n dev_stats = {d.device: d.node_stats\n for d in run_metadata.step_stats.dev_stats}\n for d in dev_stats:\n if \"/task:1/\" in d:\n self.assertTrue(\n [s for s in dev_stats[d] if \"/TensorArray\" in s.node_name])\n elif \"/host:CPU\" not in d:\n self.assertFalse(\n [s for s in dev_stats[d] if \"/TensorArray\" in s.node_name])", " @test_util.disable_control_flow_v2(\"colocate_with not supported in v2.\")\n @test_util.run_v1_only(\"b/120545219\")\n def testSkipEagerTensorArrayGetsDeviceFromFirstWriteInWhileLoop(self):\n with ops.device(\"/job:worker/task:0/cpu:0\"):\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)", " def _body(i, ta_i):\n with ops.device(\"/job:worker/task:1/cpu:0\"):\n return i + 1, ta_i.write(i, constant_op.constant(0.0))", " _, ta_out = control_flow_ops.while_loop(\n lambda i, ta: i < 2, _body, loop_vars=[0, ta])", " session = session_lib.Session(self._workers[0].target)", " run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE)\n run_metadata = config_pb2.RunMetadata()", " session.run(ta_out.flow, options=run_options, run_metadata=run_metadata)\n self.assertTrue(run_metadata.HasField(\"step_stats\"))\n dev_stats = {d.device: d.node_stats\n for d in run_metadata.step_stats.dev_stats}\n for d in dev_stats:\n if \"/task:1/\" in d:\n self.assertTrue(\n [s for s in dev_stats[d] if \"TensorArray\" == s.node_name])\n else:\n self.assertFalse(\n [s for s in dev_stats[d] if \"TensorArray\" == s.node_name])", " @test_util.disable_control_flow_v2(\"colocate_with not supported in v2.\")\n @test_util.run_v1_only(\"b/120545219\")\n def testSkipEagerTensorArrayDisabledColocateWithFirstWriteCall(self):\n with ops.device(\"/job:worker/task:0/cpu:0\"):\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=2, colocate_with_first_write_call=False)", " def _body(i, ta_i):\n with ops.device(\"/job:worker/task:1/cpu:0\"):\n return i + 1, ta_i.write(i, constant_op.constant(0.0))", " _, ta_out = control_flow_ops.while_loop(\n lambda i, ta: i < 2, _body, loop_vars=[0, ta])", " session = session_lib.Session(self._workers[0].target)", " run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE)\n run_metadata = config_pb2.RunMetadata()", " session.run(ta_out.flow, options=run_options, run_metadata=run_metadata)\n self.assertTrue(run_metadata.HasField(\"step_stats\"))\n dev_stats = {d.device: list(d.node_stats)\n for d in run_metadata.step_stats.dev_stats}\n for d in dev_stats:\n if \"/task:0/\" in d and \"CPU\" in d: # Skip any GPU node stats\n self.assertTrue(\n [s for s in dev_stats[d] if \"TensorArray\" == s.node_name])\n else:\n self.assertFalse(\n [s for s in dev_stats[d] if \"TensorArray\" == s.node_name])", " def testTensorArrayIdentity(self):\n with self.session():\n ta0 = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2,\n infer_shape=False)\n ta1 = tensor_array_ops.TensorArray(dtype=dtypes.int32, size=4,\n infer_shape=True)", " ta0 = ta0.write(0, 0.)\n ta1 = ta1.write(0, 1)", " v0 = variable_scope.get_variable(\n \"v0\", shape=(), initializer=init_ops.zeros_initializer())\n v1 = variable_scope.get_variable(\n \"v1\", shape=(), initializer=init_ops.zeros_initializer())", " with ops.control_dependencies([v0.assign_add(1)]):\n ta0 = ta0.identity()", " with ops.control_dependencies([v1.assign_add(1)]):\n ta1 = ta1.identity()", " read0 = ta0.read(0)\n read1 = ta1.read(0)", " size0 = ta0.size()\n size1 = ta1.size()", " # Tests correct properties on new TensorArrays.\n self.assertEqual(dtypes.float32, ta0.dtype)\n self.assertEqual(dtypes.int32, ta1.dtype)\n if context.executing_eagerly():\n self.assertEqual(tensor_shape.TensorShape([]), read0.get_shape())\n else:\n self.assertEqual(tensor_shape.unknown_shape(), read0.get_shape())\n self.assertEqual(tensor_shape.TensorShape([]), read1.get_shape())", " if not context.executing_eagerly():\n self.evaluate(variables.global_variables_initializer())", " read0_v, read1_v, size0_v, size1_v = self.evaluate((read0, read1, size0,\n size1))", " # Tests that the control dependencies was added and executed.\n self.assertEqual(1, self.evaluate(v0))\n self.assertEqual(1, self.evaluate(v1))", " # Tests correct TensorArray.\n self.assertEqual(read0_v, 0)\n self.assertEqual(read1_v, 1)\n self.assertEqual(size0_v, 2)\n self.assertEqual(size1_v, 4)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayGradYsInCorrectScope(self):\n n_time = 1\n n_dim = 1\n x = constant_op.constant([[1.42]])\n dy = constant_op.constant([[2.42]])", " ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=n_time, element_shape=[n_dim])\n for t in range(n_time):\n ta = ta.write(index=t, value=x[t])\n y = ta.stack()\n # dy is outside of the gradients name scope; tf.gradients must\n # wrap it in the correct name scope.\n dx, = gradients_impl.gradients(ys=[y], xs=[x], grad_ys=[dy])\n with self.cached_session():\n vdx, vdy = self.evaluate([dx, dy])\n self.assertAllClose(vdx, vdy)", " @test_util.deprecated_graph_mode_only\n def testSkipEagerTensorArrayInt64GPU(self):\n if not test.is_gpu_available():\n return\n with self.session(force_gpu=True) as sess:\n value = array_ops.placeholder(dtypes.int64)\n ta = tensor_array_ops.TensorArray(dtype=dtypes.int64, size=2)\n ta = ta.scatter([0, 1], value)\n r0 = ta.read(0)\n r1 = ta.read(1)\n v0, v1 = sess.run([r0, r1], feed_dict={value: [-3, 100]})\n self.assertAllEqual(v0, -3)\n self.assertAllEqual(v1, 100)", " @test_util.deprecated_graph_mode_only\n def testTensorArrayScatterBfloat16GPU(self):\n if not test.is_gpu_available():\n return\n with self.session(force_gpu=True) as sess:\n ta = tensor_array_ops.TensorArray(\n dtype=dtypes.bfloat16, tensor_array_name=\"foo\", size=5)\n ta = ta.scatter(\n indices=[3, 4], value=array_ops.ones([2], dtype=dtypes.bfloat16))\n self.assertAllEqual(ta.stack(), [0., 0., 0., 1., 1.])", " def testInferShapeFalseValid(self):\n ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=3, infer_shape=False, element_shape=[None, 10, 20])\n ta = ta.write(0, array_ops.ones([50, 10, 20]))\n ta = ta.write(1, array_ops.ones([50, 10, 20]))\n ta = ta.write(2, array_ops.ones([1, 10, 20]))\n ta = ta.concat()", " correct = np.ones([101, 10, 20])", " self.assertAllEqual(ta, correct)", " def testInferShapeFalseInvalid(self):\n ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=2, infer_shape=False, element_shape=[None, 10, 20])\n ta = ta.write(0, array_ops.ones([50, 10, 20]))", " with self.assertRaises(ValueError):\n ta = ta.write(1, array_ops.ones([1, 20, 20]))", " def testInferShapeTrue(self):\n ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=3, infer_shape=True, element_shape=[None, 10, 20])\n self.assertAllEqual((None, 10, 20), ta.element_shape.as_list())\n ta = ta.write(0, array_ops.ones([50, 10, 20]))\n self.assertAllEqual((50, 10, 20), ta.element_shape.as_list())\n ta = ta.write(1, array_ops.ones([50, 10, 20]))\n with self.assertRaises(ValueError):\n ta = ta.write(\n 2, array_ops.ones([1, 10, 20])\n ) # Inconsistent shapes: saw (1, 10, 20) but expected (50, 10, 20)", " def testStackShapeOnEmpty(self):\n ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=0, element_shape=(5, 10), dynamic_size=True)\n self.assertAllEqual([0, 5, 10], self.evaluate(ta.stack()).shape)", " @test_util.run_deprecated_v1\n def testSkipEagerStackOnPartiallyDefinedShape(self):\n ta = tensor_array_ops.TensorArray(\n dtypes.float32, size=0, element_shape=(5, None), dynamic_size=True)\n self.assertEqual([None, 5, None], ta.stack().shape.as_list())", " def testStackShapeOnStaticSize(self):\n ta = tensor_array_ops.TensorArray(dtypes.float32, size=42)\n ta = ta.write(0, [0])\n self.assertEqual([42, 1], ta.stack().shape.as_list())\n", " def testTensorArrayConcatFailsWhenMissingStepContainer(self):\n @def_function.function\n def func():\n y = data_flow_ops.TensorArrayConcatV2(\n handle=[\"a\", \"b\"],\n flow_in=0.1,\n dtype=dtypes.int32,\n element_shape_except0=1,\n )\n return y", " with self.assertRaisesRegex(\n errors.NotFoundError, \"Container .* does not exist\"\n ):\n self.evaluate(func())\n", "\nclass TensorArrayBenchmark(test.Benchmark):", " def _tensorArrayWriteInWhile(self):\n size = 10000\n ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=size)\n (_, ta) = control_flow_ops.while_loop(\n lambda i, _: i < size,\n lambda i, ta: (i + 1, ta.write(i, 0.)), [0, ta],\n parallel_iterations=1)\n return ta.stack()", " def _benchmarkWriteInWhile(self):\n ops.reset_default_graph()\n op = self._tensorArrayWriteInWhile()\n self.run_op_benchmark(session_lib.Session(), op)", " def benchmarkWriteInWhile(self):\n self._benchmarkWriteInWhile()", " @test_util.enable_control_flow_v2\n def benchmarkWriteInWhileWithControlFlowV2(self):\n self._benchmarkWriteInWhile()", " def benchmarkWriteInDatasetMapFn(self):\n ds = dataset_ops.Dataset.from_tensors(array_ops.zeros([10])).repeat()\n ds = ds.map(lambda _: self._tensorArrayWriteInWhile())\n op = ds.make_one_shot_iterator().get_next()\n self.run_op_benchmark(session_lib.Session(), op)", " def benchmarkWriteInDatasetParallelMapFn(self):\n ds = dataset_ops.Dataset.from_tensors(array_ops.zeros([10])).repeat()\n ds = ds.map(lambda _: self._tensorArrayWriteInWhile(), num_parallel_calls=2)\n op = ds.make_one_shot_iterator().get_next()\n self.run_op_benchmark(session_lib.Session(), op)", "\nif __name__ == \"__main__\":\n test.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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [85, 1848], "buggy_code_start_loc": [83, 1848], "filenames": ["tensorflow/core/kernels/tensor_array_ops.cc", "tensorflow/python/kernel_tests/data_structures/tensor_array_ops_test.py"], "fixing_code_end_loc": [86, 1865], "fixing_code_start_loc": [83, 1849], "message": "TensorFlow is an open source platform for machine learning. Prior to versions 2.12.0 and 2.11.1, when `ctx->step_containter()` is a null ptr, the Lookup function will be executed with a null pointer. A fix is included in TensorFlow 2.12.0 and 2.11.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "FAC3DE54-93B4-4D6C-9648-B9D416B9770F", "versionEndExcluding": "2.12.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an open source platform for machine learning. Prior to versions 2.12.0 and 2.11.1, when `ctx->step_containter()` is a null ptr, the Lookup function will be executed with a null pointer. A fix is included in TensorFlow 2.12.0 and 2.11.1."}], "evaluatorComment": null, "id": "CVE-2023-25663", "lastModified": "2023-03-30T17:42:24.500", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-25T00:15:07.313", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/tensorflow/tensorflow/commit/239139d2ae6a81ae9ba499ad78b56d9b2931538a"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-64jg-wjww-7c5w"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/239139d2ae6a81ae9ba499ad78b56d9b2931538a"}, "type": "CWE-476"}
230
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n +----------------------------------------------------------------------+\n | PHP Version 5 |\n +----------------------------------------------------------------------+\n | Copyright (c) 1997-2014 The PHP Group |\n +----------------------------------------------------------------------+\n | This source file is subject to version 3.01 of the PHP license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http://www.php.net/license/3_01.txt |\n | If you did not receive a copy of the PHP license and are unable to |\n | obtain it through the world-wide-web, please send a note to |\n | license@php.net so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Authors: The typical suspects |\n | Pollita <pollita@php.net> |\n | Marcus Boerger <helly@php.net> |\n +----------------------------------------------------------------------+\n */", "/* $Id$ */", "/* {{{ includes */\n#include \"php.h\"\n#include \"php_network.h\"", "#if HAVE_SYS_SOCKET_H\n#include <sys/socket.h>\n#endif", "#ifdef PHP_WIN32\n# include \"win32/inet.h\"\n# include <winsock2.h>\n# include <windows.h>\n# include <Ws2tcpip.h>\n#else\t/* This holds good for NetWare too, both for Winsock and Berkeley sockets */\n#include <netinet/in.h>\n#if HAVE_ARPA_INET_H\n#include <arpa/inet.h>\n#endif\n#include <netdb.h>\n#ifdef _OSD_POSIX\n#undef STATUS\n#undef T_UNSPEC\n#endif\n#if HAVE_ARPA_NAMESER_H\n#ifdef DARWIN\n# define BIND_8_COMPAT 1\n#endif\n#include <arpa/nameser.h>\n#endif\n#if HAVE_RESOLV_H\n#include <resolv.h>\n#endif\n#ifdef HAVE_DNS_H\n#include <dns.h>\n#endif\n#endif", "/* Borrowed from SYS/SOCKET.H */\n#if defined(NETWARE) && defined(USE_WINSOCK)\n#define AF_INET 2 /* internetwork: UDP, TCP, etc. */\n#endif", "#ifndef MAXHOSTNAMELEN\n#define MAXHOSTNAMELEN 255\n#endif", "/* For the local hostname obtained via gethostname which is different from the\n dns-related MAXHOSTNAMELEN constant above */\n#ifndef HOST_NAME_MAX\n#define HOST_NAME_MAX 255\n#endif", "#include \"php_dns.h\"", "/* type compat */\n#ifndef DNS_T_A\n#define DNS_T_A\t\t1\n#endif\n#ifndef DNS_T_NS\n#define DNS_T_NS\t2\n#endif\n#ifndef DNS_T_CNAME\n#define DNS_T_CNAME\t5\n#endif\n#ifndef DNS_T_SOA\n#define DNS_T_SOA\t6\n#endif\n#ifndef DNS_T_PTR\n#define DNS_T_PTR\t12\n#endif\n#ifndef DNS_T_HINFO\n#define DNS_T_HINFO\t13\n#endif\n#ifndef DNS_T_MINFO\n#define DNS_T_MINFO\t14\n#endif\n#ifndef DNS_T_MX\n#define DNS_T_MX\t15\n#endif\n#ifndef DNS_T_TXT\n#define DNS_T_TXT\t16\n#endif\n#ifndef DNS_T_AAAA\n#define DNS_T_AAAA\t28\n#endif\n#ifndef DNS_T_SRV\n#define DNS_T_SRV\t33\n#endif\n#ifndef DNS_T_NAPTR\n#define DNS_T_NAPTR\t35\n#endif\n#ifndef DNS_T_A6\n#define DNS_T_A6\t38\n#endif", "#ifndef DNS_T_ANY\n#define DNS_T_ANY\t255\n#endif\n/* }}} */", "static char *php_gethostbyaddr(char *ip);\nstatic char *php_gethostbyname(char *name);", "#ifdef HAVE_GETHOSTNAME\n/* {{{ proto string gethostname()\n Get the host name of the current machine */\nPHP_FUNCTION(gethostname)\n{\n\tchar buf[HOST_NAME_MAX];", "\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}", "\tif (gethostname(buf, sizeof(buf) - 1)) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"unable to fetch host [%d]: %s\", errno, strerror(errno));\n\t\tRETURN_FALSE;\n\t}", "\tRETURN_STRING(buf, 1);\n}\n/* }}} */\n#endif", "/* TODO: Reimplement the gethostby* functions using the new winxp+ API, in dns_win32.c, then\n we can have a dns.c, dns_unix.c and dns_win32.c instead of a messy dns.c full of #ifdef\n*/", "/* {{{ proto string gethostbyaddr(string ip_address)\n Get the Internet host name corresponding to a given IP address */\nPHP_FUNCTION(gethostbyaddr)\n{\n\tchar *addr;\n\tint addr_len;\n\tchar *hostname;", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &addr, &addr_len) == FAILURE) {\n\t\treturn;\n\t}", "\thostname = php_gethostbyaddr(addr);", "\tif (hostname == NULL) {\n#if HAVE_IPV6 && HAVE_INET_PTON\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Address is not a valid IPv4 or IPv6 address\");\n#else\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Address is not in a.b.c.d form\");\n#endif\n\t\tRETVAL_FALSE;\n\t} else {\n\t\tRETVAL_STRING(hostname, 0);\n\t}\n}\n/* }}} */", "/* {{{ php_gethostbyaddr */\nstatic char *php_gethostbyaddr(char *ip)\n{\n#if HAVE_IPV6 && HAVE_INET_PTON\n\tstruct in6_addr addr6;\n#endif\n\tstruct in_addr addr;\n\tstruct hostent *hp;", "#if HAVE_IPV6 && HAVE_INET_PTON\n\tif (inet_pton(AF_INET6, ip, &addr6)) {\n\t\thp = gethostbyaddr((char *) &addr6, sizeof(addr6), AF_INET6);\n\t} else if (inet_pton(AF_INET, ip, &addr)) {\n\t\thp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET);\n\t} else {\n\t\treturn NULL;\n\t}\n#else\n\taddr.s_addr = inet_addr(ip);", "\tif (addr.s_addr == -1) {\n\t\treturn NULL;\n\t}", "\thp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET);\n#endif", "\tif (!hp || hp->h_name == NULL || hp->h_name[0] == '\\0') {\n\t\treturn estrdup(ip);\n\t}", "\treturn estrdup(hp->h_name);\n}\n/* }}} */", "/* {{{ proto string gethostbyname(string hostname)\n Get the IP address corresponding to a given Internet host name */\nPHP_FUNCTION(gethostbyname)\n{\n\tchar *hostname;\n\tint hostname_len;\n\tchar *addr;", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &hostname, &hostname_len) == FAILURE) {\n\t\treturn;\n\t}", "\taddr = php_gethostbyname(hostname);", "\tRETVAL_STRING(addr, 0);\n}\n/* }}} */", "/* {{{ proto array gethostbynamel(string hostname)\n Return a list of IP addresses that a given hostname resolves to. */\nPHP_FUNCTION(gethostbynamel)\n{\n\tchar *hostname;\n\tint hostname_len;\n\tstruct hostent *hp;\n\tstruct in_addr in;\n\tint i;", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &hostname, &hostname_len) == FAILURE) {\n\t\treturn;\n\t}", "\thp = gethostbyname(hostname);\n\tif (hp == NULL || hp->h_addr_list == NULL) {\n\t\tRETURN_FALSE;\n\t}", "\tarray_init(return_value);", "\tfor (i = 0 ; hp->h_addr_list[i] != 0 ; i++) {\n\t\tin = *(struct in_addr *) hp->h_addr_list[i];\n\t\tadd_next_index_string(return_value, inet_ntoa(in), 1);\n\t}\n}\n/* }}} */", "/* {{{ php_gethostbyname */\nstatic char *php_gethostbyname(char *name)\n{\n\tstruct hostent *hp;\n\tstruct in_addr in;", "\thp = gethostbyname(name);", "\tif (!hp || !*(hp->h_addr_list)) {\n\t\treturn estrdup(name);\n\t}", "\tmemcpy(&in.s_addr, *(hp->h_addr_list), sizeof(in.s_addr));", "\treturn estrdup(inet_ntoa(in));\n}\n/* }}} */", "#if HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32)\n# define PHP_DNS_NUM_TYPES\t12\t/* Number of DNS Types Supported by PHP currently */", "# define PHP_DNS_A 0x00000001\n# define PHP_DNS_NS 0x00000002\n# define PHP_DNS_CNAME 0x00000010\n# define PHP_DNS_SOA 0x00000020\n# define PHP_DNS_PTR 0x00000800\n# define PHP_DNS_HINFO 0x00001000\n# define PHP_DNS_MX 0x00004000\n# define PHP_DNS_TXT 0x00008000\n# define PHP_DNS_A6 0x01000000\n# define PHP_DNS_SRV 0x02000000\n# define PHP_DNS_NAPTR 0x04000000\n# define PHP_DNS_AAAA 0x08000000\n# define PHP_DNS_ANY 0x10000000\n# define PHP_DNS_ALL (PHP_DNS_A|PHP_DNS_NS|PHP_DNS_CNAME|PHP_DNS_SOA|PHP_DNS_PTR|PHP_DNS_HINFO|PHP_DNS_MX|PHP_DNS_TXT|PHP_DNS_A6|PHP_DNS_SRV|PHP_DNS_NAPTR|PHP_DNS_AAAA)\n#endif /* HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32) */", "/* Note: These functions are defined in ext/standard/dns_win32.c for Windows! */\n#if !defined(PHP_WIN32) && (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE)))\n \n#ifndef HFIXEDSZ\n#define HFIXEDSZ 12 /* fixed data in header <arpa/nameser.h> */\n#endif /* HFIXEDSZ */", "#ifndef QFIXEDSZ\n#define QFIXEDSZ 4 /* fixed data in query <arpa/nameser.h> */\n#endif /* QFIXEDSZ */", "#undef MAXHOSTNAMELEN\n#define MAXHOSTNAMELEN 1024", "#ifndef MAXRESOURCERECORDS\n#define MAXRESOURCERECORDS\t64\n#endif /* MAXRESOURCERECORDS */", "typedef union {\n\tHEADER qb1;\n\tu_char qb2[65536];\n} querybuf;", "/* just a hack to free resources allocated by glibc in __res_nsend()\n * See also:\n * res_thread_freeres() in glibc/resolv/res_init.c\n * __libc_res_nsend() in resolv/res_send.c\n * */", "#if defined(__GLIBC__) && !defined(HAVE_DEPRECATED_DNS_FUNCS)\n#define php_dns_free_res(__res__) _php_dns_free_res(__res__)\nstatic void _php_dns_free_res(struct __res_state res) { /* {{{ */\n\tint ns;\n\tfor (ns = 0; ns < MAXNS; ns++) {\n\t\tif (res._u._ext.nsaddrs[ns] != NULL) {\n\t\t\tfree (res._u._ext.nsaddrs[ns]);\n\t\t\tres._u._ext.nsaddrs[ns] = NULL;\n\t\t}\n\t}\n} /* }}} */\n#else\n#define php_dns_free_res(__res__)\n#endif", "/* {{{ proto bool dns_check_record(string host [, string type])\n Check DNS records corresponding to a given Internet host name or IP address */\nPHP_FUNCTION(dns_check_record)\n{\n#ifndef MAXPACKET\n#define MAXPACKET 8192 /* max packet size used internally by BIND */\n#endif\n\tu_char ans[MAXPACKET];\n\tchar *hostname, *rectype = NULL;\n\tint hostname_len, rectype_len = 0;\n\tint type = T_MX, i;\n#if defined(HAVE_DNS_SEARCH)\n\tstruct sockaddr_storage from;\n\tuint32_t fromsize = sizeof(from);\n\tdns_handle_t handle;\n#elif defined(HAVE_RES_NSEARCH)\n\tstruct __res_state state;\n\tstruct __res_state *handle = &state;\n#endif", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|s\", &hostname, &hostname_len, &rectype, &rectype_len) == FAILURE) {\n\t\treturn;\n\t}", "\tif (hostname_len == 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Host cannot be empty\");\n\t\tRETURN_FALSE;\n\t}", "\tif (rectype) {\n\t\tif (!strcasecmp(\"A\", rectype)) type = T_A;\n\t\telse if (!strcasecmp(\"NS\", rectype)) type = DNS_T_NS;\n\t\telse if (!strcasecmp(\"MX\", rectype)) type = DNS_T_MX;\n\t\telse if (!strcasecmp(\"PTR\", rectype)) type = DNS_T_PTR;\n\t\telse if (!strcasecmp(\"ANY\", rectype)) type = DNS_T_ANY;\n\t\telse if (!strcasecmp(\"SOA\", rectype)) type = DNS_T_SOA;\n\t\telse if (!strcasecmp(\"TXT\", rectype)) type = DNS_T_TXT;\n\t\telse if (!strcasecmp(\"CNAME\", rectype)) type = DNS_T_CNAME;\n\t\telse if (!strcasecmp(\"AAAA\", rectype)) type = DNS_T_AAAA;\n\t\telse if (!strcasecmp(\"SRV\", rectype)) type = DNS_T_SRV;\n\t\telse if (!strcasecmp(\"NAPTR\", rectype)) type = DNS_T_NAPTR;\n\t\telse if (!strcasecmp(\"A6\", rectype)) type = DNS_T_A6;\n\t\telse {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Type '%s' not supported\", rectype);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t}", "#if defined(HAVE_DNS_SEARCH)\n\thandle = dns_open(NULL);\n\tif (handle == NULL) {\n\t\tRETURN_FALSE;\n\t}\n#elif defined(HAVE_RES_NSEARCH)\n memset(&state, 0, sizeof(state));\n if (res_ninit(handle)) {\n\t\t\tRETURN_FALSE;\n\t}\n#else\n\tres_init();\n#endif", "\tRETVAL_TRUE;\n\ti = php_dns_search(handle, hostname, C_IN, type, ans, sizeof(ans));", "\tif (i < 0) {\n\t\tRETVAL_FALSE;\n\t}", "\tphp_dns_free_handle(handle);\n}\n/* }}} */", "#if HAVE_FULL_DNS_FUNCS", "/* {{{ php_parserr */\nstatic u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray)\n{\n\tu_short type, class, dlen;\n\tu_long ttl;\n\tlong n, i;\n\tu_short s;\n\tu_char *tp, *p;\n\tchar name[MAXHOSTNAMELEN];\n\tint have_v6_break = 0, in_v6_break = 0;", "\t*subarray = NULL;", "\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, sizeof(name) - 2);\n\tif (n < 0) {\n\t\treturn NULL;\n\t}\n\tcp += n;", "\tGETSHORT(type, cp);\n\tGETSHORT(class, cp);\n\tGETLONG(ttl, cp);\n\tGETSHORT(dlen, cp);\n\tif (type_to_fetch != T_ANY && type != type_to_fetch) {\n\t\tcp += dlen;\n\t\treturn cp;\n\t}", "\tif (!store) {\n\t\tcp += dlen;\n\t\treturn cp;\n\t}", "\tALLOC_INIT_ZVAL(*subarray);\n\tarray_init(*subarray);", "\tadd_assoc_string(*subarray, \"host\", name, 1);\n\tadd_assoc_string(*subarray, \"class\", \"IN\", 1);\n\tadd_assoc_long(*subarray, \"ttl\", ttl);", "\tif (raw) {\n\t\tadd_assoc_long(*subarray, \"type\", type);\n\t\tadd_assoc_stringl(*subarray, \"data\", (char*) cp, (uint) dlen, 1);\n\t\tcp += dlen;\n\t\treturn cp;\n\t}", "\tswitch (type) {\n\t\tcase DNS_T_A:\n\t\t\tadd_assoc_string(*subarray, \"type\", \"A\", 1);\n\t\t\tsnprintf(name, sizeof(name), \"%d.%d.%d.%d\", cp[0], cp[1], cp[2], cp[3]);\n\t\t\tadd_assoc_string(*subarray, \"ip\", name, 1);\n\t\t\tcp += dlen;\n\t\t\tbreak;\n\t\tcase DNS_T_MX:\n\t\t\tadd_assoc_string(*subarray, \"type\", \"MX\", 1);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"pri\", n);\n\t\t\t/* no break; */\n\t\tcase DNS_T_CNAME:\n\t\t\tif (type == DNS_T_CNAME) {\n\t\t\t\tadd_assoc_string(*subarray, \"type\", \"CNAME\", 1);\n\t\t\t}\n\t\t\t/* no break; */\n\t\tcase DNS_T_NS:\n\t\t\tif (type == DNS_T_NS) {\n\t\t\t\tadd_assoc_string(*subarray, \"type\", \"NS\", 1);\n\t\t\t}\n\t\t\t/* no break; */\n\t\tcase DNS_T_PTR:\n\t\t\tif (type == DNS_T_PTR) {\n\t\t\t\tadd_assoc_string(*subarray, \"type\", \"PTR\", 1);\n\t\t\t}\n\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(*subarray, \"target\", name, 1);\n\t\t\tbreak;\n\t\tcase DNS_T_HINFO:\n\t\t\t/* See RFC 1010 for values */\n\t\t\tadd_assoc_string(*subarray, \"type\", \"HINFO\", 1);\n\t\t\tn = *cp & 0xFF;\n\t\t\tcp++;\n\t\t\tadd_assoc_stringl(*subarray, \"cpu\", (char*)cp, n, 1);\n\t\t\tcp += n;\n\t\t\tn = *cp & 0xFF;\n\t\t\tcp++;\n\t\t\tadd_assoc_stringl(*subarray, \"os\", (char*)cp, n, 1);\n\t\t\tcp += n;\n\t\t\tbreak;\n\t\tcase DNS_T_TXT:\n\t\t\t{\n\t\t\t\tint ll = 0;\n\t\t\t\tzval *entries = NULL;", "\t\t\t\tadd_assoc_string(*subarray, \"type\", \"TXT\", 1);\n\t\t\t\ttp = emalloc(dlen + 1);\n\t\t\t\t\n\t\t\t\tMAKE_STD_ZVAL(entries);\n\t\t\t\tarray_init(entries);\n\t\t\t\t\n\t\t\t\twhile (ll < dlen) {\n\t\t\t\t\tn = cp[ll];", "", "\t\t\t\t\tmemcpy(tp + ll , cp + ll + 1, n);\n\t\t\t\t\tadd_next_index_stringl(entries, cp + ll + 1, n, 1);\n\t\t\t\t\tll = ll + n + 1;\n\t\t\t\t}\n\t\t\t\ttp[dlen] = '\\0';\n\t\t\t\tcp += dlen;", "\t\t\t\tadd_assoc_stringl(*subarray, \"txt\", tp, (dlen>0)?dlen - 1:0, 0);\n\t\t\t\tadd_assoc_zval(*subarray, \"entries\", entries);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DNS_T_SOA:\n\t\t\tadd_assoc_string(*subarray, \"type\", \"SOA\", 1);\n\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(*subarray, \"mname\", name, 1);\n\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(*subarray, \"rname\", name, 1);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"serial\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"refresh\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"retry\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"expire\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"minimum-ttl\", n);\n\t\t\tbreak;\n\t\tcase DNS_T_AAAA:\n\t\t\ttp = (u_char*)name;\n\t\t\tfor(i=0; i < 8; i++) {\n\t\t\t\tGETSHORT(s, cp);\n\t\t\t\tif (s != 0) {\n\t\t\t\t\tif (tp > (u_char *)name) {\n\t\t\t\t\t\tin_v6_break = 0;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t\ttp += sprintf((char*)tp,\"%x\",s);\n\t\t\t\t} else {\n\t\t\t\t\tif (!have_v6_break) {\n\t\t\t\t\t\thave_v6_break = 1;\n\t\t\t\t\t\tin_v6_break = 1;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t} else if (!in_v6_break) {\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t\ttp[0] = '0';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (have_v6_break && in_v6_break) {\n\t\t\t\ttp[0] = ':';\n\t\t\t\ttp++;\n\t\t\t}\n\t\t\ttp[0] = '\\0';\n\t\t\tadd_assoc_string(*subarray, \"type\", \"AAAA\", 1);\n\t\t\tadd_assoc_string(*subarray, \"ipv6\", name, 1);\n\t\t\tbreak;\n\t\tcase DNS_T_A6:\n\t\t\tp = cp;\n\t\t\tadd_assoc_string(*subarray, \"type\", \"A6\", 1);\n\t\t\tn = ((int)cp[0]) & 0xFF;\n\t\t\tcp++;\n\t\t\tadd_assoc_long(*subarray, \"masklen\", n);\n\t\t\ttp = (u_char*)name;\n\t\t\tif (n > 15) {\n\t\t\t\thave_v6_break = 1;\n\t\t\t\tin_v6_break = 1;\n\t\t\t\ttp[0] = ':';\n\t\t\t\ttp++;\n\t\t\t}\n\t\t\tif (n % 16 > 8) {\n\t\t\t\t/* Partial short */\n\t\t\t\tif (cp[0] != 0) {\n\t\t\t\t\tif (tp > (u_char *)name) {\n\t\t\t\t\t\tin_v6_break = 0;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t\tsprintf((char*)tp, \"%x\", cp[0] & 0xFF);\n\t\t\t\t} else {\n\t\t\t\t\tif (!have_v6_break) {\n\t\t\t\t\t\thave_v6_break = 1;\n\t\t\t\t\t\tin_v6_break = 1;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t} else if (!in_v6_break) {\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t\ttp[0] = '0';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcp++;\n\t\t\t}\n\t\t\tfor (i = (n + 8) / 16; i < 8; i++) {\n\t\t\t\tGETSHORT(s, cp);\n\t\t\t\tif (s != 0) {\n\t\t\t\t\tif (tp > (u_char *)name) {\n\t\t\t\t\t\tin_v6_break = 0;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t\ttp += sprintf((char*)tp,\"%x\",s);\n\t\t\t\t} else {\n\t\t\t\t\tif (!have_v6_break) {\n\t\t\t\t\t\thave_v6_break = 1;\n\t\t\t\t\t\tin_v6_break = 1;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t} else if (!in_v6_break) {\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t\ttp[0] = '0';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (have_v6_break && in_v6_break) {\n\t\t\t\ttp[0] = ':';\n\t\t\t\ttp++;\n\t\t\t}\n\t\t\ttp[0] = '\\0';\n\t\t\tadd_assoc_string(*subarray, \"ipv6\", name, 1);\n\t\t\tif (cp < p + dlen) {\n\t\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);\n\t\t\t\tif (n < 0) {\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\tcp += n;\n\t\t\t\tadd_assoc_string(*subarray, \"chain\", name, 1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DNS_T_SRV:\n\t\t\tadd_assoc_string(*subarray, \"type\", \"SRV\", 1);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"pri\", n);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"weight\", n);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"port\", n);\n\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(*subarray, \"target\", name, 1);\n\t\t\tbreak;\n\t\tcase DNS_T_NAPTR:\n\t\t\tadd_assoc_string(*subarray, \"type\", \"NAPTR\", 1);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"order\", n);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"pref\", n);\n\t\t\tn = (cp[0] & 0xFF);\n\t\t\tadd_assoc_stringl(*subarray, \"flags\", (char*)++cp, n, 1);\n\t\t\tcp += n;\n\t\t\tn = (cp[0] & 0xFF);\n\t\t\tadd_assoc_stringl(*subarray, \"services\", (char*)++cp, n, 1);\n\t\t\tcp += n;\n\t\t\tn = (cp[0] & 0xFF);\n\t\t\tadd_assoc_stringl(*subarray, \"regex\", (char*)++cp, n, 1);\n\t\t\tcp += n;\n\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(*subarray, \"replacement\", name, 1);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tzval_ptr_dtor(subarray);\n\t\t\t*subarray = NULL;\n\t\t\tcp += dlen;\n\t\t\tbreak;\n\t}", "\treturn cp;\n}\n/* }}} */", "/* {{{ proto array|false dns_get_record(string hostname [, int type[, array authns, array addtl]])\n Get any Resource Record corresponding to a given Internet host name */\nPHP_FUNCTION(dns_get_record)\n{\n\tchar *hostname;\n\tint hostname_len;\n\tlong type_param = PHP_DNS_ANY;\n\tzval *authns = NULL, *addtl = NULL;\n\tint type_to_fetch;\n#if defined(HAVE_DNS_SEARCH)\n\tstruct sockaddr_storage from;\n\tuint32_t fromsize = sizeof(from);\n\tdns_handle_t handle;\n#elif defined(HAVE_RES_NSEARCH)\n\tstruct __res_state state;\n\tstruct __res_state *handle = &state;\n#endif\n\tHEADER *hp;\n\tquerybuf answer;\n\tu_char *cp = NULL, *end = NULL;\n\tint n, qd, an, ns = 0, ar = 0;\n\tint type, first_query = 1, store_results = 1;\n\tzend_bool raw = 0;", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|lz!z!b\",\n\t\t\t&hostname, &hostname_len, &type_param, &authns, &addtl, &raw) == FAILURE) {\n\t\treturn;\n\t}", "\tif (authns) {\n\t\tzval_dtor(authns);\n\t\tarray_init(authns);\n\t}\n\tif (addtl) {\n\t\tzval_dtor(addtl);\n\t\tarray_init(addtl);\n\t}", "\tif (!raw) {\n\t\tif ((type_param & ~PHP_DNS_ALL) && (type_param != PHP_DNS_ANY)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Type '%ld' not supported\", type_param);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t} else {\n\t\tif ((type_param < 1) || (type_param > 0xFFFF)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING,\n\t\t\t\t\"Numeric DNS record type must be between 1 and 65535, '%ld' given\", type_param);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t}", "\t/* Initialize the return array */\n\tarray_init(return_value);", "\t/* - We emulate an or'ed type mask by querying type by type. (Steps 0 - NUMTYPES-1 )\n\t * If additional info is wanted we check again with DNS_T_ANY (step NUMTYPES / NUMTYPES+1 )\n\t * store_results is used to skip storing the results retrieved in step\n\t * NUMTYPES+1 when results were already fetched.\n\t * - In case of PHP_DNS_ANY we use the directly fetch DNS_T_ANY. (step NUMTYPES+1 )\n\t * - In case of raw mode, we query only the requestd type instead of looping type by type\n\t * before going with the additional info stuff.\n\t */", "\tif (raw) {\n\t\ttype = -1;\n\t} else if (type_param == PHP_DNS_ANY) {\n\t\ttype = PHP_DNS_NUM_TYPES + 1;\n\t} else {\n\t\ttype = 0;\n\t}", "\tfor ( ;\n\t\ttype < (addtl ? (PHP_DNS_NUM_TYPES + 2) : PHP_DNS_NUM_TYPES) || first_query;\n\t\ttype++\n\t) {\n\t\tfirst_query = 0;\n\t\tswitch (type) {\n\t\t\tcase -1: /* raw */\n\t\t\t\ttype_to_fetch = type_param;\n\t\t\t\t/* skip over the rest and go directly to additional records */\n\t\t\t\ttype = PHP_DNS_NUM_TYPES - 1;\n\t\t\t\tbreak;\n\t\t\tcase 0:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_A ? DNS_T_A : 0;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_NS ? DNS_T_NS : 0;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_CNAME ? DNS_T_CNAME : 0;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_SOA ? DNS_T_SOA : 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_PTR ? DNS_T_PTR : 0;\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_HINFO ? DNS_T_HINFO : 0;\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_MX ? DNS_T_MX : 0;\n\t\t\t\tbreak;\n\t\t\tcase 7:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_TXT ? DNS_T_TXT : 0;\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_AAAA\t ? DNS_T_AAAA : 0;\n\t\t\t\tbreak;\n\t\t\tcase 9:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_SRV ? DNS_T_SRV : 0;\n\t\t\t\tbreak;\n\t\t\tcase 10:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_NAPTR ? DNS_T_NAPTR : 0;\n\t\t\t\tbreak;\n\t\t\tcase 11:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_A6\t ? DNS_T_A6 : 0;\n\t\t\t\tbreak;\n\t\t\tcase PHP_DNS_NUM_TYPES:\n\t\t\t\tstore_results = 0;\n\t\t\t\tcontinue;\n\t\t\tdefault:\n\t\t\tcase (PHP_DNS_NUM_TYPES + 1):\n\t\t\t\ttype_to_fetch = DNS_T_ANY;\n\t\t\t\tbreak;\n\t\t}", "\t\tif (type_to_fetch) {\n#if defined(HAVE_DNS_SEARCH)\n\t\t\thandle = dns_open(NULL);\n\t\t\tif (handle == NULL) {\n\t\t\t\tzval_dtor(return_value);\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n#elif defined(HAVE_RES_NSEARCH)\n\t\t memset(&state, 0, sizeof(state));\n\t\t if (res_ninit(handle)) {\n\t\t \tzval_dtor(return_value);\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n#else\n\t\t\tres_init();\n#endif", "\t\t\tn = php_dns_search(handle, hostname, C_IN, type_to_fetch, answer.qb2, sizeof answer);", "\t\t\tif (n < 0) {\n\t\t\t\tphp_dns_free_handle(handle);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tcp = answer.qb2 + HFIXEDSZ;\n\t\t\tend = answer.qb2 + n;\n\t\t\thp = (HEADER *)&answer;\n\t\t\tqd = ntohs(hp->qdcount);\n\t\t\tan = ntohs(hp->ancount);\n\t\t\tns = ntohs(hp->nscount);\n\t\t\tar = ntohs(hp->arcount);", "\t\t\t/* Skip QD entries, they're only used by dn_expand later on */\n\t\t\twhile (qd-- > 0) {\n\t\t\t\tn = dn_skipname(cp, end);\n\t\t\t\tif (n < 0) {\n\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Unable to parse DNS data received\");\n\t\t\t\t\tzval_dtor(return_value);\n\t\t\t\t\tphp_dns_free_handle(handle);\n\t\t\t\t\tRETURN_FALSE;\n\t\t\t\t}\n\t\t\t\tcp += n + QFIXEDSZ;\n\t\t\t}", "\t\t\t/* YAY! Our real answers! */\n\t\t\twhile (an-- && cp && cp < end) {\n\t\t\t\tzval *retval;", "\t\t\t\tcp = php_parserr(cp, &answer, type_to_fetch, store_results, raw, &retval);\n\t\t\t\tif (retval != NULL && store_results) {\n\t\t\t\t\tadd_next_index_zval(return_value, retval);\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (authns || addtl) {\n\t\t\t\t/* List of Authoritative Name Servers\n\t\t\t\t * Process when only requesting addtl so that we can skip through the section\n\t\t\t\t */\n\t\t\t\twhile (ns-- > 0 && cp && cp < end) {\n\t\t\t\t\tzval *retval = NULL;", "\t\t\t\t\tcp = php_parserr(cp, &answer, DNS_T_ANY, authns != NULL, raw, &retval);\n\t\t\t\t\tif (retval != NULL) {\n\t\t\t\t\t\tadd_next_index_zval(authns, retval);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (addtl) {\n\t\t\t\t/* Additional records associated with authoritative name servers */\n\t\t\t\twhile (ar-- > 0 && cp && cp < end) {\n\t\t\t\t\tzval *retval = NULL;", "\t\t\t\t\tcp = php_parserr(cp, &answer, DNS_T_ANY, 1, raw, &retval);\n\t\t\t\t\tif (retval != NULL) {\n\t\t\t\t\t\tadd_next_index_zval(addtl, retval);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tphp_dns_free_handle(handle);\n\t\t}\n\t}\n}\n/* }}} */", "/* {{{ proto bool dns_get_mx(string hostname, array mxhosts [, array weight])\n Get MX records corresponding to a given Internet host name */\nPHP_FUNCTION(dns_get_mx)\n{\n\tchar *hostname;\n\tint hostname_len;\n\tzval *mx_list, *weight_list = NULL;\n\tint count, qdc;\n\tu_short type, weight;\n\tu_char ans[MAXPACKET];\n\tchar buf[MAXHOSTNAMELEN];\n\tHEADER *hp;\n\tu_char *cp, *end;\n\tint i;\n#if defined(HAVE_DNS_SEARCH)\n\tstruct sockaddr_storage from;\n\tuint32_t fromsize = sizeof(from);\n\tdns_handle_t handle;\n#elif defined(HAVE_RES_NSEARCH)\n\tstruct __res_state state;\n\tstruct __res_state *handle = &state;\n#endif", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"sz|z\", &hostname, &hostname_len, &mx_list, &weight_list) == FAILURE) {\n\t\treturn;\n\t}", "\tzval_dtor(mx_list);\n\tarray_init(mx_list);", "\tif (weight_list) {\n\t\tzval_dtor(weight_list);\n\t\tarray_init(weight_list);\n\t}", "#if defined(HAVE_DNS_SEARCH)\n\thandle = dns_open(NULL);\n\tif (handle == NULL) {\n\t\tRETURN_FALSE;\n\t}\n#elif defined(HAVE_RES_NSEARCH)\n memset(&state, 0, sizeof(state));\n if (res_ninit(handle)) {\n\t\t\tRETURN_FALSE;\n\t}\n#else\n\tres_init();\n#endif", "\ti = php_dns_search(handle, hostname, C_IN, DNS_T_MX, (u_char *)&ans, sizeof(ans));\n\tif (i < 0) {\n\t\tRETURN_FALSE;\n\t}\n\tif (i > (int)sizeof(ans)) {\n\t\ti = sizeof(ans);\n\t}\n\thp = (HEADER *)&ans;\n\tcp = (u_char *)&ans + HFIXEDSZ;\n\tend = (u_char *)&ans +i;\n\tfor (qdc = ntohs((unsigned short)hp->qdcount); qdc--; cp += i + QFIXEDSZ) {\n\t\tif ((i = dn_skipname(cp, end)) < 0 ) {\n\t\t\tphp_dns_free_handle(handle);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t}\n\tcount = ntohs((unsigned short)hp->ancount);\n\twhile (--count >= 0 && cp < end) {\n\t\tif ((i = dn_skipname(cp, end)) < 0 ) {\n\t\t\tphp_dns_free_handle(handle);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t\tcp += i;\n\t\tGETSHORT(type, cp);\n\t\tcp += INT16SZ + INT32SZ;\n\t\tGETSHORT(i, cp);\n\t\tif (type != DNS_T_MX) {\n\t\t\tcp += i;\n\t\t\tcontinue;\n\t\t}\n\t\tGETSHORT(weight, cp);\n\t\tif ((i = dn_expand(ans, end, cp, buf, sizeof(buf)-1)) < 0) {\n\t\t\tphp_dns_free_handle(handle);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t\tcp += i;\n\t\tadd_next_index_string(mx_list, buf, 1);\n\t\tif (weight_list) {\n\t\t\tadd_next_index_long(weight_list, weight);\n\t\t}\n\t}\n\tphp_dns_free_handle(handle);\n\tRETURN_TRUE;\n}\n/* }}} */\n#endif /* HAVE_FULL_DNS_FUNCS */\n#endif /* !defined(PHP_WIN32) && (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) */", "#if HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32)\nPHP_MINIT_FUNCTION(dns) {\n\tREGISTER_LONG_CONSTANT(\"DNS_A\", PHP_DNS_A, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_NS\", PHP_DNS_NS, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_CNAME\", PHP_DNS_CNAME, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_SOA\", PHP_DNS_SOA, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_PTR\", PHP_DNS_PTR, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_HINFO\", PHP_DNS_HINFO, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_MX\", PHP_DNS_MX, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_TXT\", PHP_DNS_TXT, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_SRV\", PHP_DNS_SRV, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_NAPTR\", PHP_DNS_NAPTR, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_AAAA\", PHP_DNS_AAAA, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_A6\", PHP_DNS_A6, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_ANY\", PHP_DNS_ANY, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_ALL\", PHP_DNS_ALL, CONST_CS | CONST_PERSISTENT);\n\treturn SUCCESS;\n}\n#endif /* HAVE_FULL_DNS_FUNCS */", "/*\n * Local variables:\n * tab-width: 4\n * c-basic-offset: 4\n * End:\n * vim600: sw=4 ts=4 fdm=marker\n * vim<600: sw=4 ts=4\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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [519], "buggy_code_start_loc": [519], "filenames": ["ext/standard/dns.c"], "fixing_code_end_loc": [524], "fixing_code_start_loc": [520], "message": "Heap-based buffer overflow in the php_parserr function in ext/standard/dns.c in PHP 5.6.0beta4 and earlier allows remote servers to cause a denial of service (crash) and possibly execute arbitrary code via a crafted DNS TXT record, related to the dns_get_record function.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:opensuse:11.3:*:*:*:*:*:*:*", "matchCriteriaId": "5646FDE9-CF21-46A9-B89D-F5BBDB4249AF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:php:php:*:*:*:*:*:*:*:*", "matchCriteriaId": "B61C8E39-DB8E-4636-91E5-2473B0915FBD", "versionEndExcluding": "5.3.29", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "5.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:*:*:*:*:*:*:*:*", "matchCriteriaId": "AD052020-AA37-4F49-A0FE-EA99616C12C7", "versionEndExcluding": "5.4.30", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "5.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:*:*:*:*:*:*:*:*", "matchCriteriaId": "4ADC6057-9D35-4D87-B15D-F6F52A283464", "versionEndExcluding": "5.5.14", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "5.5.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "5BF4E8FF-A3EC-43E8-A0C1-FD38AFCB77B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "54ADECFC-3C07-43BC-B296-6C25AC7F1C95", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "FE192054-2FBB-4388-A52A-422E20DEA2D7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:alpha4:*:*:*:*:*:*", "matchCriteriaId": "F0195D48-3B42-4AC0-B9C5-436E01C63879", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:alpha5:*:*:*:*:*:*", "matchCriteriaId": "BF0E5D67-ABC1-41A5-94E1-7DD3CDB51D81", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:beta1:*:*:*:*:*:*", "matchCriteriaId": "319E0573-B1AD-40B6-B4BC-8BE67ED3EFDB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:beta2:*:*:*:*:*:*", "matchCriteriaId": "1A7C00EB-87B7-4EB7-A4AC-8665D8C78467", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:beta3:*:*:*:*:*:*", "matchCriteriaId": "21BFCF10-786A-4D1E-9C37-50A1EC6056F1", "versionEndExcluding": null, "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: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}], "descriptions": [{"lang": "en", "value": "Heap-based buffer overflow in the php_parserr function in ext/standard/dns.c in PHP 5.6.0beta4 and earlier allows remote servers to cause a denial of service (crash) and possibly execute arbitrary code via a crafted DNS TXT record, related to the dns_get_record function."}, {"lang": "es", "value": "Desbordamiento de buffer basado en memoria din\u00e1mica en la funci\u00f3n php_parserr en ext/standard/dns.c en PHP 5.6.0beta4 y anteriores permite a servidores remotos causar una denegaci\u00f3n de servicio (ca\u00edda) y posiblemente ejecutar c\u00f3digo arbitrario a trav\u00e9s de un registro DNS TXT manipulado, relacionado con la funci\u00f3n dns_get_record."}], "evaluatorComment": null, "id": "CVE-2014-4049", "lastModified": "2022-08-29T20:05:23.073", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "HIGH", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.1, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:H/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.9, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-06-18T19:55:05.683", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.apple.com/archives/security-announce/2015/Apr/msg00001.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2014-07/msg00001.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2014-07/msg00002.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2014-06/msg00051.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2014-07/msg00032.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://marc.info/?l=bugtraq&m=141017844705317&w=2"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2014-1765.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2014-1766.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://secunia.com/advisories/59329"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://secunia.com/advisories/59418"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://secunia.com/advisories/59496"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://secunia.com/advisories/59513"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://secunia.com/advisories/60998"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://support.apple.com/kb/HT6443"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www-01.ibm.com/support/docview.wss?uid=swg21683486"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2014/dsa-2961"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/06/13/4"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.oracle.com/technetwork/topics/security/bulletinjan2015-2370101.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/68007"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securitytracker.com/id/1030435"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1108447"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/php/php-src/commit/b34d7849ed90ced9345f8ea1c59bc8d101c18468"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/HT204659"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/php/php-src/commit/b34d7849ed90ced9345f8ea1c59bc8d101c18468"}, "type": "CWE-119"}
231
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n +----------------------------------------------------------------------+\n | PHP Version 5 |\n +----------------------------------------------------------------------+\n | Copyright (c) 1997-2014 The PHP Group |\n +----------------------------------------------------------------------+\n | This source file is subject to version 3.01 of the PHP license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http://www.php.net/license/3_01.txt |\n | If you did not receive a copy of the PHP license and are unable to |\n | obtain it through the world-wide-web, please send a note to |\n | license@php.net so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Authors: The typical suspects |\n | Pollita <pollita@php.net> |\n | Marcus Boerger <helly@php.net> |\n +----------------------------------------------------------------------+\n */", "/* $Id$ */", "/* {{{ includes */\n#include \"php.h\"\n#include \"php_network.h\"", "#if HAVE_SYS_SOCKET_H\n#include <sys/socket.h>\n#endif", "#ifdef PHP_WIN32\n# include \"win32/inet.h\"\n# include <winsock2.h>\n# include <windows.h>\n# include <Ws2tcpip.h>\n#else\t/* This holds good for NetWare too, both for Winsock and Berkeley sockets */\n#include <netinet/in.h>\n#if HAVE_ARPA_INET_H\n#include <arpa/inet.h>\n#endif\n#include <netdb.h>\n#ifdef _OSD_POSIX\n#undef STATUS\n#undef T_UNSPEC\n#endif\n#if HAVE_ARPA_NAMESER_H\n#ifdef DARWIN\n# define BIND_8_COMPAT 1\n#endif\n#include <arpa/nameser.h>\n#endif\n#if HAVE_RESOLV_H\n#include <resolv.h>\n#endif\n#ifdef HAVE_DNS_H\n#include <dns.h>\n#endif\n#endif", "/* Borrowed from SYS/SOCKET.H */\n#if defined(NETWARE) && defined(USE_WINSOCK)\n#define AF_INET 2 /* internetwork: UDP, TCP, etc. */\n#endif", "#ifndef MAXHOSTNAMELEN\n#define MAXHOSTNAMELEN 255\n#endif", "/* For the local hostname obtained via gethostname which is different from the\n dns-related MAXHOSTNAMELEN constant above */\n#ifndef HOST_NAME_MAX\n#define HOST_NAME_MAX 255\n#endif", "#include \"php_dns.h\"", "/* type compat */\n#ifndef DNS_T_A\n#define DNS_T_A\t\t1\n#endif\n#ifndef DNS_T_NS\n#define DNS_T_NS\t2\n#endif\n#ifndef DNS_T_CNAME\n#define DNS_T_CNAME\t5\n#endif\n#ifndef DNS_T_SOA\n#define DNS_T_SOA\t6\n#endif\n#ifndef DNS_T_PTR\n#define DNS_T_PTR\t12\n#endif\n#ifndef DNS_T_HINFO\n#define DNS_T_HINFO\t13\n#endif\n#ifndef DNS_T_MINFO\n#define DNS_T_MINFO\t14\n#endif\n#ifndef DNS_T_MX\n#define DNS_T_MX\t15\n#endif\n#ifndef DNS_T_TXT\n#define DNS_T_TXT\t16\n#endif\n#ifndef DNS_T_AAAA\n#define DNS_T_AAAA\t28\n#endif\n#ifndef DNS_T_SRV\n#define DNS_T_SRV\t33\n#endif\n#ifndef DNS_T_NAPTR\n#define DNS_T_NAPTR\t35\n#endif\n#ifndef DNS_T_A6\n#define DNS_T_A6\t38\n#endif", "#ifndef DNS_T_ANY\n#define DNS_T_ANY\t255\n#endif\n/* }}} */", "static char *php_gethostbyaddr(char *ip);\nstatic char *php_gethostbyname(char *name);", "#ifdef HAVE_GETHOSTNAME\n/* {{{ proto string gethostname()\n Get the host name of the current machine */\nPHP_FUNCTION(gethostname)\n{\n\tchar buf[HOST_NAME_MAX];", "\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}", "\tif (gethostname(buf, sizeof(buf) - 1)) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"unable to fetch host [%d]: %s\", errno, strerror(errno));\n\t\tRETURN_FALSE;\n\t}", "\tRETURN_STRING(buf, 1);\n}\n/* }}} */\n#endif", "/* TODO: Reimplement the gethostby* functions using the new winxp+ API, in dns_win32.c, then\n we can have a dns.c, dns_unix.c and dns_win32.c instead of a messy dns.c full of #ifdef\n*/", "/* {{{ proto string gethostbyaddr(string ip_address)\n Get the Internet host name corresponding to a given IP address */\nPHP_FUNCTION(gethostbyaddr)\n{\n\tchar *addr;\n\tint addr_len;\n\tchar *hostname;", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &addr, &addr_len) == FAILURE) {\n\t\treturn;\n\t}", "\thostname = php_gethostbyaddr(addr);", "\tif (hostname == NULL) {\n#if HAVE_IPV6 && HAVE_INET_PTON\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Address is not a valid IPv4 or IPv6 address\");\n#else\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Address is not in a.b.c.d form\");\n#endif\n\t\tRETVAL_FALSE;\n\t} else {\n\t\tRETVAL_STRING(hostname, 0);\n\t}\n}\n/* }}} */", "/* {{{ php_gethostbyaddr */\nstatic char *php_gethostbyaddr(char *ip)\n{\n#if HAVE_IPV6 && HAVE_INET_PTON\n\tstruct in6_addr addr6;\n#endif\n\tstruct in_addr addr;\n\tstruct hostent *hp;", "#if HAVE_IPV6 && HAVE_INET_PTON\n\tif (inet_pton(AF_INET6, ip, &addr6)) {\n\t\thp = gethostbyaddr((char *) &addr6, sizeof(addr6), AF_INET6);\n\t} else if (inet_pton(AF_INET, ip, &addr)) {\n\t\thp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET);\n\t} else {\n\t\treturn NULL;\n\t}\n#else\n\taddr.s_addr = inet_addr(ip);", "\tif (addr.s_addr == -1) {\n\t\treturn NULL;\n\t}", "\thp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET);\n#endif", "\tif (!hp || hp->h_name == NULL || hp->h_name[0] == '\\0') {\n\t\treturn estrdup(ip);\n\t}", "\treturn estrdup(hp->h_name);\n}\n/* }}} */", "/* {{{ proto string gethostbyname(string hostname)\n Get the IP address corresponding to a given Internet host name */\nPHP_FUNCTION(gethostbyname)\n{\n\tchar *hostname;\n\tint hostname_len;\n\tchar *addr;", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &hostname, &hostname_len) == FAILURE) {\n\t\treturn;\n\t}", "\taddr = php_gethostbyname(hostname);", "\tRETVAL_STRING(addr, 0);\n}\n/* }}} */", "/* {{{ proto array gethostbynamel(string hostname)\n Return a list of IP addresses that a given hostname resolves to. */\nPHP_FUNCTION(gethostbynamel)\n{\n\tchar *hostname;\n\tint hostname_len;\n\tstruct hostent *hp;\n\tstruct in_addr in;\n\tint i;", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &hostname, &hostname_len) == FAILURE) {\n\t\treturn;\n\t}", "\thp = gethostbyname(hostname);\n\tif (hp == NULL || hp->h_addr_list == NULL) {\n\t\tRETURN_FALSE;\n\t}", "\tarray_init(return_value);", "\tfor (i = 0 ; hp->h_addr_list[i] != 0 ; i++) {\n\t\tin = *(struct in_addr *) hp->h_addr_list[i];\n\t\tadd_next_index_string(return_value, inet_ntoa(in), 1);\n\t}\n}\n/* }}} */", "/* {{{ php_gethostbyname */\nstatic char *php_gethostbyname(char *name)\n{\n\tstruct hostent *hp;\n\tstruct in_addr in;", "\thp = gethostbyname(name);", "\tif (!hp || !*(hp->h_addr_list)) {\n\t\treturn estrdup(name);\n\t}", "\tmemcpy(&in.s_addr, *(hp->h_addr_list), sizeof(in.s_addr));", "\treturn estrdup(inet_ntoa(in));\n}\n/* }}} */", "#if HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32)\n# define PHP_DNS_NUM_TYPES\t12\t/* Number of DNS Types Supported by PHP currently */", "# define PHP_DNS_A 0x00000001\n# define PHP_DNS_NS 0x00000002\n# define PHP_DNS_CNAME 0x00000010\n# define PHP_DNS_SOA 0x00000020\n# define PHP_DNS_PTR 0x00000800\n# define PHP_DNS_HINFO 0x00001000\n# define PHP_DNS_MX 0x00004000\n# define PHP_DNS_TXT 0x00008000\n# define PHP_DNS_A6 0x01000000\n# define PHP_DNS_SRV 0x02000000\n# define PHP_DNS_NAPTR 0x04000000\n# define PHP_DNS_AAAA 0x08000000\n# define PHP_DNS_ANY 0x10000000\n# define PHP_DNS_ALL (PHP_DNS_A|PHP_DNS_NS|PHP_DNS_CNAME|PHP_DNS_SOA|PHP_DNS_PTR|PHP_DNS_HINFO|PHP_DNS_MX|PHP_DNS_TXT|PHP_DNS_A6|PHP_DNS_SRV|PHP_DNS_NAPTR|PHP_DNS_AAAA)\n#endif /* HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32) */", "/* Note: These functions are defined in ext/standard/dns_win32.c for Windows! */\n#if !defined(PHP_WIN32) && (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE)))\n \n#ifndef HFIXEDSZ\n#define HFIXEDSZ 12 /* fixed data in header <arpa/nameser.h> */\n#endif /* HFIXEDSZ */", "#ifndef QFIXEDSZ\n#define QFIXEDSZ 4 /* fixed data in query <arpa/nameser.h> */\n#endif /* QFIXEDSZ */", "#undef MAXHOSTNAMELEN\n#define MAXHOSTNAMELEN 1024", "#ifndef MAXRESOURCERECORDS\n#define MAXRESOURCERECORDS\t64\n#endif /* MAXRESOURCERECORDS */", "typedef union {\n\tHEADER qb1;\n\tu_char qb2[65536];\n} querybuf;", "/* just a hack to free resources allocated by glibc in __res_nsend()\n * See also:\n * res_thread_freeres() in glibc/resolv/res_init.c\n * __libc_res_nsend() in resolv/res_send.c\n * */", "#if defined(__GLIBC__) && !defined(HAVE_DEPRECATED_DNS_FUNCS)\n#define php_dns_free_res(__res__) _php_dns_free_res(__res__)\nstatic void _php_dns_free_res(struct __res_state res) { /* {{{ */\n\tint ns;\n\tfor (ns = 0; ns < MAXNS; ns++) {\n\t\tif (res._u._ext.nsaddrs[ns] != NULL) {\n\t\t\tfree (res._u._ext.nsaddrs[ns]);\n\t\t\tres._u._ext.nsaddrs[ns] = NULL;\n\t\t}\n\t}\n} /* }}} */\n#else\n#define php_dns_free_res(__res__)\n#endif", "/* {{{ proto bool dns_check_record(string host [, string type])\n Check DNS records corresponding to a given Internet host name or IP address */\nPHP_FUNCTION(dns_check_record)\n{\n#ifndef MAXPACKET\n#define MAXPACKET 8192 /* max packet size used internally by BIND */\n#endif\n\tu_char ans[MAXPACKET];\n\tchar *hostname, *rectype = NULL;\n\tint hostname_len, rectype_len = 0;\n\tint type = T_MX, i;\n#if defined(HAVE_DNS_SEARCH)\n\tstruct sockaddr_storage from;\n\tuint32_t fromsize = sizeof(from);\n\tdns_handle_t handle;\n#elif defined(HAVE_RES_NSEARCH)\n\tstruct __res_state state;\n\tstruct __res_state *handle = &state;\n#endif", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|s\", &hostname, &hostname_len, &rectype, &rectype_len) == FAILURE) {\n\t\treturn;\n\t}", "\tif (hostname_len == 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Host cannot be empty\");\n\t\tRETURN_FALSE;\n\t}", "\tif (rectype) {\n\t\tif (!strcasecmp(\"A\", rectype)) type = T_A;\n\t\telse if (!strcasecmp(\"NS\", rectype)) type = DNS_T_NS;\n\t\telse if (!strcasecmp(\"MX\", rectype)) type = DNS_T_MX;\n\t\telse if (!strcasecmp(\"PTR\", rectype)) type = DNS_T_PTR;\n\t\telse if (!strcasecmp(\"ANY\", rectype)) type = DNS_T_ANY;\n\t\telse if (!strcasecmp(\"SOA\", rectype)) type = DNS_T_SOA;\n\t\telse if (!strcasecmp(\"TXT\", rectype)) type = DNS_T_TXT;\n\t\telse if (!strcasecmp(\"CNAME\", rectype)) type = DNS_T_CNAME;\n\t\telse if (!strcasecmp(\"AAAA\", rectype)) type = DNS_T_AAAA;\n\t\telse if (!strcasecmp(\"SRV\", rectype)) type = DNS_T_SRV;\n\t\telse if (!strcasecmp(\"NAPTR\", rectype)) type = DNS_T_NAPTR;\n\t\telse if (!strcasecmp(\"A6\", rectype)) type = DNS_T_A6;\n\t\telse {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Type '%s' not supported\", rectype);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t}", "#if defined(HAVE_DNS_SEARCH)\n\thandle = dns_open(NULL);\n\tif (handle == NULL) {\n\t\tRETURN_FALSE;\n\t}\n#elif defined(HAVE_RES_NSEARCH)\n memset(&state, 0, sizeof(state));\n if (res_ninit(handle)) {\n\t\t\tRETURN_FALSE;\n\t}\n#else\n\tres_init();\n#endif", "\tRETVAL_TRUE;\n\ti = php_dns_search(handle, hostname, C_IN, type, ans, sizeof(ans));", "\tif (i < 0) {\n\t\tRETVAL_FALSE;\n\t}", "\tphp_dns_free_handle(handle);\n}\n/* }}} */", "#if HAVE_FULL_DNS_FUNCS", "/* {{{ php_parserr */\nstatic u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray)\n{\n\tu_short type, class, dlen;\n\tu_long ttl;\n\tlong n, i;\n\tu_short s;\n\tu_char *tp, *p;\n\tchar name[MAXHOSTNAMELEN];\n\tint have_v6_break = 0, in_v6_break = 0;", "\t*subarray = NULL;", "\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, sizeof(name) - 2);\n\tif (n < 0) {\n\t\treturn NULL;\n\t}\n\tcp += n;", "\tGETSHORT(type, cp);\n\tGETSHORT(class, cp);\n\tGETLONG(ttl, cp);\n\tGETSHORT(dlen, cp);\n\tif (type_to_fetch != T_ANY && type != type_to_fetch) {\n\t\tcp += dlen;\n\t\treturn cp;\n\t}", "\tif (!store) {\n\t\tcp += dlen;\n\t\treturn cp;\n\t}", "\tALLOC_INIT_ZVAL(*subarray);\n\tarray_init(*subarray);", "\tadd_assoc_string(*subarray, \"host\", name, 1);\n\tadd_assoc_string(*subarray, \"class\", \"IN\", 1);\n\tadd_assoc_long(*subarray, \"ttl\", ttl);", "\tif (raw) {\n\t\tadd_assoc_long(*subarray, \"type\", type);\n\t\tadd_assoc_stringl(*subarray, \"data\", (char*) cp, (uint) dlen, 1);\n\t\tcp += dlen;\n\t\treturn cp;\n\t}", "\tswitch (type) {\n\t\tcase DNS_T_A:\n\t\t\tadd_assoc_string(*subarray, \"type\", \"A\", 1);\n\t\t\tsnprintf(name, sizeof(name), \"%d.%d.%d.%d\", cp[0], cp[1], cp[2], cp[3]);\n\t\t\tadd_assoc_string(*subarray, \"ip\", name, 1);\n\t\t\tcp += dlen;\n\t\t\tbreak;\n\t\tcase DNS_T_MX:\n\t\t\tadd_assoc_string(*subarray, \"type\", \"MX\", 1);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"pri\", n);\n\t\t\t/* no break; */\n\t\tcase DNS_T_CNAME:\n\t\t\tif (type == DNS_T_CNAME) {\n\t\t\t\tadd_assoc_string(*subarray, \"type\", \"CNAME\", 1);\n\t\t\t}\n\t\t\t/* no break; */\n\t\tcase DNS_T_NS:\n\t\t\tif (type == DNS_T_NS) {\n\t\t\t\tadd_assoc_string(*subarray, \"type\", \"NS\", 1);\n\t\t\t}\n\t\t\t/* no break; */\n\t\tcase DNS_T_PTR:\n\t\t\tif (type == DNS_T_PTR) {\n\t\t\t\tadd_assoc_string(*subarray, \"type\", \"PTR\", 1);\n\t\t\t}\n\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(*subarray, \"target\", name, 1);\n\t\t\tbreak;\n\t\tcase DNS_T_HINFO:\n\t\t\t/* See RFC 1010 for values */\n\t\t\tadd_assoc_string(*subarray, \"type\", \"HINFO\", 1);\n\t\t\tn = *cp & 0xFF;\n\t\t\tcp++;\n\t\t\tadd_assoc_stringl(*subarray, \"cpu\", (char*)cp, n, 1);\n\t\t\tcp += n;\n\t\t\tn = *cp & 0xFF;\n\t\t\tcp++;\n\t\t\tadd_assoc_stringl(*subarray, \"os\", (char*)cp, n, 1);\n\t\t\tcp += n;\n\t\t\tbreak;\n\t\tcase DNS_T_TXT:\n\t\t\t{\n\t\t\t\tint ll = 0;\n\t\t\t\tzval *entries = NULL;", "\t\t\t\tadd_assoc_string(*subarray, \"type\", \"TXT\", 1);\n\t\t\t\ttp = emalloc(dlen + 1);\n\t\t\t\t\n\t\t\t\tMAKE_STD_ZVAL(entries);\n\t\t\t\tarray_init(entries);\n\t\t\t\t\n\t\t\t\twhile (ll < dlen) {\n\t\t\t\t\tn = cp[ll];", "\t\t\t\t\tif ((ll + n) >= dlen) {\n\t\t\t\t\t\t// Invalid chunk length, truncate\n\t\t\t\t\t\tn = dlen - (ll + 1);\n\t\t\t\t\t}", "\t\t\t\t\tmemcpy(tp + ll , cp + ll + 1, n);\n\t\t\t\t\tadd_next_index_stringl(entries, cp + ll + 1, n, 1);\n\t\t\t\t\tll = ll + n + 1;\n\t\t\t\t}\n\t\t\t\ttp[dlen] = '\\0';\n\t\t\t\tcp += dlen;", "\t\t\t\tadd_assoc_stringl(*subarray, \"txt\", tp, (dlen>0)?dlen - 1:0, 0);\n\t\t\t\tadd_assoc_zval(*subarray, \"entries\", entries);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DNS_T_SOA:\n\t\t\tadd_assoc_string(*subarray, \"type\", \"SOA\", 1);\n\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(*subarray, \"mname\", name, 1);\n\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(*subarray, \"rname\", name, 1);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"serial\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"refresh\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"retry\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"expire\", n);\n\t\t\tGETLONG(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"minimum-ttl\", n);\n\t\t\tbreak;\n\t\tcase DNS_T_AAAA:\n\t\t\ttp = (u_char*)name;\n\t\t\tfor(i=0; i < 8; i++) {\n\t\t\t\tGETSHORT(s, cp);\n\t\t\t\tif (s != 0) {\n\t\t\t\t\tif (tp > (u_char *)name) {\n\t\t\t\t\t\tin_v6_break = 0;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t\ttp += sprintf((char*)tp,\"%x\",s);\n\t\t\t\t} else {\n\t\t\t\t\tif (!have_v6_break) {\n\t\t\t\t\t\thave_v6_break = 1;\n\t\t\t\t\t\tin_v6_break = 1;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t} else if (!in_v6_break) {\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t\ttp[0] = '0';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (have_v6_break && in_v6_break) {\n\t\t\t\ttp[0] = ':';\n\t\t\t\ttp++;\n\t\t\t}\n\t\t\ttp[0] = '\\0';\n\t\t\tadd_assoc_string(*subarray, \"type\", \"AAAA\", 1);\n\t\t\tadd_assoc_string(*subarray, \"ipv6\", name, 1);\n\t\t\tbreak;\n\t\tcase DNS_T_A6:\n\t\t\tp = cp;\n\t\t\tadd_assoc_string(*subarray, \"type\", \"A6\", 1);\n\t\t\tn = ((int)cp[0]) & 0xFF;\n\t\t\tcp++;\n\t\t\tadd_assoc_long(*subarray, \"masklen\", n);\n\t\t\ttp = (u_char*)name;\n\t\t\tif (n > 15) {\n\t\t\t\thave_v6_break = 1;\n\t\t\t\tin_v6_break = 1;\n\t\t\t\ttp[0] = ':';\n\t\t\t\ttp++;\n\t\t\t}\n\t\t\tif (n % 16 > 8) {\n\t\t\t\t/* Partial short */\n\t\t\t\tif (cp[0] != 0) {\n\t\t\t\t\tif (tp > (u_char *)name) {\n\t\t\t\t\t\tin_v6_break = 0;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t\tsprintf((char*)tp, \"%x\", cp[0] & 0xFF);\n\t\t\t\t} else {\n\t\t\t\t\tif (!have_v6_break) {\n\t\t\t\t\t\thave_v6_break = 1;\n\t\t\t\t\t\tin_v6_break = 1;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t} else if (!in_v6_break) {\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t\ttp[0] = '0';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcp++;\n\t\t\t}\n\t\t\tfor (i = (n + 8) / 16; i < 8; i++) {\n\t\t\t\tGETSHORT(s, cp);\n\t\t\t\tif (s != 0) {\n\t\t\t\t\tif (tp > (u_char *)name) {\n\t\t\t\t\t\tin_v6_break = 0;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t\ttp += sprintf((char*)tp,\"%x\",s);\n\t\t\t\t} else {\n\t\t\t\t\tif (!have_v6_break) {\n\t\t\t\t\t\thave_v6_break = 1;\n\t\t\t\t\t\tin_v6_break = 1;\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t} else if (!in_v6_break) {\n\t\t\t\t\t\ttp[0] = ':';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t\ttp[0] = '0';\n\t\t\t\t\t\ttp++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (have_v6_break && in_v6_break) {\n\t\t\t\ttp[0] = ':';\n\t\t\t\ttp++;\n\t\t\t}\n\t\t\ttp[0] = '\\0';\n\t\t\tadd_assoc_string(*subarray, \"ipv6\", name, 1);\n\t\t\tif (cp < p + dlen) {\n\t\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);\n\t\t\t\tif (n < 0) {\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\tcp += n;\n\t\t\t\tadd_assoc_string(*subarray, \"chain\", name, 1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DNS_T_SRV:\n\t\t\tadd_assoc_string(*subarray, \"type\", \"SRV\", 1);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"pri\", n);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"weight\", n);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"port\", n);\n\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(*subarray, \"target\", name, 1);\n\t\t\tbreak;\n\t\tcase DNS_T_NAPTR:\n\t\t\tadd_assoc_string(*subarray, \"type\", \"NAPTR\", 1);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"order\", n);\n\t\t\tGETSHORT(n, cp);\n\t\t\tadd_assoc_long(*subarray, \"pref\", n);\n\t\t\tn = (cp[0] & 0xFF);\n\t\t\tadd_assoc_stringl(*subarray, \"flags\", (char*)++cp, n, 1);\n\t\t\tcp += n;\n\t\t\tn = (cp[0] & 0xFF);\n\t\t\tadd_assoc_stringl(*subarray, \"services\", (char*)++cp, n, 1);\n\t\t\tcp += n;\n\t\t\tn = (cp[0] & 0xFF);\n\t\t\tadd_assoc_stringl(*subarray, \"regex\", (char*)++cp, n, 1);\n\t\t\tcp += n;\n\t\t\tn = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);\n\t\t\tif (n < 0) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tcp += n;\n\t\t\tadd_assoc_string(*subarray, \"replacement\", name, 1);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tzval_ptr_dtor(subarray);\n\t\t\t*subarray = NULL;\n\t\t\tcp += dlen;\n\t\t\tbreak;\n\t}", "\treturn cp;\n}\n/* }}} */", "/* {{{ proto array|false dns_get_record(string hostname [, int type[, array authns, array addtl]])\n Get any Resource Record corresponding to a given Internet host name */\nPHP_FUNCTION(dns_get_record)\n{\n\tchar *hostname;\n\tint hostname_len;\n\tlong type_param = PHP_DNS_ANY;\n\tzval *authns = NULL, *addtl = NULL;\n\tint type_to_fetch;\n#if defined(HAVE_DNS_SEARCH)\n\tstruct sockaddr_storage from;\n\tuint32_t fromsize = sizeof(from);\n\tdns_handle_t handle;\n#elif defined(HAVE_RES_NSEARCH)\n\tstruct __res_state state;\n\tstruct __res_state *handle = &state;\n#endif\n\tHEADER *hp;\n\tquerybuf answer;\n\tu_char *cp = NULL, *end = NULL;\n\tint n, qd, an, ns = 0, ar = 0;\n\tint type, first_query = 1, store_results = 1;\n\tzend_bool raw = 0;", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|lz!z!b\",\n\t\t\t&hostname, &hostname_len, &type_param, &authns, &addtl, &raw) == FAILURE) {\n\t\treturn;\n\t}", "\tif (authns) {\n\t\tzval_dtor(authns);\n\t\tarray_init(authns);\n\t}\n\tif (addtl) {\n\t\tzval_dtor(addtl);\n\t\tarray_init(addtl);\n\t}", "\tif (!raw) {\n\t\tif ((type_param & ~PHP_DNS_ALL) && (type_param != PHP_DNS_ANY)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Type '%ld' not supported\", type_param);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t} else {\n\t\tif ((type_param < 1) || (type_param > 0xFFFF)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING,\n\t\t\t\t\"Numeric DNS record type must be between 1 and 65535, '%ld' given\", type_param);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t}", "\t/* Initialize the return array */\n\tarray_init(return_value);", "\t/* - We emulate an or'ed type mask by querying type by type. (Steps 0 - NUMTYPES-1 )\n\t * If additional info is wanted we check again with DNS_T_ANY (step NUMTYPES / NUMTYPES+1 )\n\t * store_results is used to skip storing the results retrieved in step\n\t * NUMTYPES+1 when results were already fetched.\n\t * - In case of PHP_DNS_ANY we use the directly fetch DNS_T_ANY. (step NUMTYPES+1 )\n\t * - In case of raw mode, we query only the requestd type instead of looping type by type\n\t * before going with the additional info stuff.\n\t */", "\tif (raw) {\n\t\ttype = -1;\n\t} else if (type_param == PHP_DNS_ANY) {\n\t\ttype = PHP_DNS_NUM_TYPES + 1;\n\t} else {\n\t\ttype = 0;\n\t}", "\tfor ( ;\n\t\ttype < (addtl ? (PHP_DNS_NUM_TYPES + 2) : PHP_DNS_NUM_TYPES) || first_query;\n\t\ttype++\n\t) {\n\t\tfirst_query = 0;\n\t\tswitch (type) {\n\t\t\tcase -1: /* raw */\n\t\t\t\ttype_to_fetch = type_param;\n\t\t\t\t/* skip over the rest and go directly to additional records */\n\t\t\t\ttype = PHP_DNS_NUM_TYPES - 1;\n\t\t\t\tbreak;\n\t\t\tcase 0:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_A ? DNS_T_A : 0;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_NS ? DNS_T_NS : 0;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_CNAME ? DNS_T_CNAME : 0;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_SOA ? DNS_T_SOA : 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_PTR ? DNS_T_PTR : 0;\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_HINFO ? DNS_T_HINFO : 0;\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_MX ? DNS_T_MX : 0;\n\t\t\t\tbreak;\n\t\t\tcase 7:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_TXT ? DNS_T_TXT : 0;\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_AAAA\t ? DNS_T_AAAA : 0;\n\t\t\t\tbreak;\n\t\t\tcase 9:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_SRV ? DNS_T_SRV : 0;\n\t\t\t\tbreak;\n\t\t\tcase 10:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_NAPTR ? DNS_T_NAPTR : 0;\n\t\t\t\tbreak;\n\t\t\tcase 11:\n\t\t\t\ttype_to_fetch = type_param&PHP_DNS_A6\t ? DNS_T_A6 : 0;\n\t\t\t\tbreak;\n\t\t\tcase PHP_DNS_NUM_TYPES:\n\t\t\t\tstore_results = 0;\n\t\t\t\tcontinue;\n\t\t\tdefault:\n\t\t\tcase (PHP_DNS_NUM_TYPES + 1):\n\t\t\t\ttype_to_fetch = DNS_T_ANY;\n\t\t\t\tbreak;\n\t\t}", "\t\tif (type_to_fetch) {\n#if defined(HAVE_DNS_SEARCH)\n\t\t\thandle = dns_open(NULL);\n\t\t\tif (handle == NULL) {\n\t\t\t\tzval_dtor(return_value);\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n#elif defined(HAVE_RES_NSEARCH)\n\t\t memset(&state, 0, sizeof(state));\n\t\t if (res_ninit(handle)) {\n\t\t \tzval_dtor(return_value);\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n#else\n\t\t\tres_init();\n#endif", "\t\t\tn = php_dns_search(handle, hostname, C_IN, type_to_fetch, answer.qb2, sizeof answer);", "\t\t\tif (n < 0) {\n\t\t\t\tphp_dns_free_handle(handle);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tcp = answer.qb2 + HFIXEDSZ;\n\t\t\tend = answer.qb2 + n;\n\t\t\thp = (HEADER *)&answer;\n\t\t\tqd = ntohs(hp->qdcount);\n\t\t\tan = ntohs(hp->ancount);\n\t\t\tns = ntohs(hp->nscount);\n\t\t\tar = ntohs(hp->arcount);", "\t\t\t/* Skip QD entries, they're only used by dn_expand later on */\n\t\t\twhile (qd-- > 0) {\n\t\t\t\tn = dn_skipname(cp, end);\n\t\t\t\tif (n < 0) {\n\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Unable to parse DNS data received\");\n\t\t\t\t\tzval_dtor(return_value);\n\t\t\t\t\tphp_dns_free_handle(handle);\n\t\t\t\t\tRETURN_FALSE;\n\t\t\t\t}\n\t\t\t\tcp += n + QFIXEDSZ;\n\t\t\t}", "\t\t\t/* YAY! Our real answers! */\n\t\t\twhile (an-- && cp && cp < end) {\n\t\t\t\tzval *retval;", "\t\t\t\tcp = php_parserr(cp, &answer, type_to_fetch, store_results, raw, &retval);\n\t\t\t\tif (retval != NULL && store_results) {\n\t\t\t\t\tadd_next_index_zval(return_value, retval);\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (authns || addtl) {\n\t\t\t\t/* List of Authoritative Name Servers\n\t\t\t\t * Process when only requesting addtl so that we can skip through the section\n\t\t\t\t */\n\t\t\t\twhile (ns-- > 0 && cp && cp < end) {\n\t\t\t\t\tzval *retval = NULL;", "\t\t\t\t\tcp = php_parserr(cp, &answer, DNS_T_ANY, authns != NULL, raw, &retval);\n\t\t\t\t\tif (retval != NULL) {\n\t\t\t\t\t\tadd_next_index_zval(authns, retval);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (addtl) {\n\t\t\t\t/* Additional records associated with authoritative name servers */\n\t\t\t\twhile (ar-- > 0 && cp && cp < end) {\n\t\t\t\t\tzval *retval = NULL;", "\t\t\t\t\tcp = php_parserr(cp, &answer, DNS_T_ANY, 1, raw, &retval);\n\t\t\t\t\tif (retval != NULL) {\n\t\t\t\t\t\tadd_next_index_zval(addtl, retval);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tphp_dns_free_handle(handle);\n\t\t}\n\t}\n}\n/* }}} */", "/* {{{ proto bool dns_get_mx(string hostname, array mxhosts [, array weight])\n Get MX records corresponding to a given Internet host name */\nPHP_FUNCTION(dns_get_mx)\n{\n\tchar *hostname;\n\tint hostname_len;\n\tzval *mx_list, *weight_list = NULL;\n\tint count, qdc;\n\tu_short type, weight;\n\tu_char ans[MAXPACKET];\n\tchar buf[MAXHOSTNAMELEN];\n\tHEADER *hp;\n\tu_char *cp, *end;\n\tint i;\n#if defined(HAVE_DNS_SEARCH)\n\tstruct sockaddr_storage from;\n\tuint32_t fromsize = sizeof(from);\n\tdns_handle_t handle;\n#elif defined(HAVE_RES_NSEARCH)\n\tstruct __res_state state;\n\tstruct __res_state *handle = &state;\n#endif", "\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"sz|z\", &hostname, &hostname_len, &mx_list, &weight_list) == FAILURE) {\n\t\treturn;\n\t}", "\tzval_dtor(mx_list);\n\tarray_init(mx_list);", "\tif (weight_list) {\n\t\tzval_dtor(weight_list);\n\t\tarray_init(weight_list);\n\t}", "#if defined(HAVE_DNS_SEARCH)\n\thandle = dns_open(NULL);\n\tif (handle == NULL) {\n\t\tRETURN_FALSE;\n\t}\n#elif defined(HAVE_RES_NSEARCH)\n memset(&state, 0, sizeof(state));\n if (res_ninit(handle)) {\n\t\t\tRETURN_FALSE;\n\t}\n#else\n\tres_init();\n#endif", "\ti = php_dns_search(handle, hostname, C_IN, DNS_T_MX, (u_char *)&ans, sizeof(ans));\n\tif (i < 0) {\n\t\tRETURN_FALSE;\n\t}\n\tif (i > (int)sizeof(ans)) {\n\t\ti = sizeof(ans);\n\t}\n\thp = (HEADER *)&ans;\n\tcp = (u_char *)&ans + HFIXEDSZ;\n\tend = (u_char *)&ans +i;\n\tfor (qdc = ntohs((unsigned short)hp->qdcount); qdc--; cp += i + QFIXEDSZ) {\n\t\tif ((i = dn_skipname(cp, end)) < 0 ) {\n\t\t\tphp_dns_free_handle(handle);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t}\n\tcount = ntohs((unsigned short)hp->ancount);\n\twhile (--count >= 0 && cp < end) {\n\t\tif ((i = dn_skipname(cp, end)) < 0 ) {\n\t\t\tphp_dns_free_handle(handle);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t\tcp += i;\n\t\tGETSHORT(type, cp);\n\t\tcp += INT16SZ + INT32SZ;\n\t\tGETSHORT(i, cp);\n\t\tif (type != DNS_T_MX) {\n\t\t\tcp += i;\n\t\t\tcontinue;\n\t\t}\n\t\tGETSHORT(weight, cp);\n\t\tif ((i = dn_expand(ans, end, cp, buf, sizeof(buf)-1)) < 0) {\n\t\t\tphp_dns_free_handle(handle);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t\tcp += i;\n\t\tadd_next_index_string(mx_list, buf, 1);\n\t\tif (weight_list) {\n\t\t\tadd_next_index_long(weight_list, weight);\n\t\t}\n\t}\n\tphp_dns_free_handle(handle);\n\tRETURN_TRUE;\n}\n/* }}} */\n#endif /* HAVE_FULL_DNS_FUNCS */\n#endif /* !defined(PHP_WIN32) && (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) */", "#if HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32)\nPHP_MINIT_FUNCTION(dns) {\n\tREGISTER_LONG_CONSTANT(\"DNS_A\", PHP_DNS_A, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_NS\", PHP_DNS_NS, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_CNAME\", PHP_DNS_CNAME, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_SOA\", PHP_DNS_SOA, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_PTR\", PHP_DNS_PTR, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_HINFO\", PHP_DNS_HINFO, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_MX\", PHP_DNS_MX, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_TXT\", PHP_DNS_TXT, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_SRV\", PHP_DNS_SRV, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_NAPTR\", PHP_DNS_NAPTR, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_AAAA\", PHP_DNS_AAAA, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_A6\", PHP_DNS_A6, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_ANY\", PHP_DNS_ANY, CONST_CS | CONST_PERSISTENT);\n\tREGISTER_LONG_CONSTANT(\"DNS_ALL\", PHP_DNS_ALL, CONST_CS | CONST_PERSISTENT);\n\treturn SUCCESS;\n}\n#endif /* HAVE_FULL_DNS_FUNCS */", "/*\n * Local variables:\n * tab-width: 4\n * c-basic-offset: 4\n * End:\n * vim600: sw=4 ts=4 fdm=marker\n * vim<600: sw=4 ts=4\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 ]
PreciseBugs
{"buggy_code_end_loc": [519], "buggy_code_start_loc": [519], "filenames": ["ext/standard/dns.c"], "fixing_code_end_loc": [524], "fixing_code_start_loc": [520], "message": "Heap-based buffer overflow in the php_parserr function in ext/standard/dns.c in PHP 5.6.0beta4 and earlier allows remote servers to cause a denial of service (crash) and possibly execute arbitrary code via a crafted DNS TXT record, related to the dns_get_record function.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:opensuse:11.3:*:*:*:*:*:*:*", "matchCriteriaId": "5646FDE9-CF21-46A9-B89D-F5BBDB4249AF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:php:php:*:*:*:*:*:*:*:*", "matchCriteriaId": "B61C8E39-DB8E-4636-91E5-2473B0915FBD", "versionEndExcluding": "5.3.29", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "5.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:*:*:*:*:*:*:*:*", "matchCriteriaId": "AD052020-AA37-4F49-A0FE-EA99616C12C7", "versionEndExcluding": "5.4.30", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "5.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:*:*:*:*:*:*:*:*", "matchCriteriaId": "4ADC6057-9D35-4D87-B15D-F6F52A283464", "versionEndExcluding": "5.5.14", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "5.5.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "5BF4E8FF-A3EC-43E8-A0C1-FD38AFCB77B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "54ADECFC-3C07-43BC-B296-6C25AC7F1C95", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "FE192054-2FBB-4388-A52A-422E20DEA2D7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:alpha4:*:*:*:*:*:*", "matchCriteriaId": "F0195D48-3B42-4AC0-B9C5-436E01C63879", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:alpha5:*:*:*:*:*:*", "matchCriteriaId": "BF0E5D67-ABC1-41A5-94E1-7DD3CDB51D81", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:beta1:*:*:*:*:*:*", "matchCriteriaId": "319E0573-B1AD-40B6-B4BC-8BE67ED3EFDB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:beta2:*:*:*:*:*:*", "matchCriteriaId": "1A7C00EB-87B7-4EB7-A4AC-8665D8C78467", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:php:php:5.6.0:beta3:*:*:*:*:*:*", "matchCriteriaId": "21BFCF10-786A-4D1E-9C37-50A1EC6056F1", "versionEndExcluding": null, "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: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}], "descriptions": [{"lang": "en", "value": "Heap-based buffer overflow in the php_parserr function in ext/standard/dns.c in PHP 5.6.0beta4 and earlier allows remote servers to cause a denial of service (crash) and possibly execute arbitrary code via a crafted DNS TXT record, related to the dns_get_record function."}, {"lang": "es", "value": "Desbordamiento de buffer basado en memoria din\u00e1mica en la funci\u00f3n php_parserr en ext/standard/dns.c en PHP 5.6.0beta4 y anteriores permite a servidores remotos causar una denegaci\u00f3n de servicio (ca\u00edda) y posiblemente ejecutar c\u00f3digo arbitrario a trav\u00e9s de un registro DNS TXT manipulado, relacionado con la funci\u00f3n dns_get_record."}], "evaluatorComment": null, "id": "CVE-2014-4049", "lastModified": "2022-08-29T20:05:23.073", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "HIGH", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.1, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:H/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 4.9, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-06-18T19:55:05.683", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.apple.com/archives/security-announce/2015/Apr/msg00001.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2014-07/msg00001.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2014-07/msg00002.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2014-06/msg00051.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2014-07/msg00032.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://marc.info/?l=bugtraq&m=141017844705317&w=2"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2014-1765.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2014-1766.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://secunia.com/advisories/59329"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://secunia.com/advisories/59418"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://secunia.com/advisories/59496"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://secunia.com/advisories/59513"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://secunia.com/advisories/60998"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://support.apple.com/kb/HT6443"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www-01.ibm.com/support/docview.wss?uid=swg21683486"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2014/dsa-2961"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/06/13/4"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.oracle.com/technetwork/topics/security/bulletinjan2015-2370101.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/68007"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securitytracker.com/id/1030435"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1108447"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/php/php-src/commit/b34d7849ed90ced9345f8ea1c59bc8d101c18468"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/HT204659"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/php/php-src/commit/b34d7849ed90ced9345f8ea1c59bc8d101c18468"}, "type": "CWE-119"}
231
Determine whether the {function_name} code is vulnerable or not.
[ "# frozen_string_literal: true", "class StrippedLengthValidator < ActiveModel::EachValidator\n def self.validate(record, attribute, value, range)", " if !value.nil?", " value = get_sanitized_value(value)", " record.errors.add attribute, (I18n.t('errors.messages.too_short', count: range.begin)) if value.length < range.begin\n record.errors.add attribute, (I18n.t('errors.messages.too_long_validation', max: range.end, length: value.length)) if value.length > range.end\n else\n record.errors.add attribute, (I18n.t('errors.messages.blank'))", " end\n end", " def validate_each(record, attribute, value)\n # the `in` parameter might be a lambda when the range is dynamic\n range = options[:in].lambda? ? options[:in].call : options[:in]\n self.class.validate(record, attribute, value, range)\n end", " def self.get_sanitized_value(value)\n value = value.dup\n value.gsub!(/<!--(.*?)-->/, '') # strip HTML comments\n value.gsub!(/:\\w+(:\\w+)?:/, \"X\") # replace emojis with a single character\n value.gsub!(/\\.{2,}/, '…') # replace multiple ... with …\n value.gsub!(/\\,{2,}/, ',') # replace multiple ,,, with ,\n value.strip\n end\nend" ]
[ 1, 1, 0, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [11, 1046], "buggy_code_start_loc": [5, 1046], "filenames": ["lib/validators/stripped_length_validator.rb", "spec/requests/posts_controller_spec.rb"], "fixing_code_end_loc": [15, 1061], "fixing_code_start_loc": [5, 1047], "message": "Discourse is an option source discussion platform. Prior to version 2.8.14 on the `stable` branch and version 2.9.0.beta16 on the `beta` and `tests-passed` branches, users can create posts with raw body longer than the `max_length` site setting by including html comments that are not counted toward the character limit. This issue is patched in versions 2.8.14 and 2.9.0.beta16. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:discourse:discourse:*:*:*:*:*:*:*:*", "matchCriteriaId": "9C13BCBA-EF34-4F4B-9F4A-33392EB45196", "versionEndExcluding": "2.8.14", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta1:*:*:*:*:*:*", "matchCriteriaId": "B3803EF9-A296-42B7-887F-93C5E68E94C4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta10:*:*:*:*:*:*", "matchCriteriaId": "35BAC488-3622-4B0B-B8EA-879E8C68E8CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta11:*:*:*:*:*:*", "matchCriteriaId": "406A23B4-B971-4DC8-A132-EE9854FE8546", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta12:*:*:*:*:*:*", "matchCriteriaId": "1DD3C47F-E49F-4E19-9EA7-A322C4CFD541", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta13:*:*:*:*:*:*", "matchCriteriaId": "E924AC08-6978-4DFF-B616-9E3E9D6FBE1B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta14:*:*:*:*:*:*", "matchCriteriaId": "B5A3C7FB-B3B6-45F0-AD7D-062A50490AD7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta2:*:*:*:*:*:*", "matchCriteriaId": "8BA3D313-3C11-43E2-A47D-CBB532D1B6F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta3:*:*:*:*:*:*", "matchCriteriaId": "6F42673E-65F3-4807-9484-20CB747420FB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta4:*:*:*:*:*:*", "matchCriteriaId": "0B91D023-FCE5-4866-AD8B-BBB675763104", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta5:*:*:*:*:*:*", "matchCriteriaId": "0086484D-0164-449C-8AAE-BE7479CB9706", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta6:*:*:*:*:*:*", "matchCriteriaId": "F9D1B031-96C7-44C0-A0A0-F67ABE55C93C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta7:*:*:*:*:*:*", "matchCriteriaId": "750D2AD9-35E7-4AC7-9C22-AA90DAA34F3F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta8:*:*:*:*:*:*", "matchCriteriaId": "B68E308A-BDAB-4614-A563-4460F7996CBE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:3.0.0:beta15:*:*:*:*:*:*", "matchCriteriaId": "F62275F8-11E9-4D94-8F2E-F83905F65031", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Discourse is an option source discussion platform. Prior to version 2.8.14 on the `stable` branch and version 2.9.0.beta16 on the `beta` and `tests-passed` branches, users can create posts with raw body longer than the `max_length` site setting by including html comments that are not counted toward the character limit. This issue is patched in versions 2.8.14 and 2.9.0.beta16. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23549", "lastModified": "2023-01-12T20:33:47.867", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-01-05T19:15:09.500", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/discourse/discourse/commit/bf6b08670a927cc80bb090b7a2e710b4b554e6a8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/discourse/discourse/security/advisories/GHSA-p47g-v5wr-p4xp"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-20"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/discourse/discourse/commit/bf6b08670a927cc80bb090b7a2e710b4b554e6a8"}, "type": "NVD-CWE-Other"}
232
Determine whether the {function_name} code is vulnerable or not.
[ "# frozen_string_literal: true", "class StrippedLengthValidator < ActiveModel::EachValidator\n def self.validate(record, attribute, value, range)", " if value.nil?\n record.errors.add attribute, I18n.t('errors.messages.blank')\n elsif value.length > range.end\n record.errors.add attribute, I18n.t('errors.messages.too_long_validation', max: range.end, length: value.length)\n else", " value = get_sanitized_value(value)", "\n if value.length < range.begin\n record.errors.add attribute, I18n.t('errors.messages.too_short', count: range.begin)\n end", " end\n end", " def validate_each(record, attribute, value)\n # the `in` parameter might be a lambda when the range is dynamic\n range = options[:in].lambda? ? options[:in].call : options[:in]\n self.class.validate(record, attribute, value, range)\n end", " def self.get_sanitized_value(value)\n value = value.dup\n value.gsub!(/<!--(.*?)-->/, '') # strip HTML comments\n value.gsub!(/:\\w+(:\\w+)?:/, \"X\") # replace emojis with a single character\n value.gsub!(/\\.{2,}/, '…') # replace multiple ... with …\n value.gsub!(/\\,{2,}/, ',') # replace multiple ,,, with ,\n value.strip\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [11, 1046], "buggy_code_start_loc": [5, 1046], "filenames": ["lib/validators/stripped_length_validator.rb", "spec/requests/posts_controller_spec.rb"], "fixing_code_end_loc": [15, 1061], "fixing_code_start_loc": [5, 1047], "message": "Discourse is an option source discussion platform. Prior to version 2.8.14 on the `stable` branch and version 2.9.0.beta16 on the `beta` and `tests-passed` branches, users can create posts with raw body longer than the `max_length` site setting by including html comments that are not counted toward the character limit. This issue is patched in versions 2.8.14 and 2.9.0.beta16. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:discourse:discourse:*:*:*:*:*:*:*:*", "matchCriteriaId": "9C13BCBA-EF34-4F4B-9F4A-33392EB45196", "versionEndExcluding": "2.8.14", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta1:*:*:*:*:*:*", "matchCriteriaId": "B3803EF9-A296-42B7-887F-93C5E68E94C4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta10:*:*:*:*:*:*", "matchCriteriaId": "35BAC488-3622-4B0B-B8EA-879E8C68E8CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta11:*:*:*:*:*:*", "matchCriteriaId": "406A23B4-B971-4DC8-A132-EE9854FE8546", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta12:*:*:*:*:*:*", "matchCriteriaId": "1DD3C47F-E49F-4E19-9EA7-A322C4CFD541", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta13:*:*:*:*:*:*", "matchCriteriaId": "E924AC08-6978-4DFF-B616-9E3E9D6FBE1B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta14:*:*:*:*:*:*", "matchCriteriaId": "B5A3C7FB-B3B6-45F0-AD7D-062A50490AD7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta2:*:*:*:*:*:*", "matchCriteriaId": "8BA3D313-3C11-43E2-A47D-CBB532D1B6F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta3:*:*:*:*:*:*", "matchCriteriaId": "6F42673E-65F3-4807-9484-20CB747420FB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta4:*:*:*:*:*:*", "matchCriteriaId": "0B91D023-FCE5-4866-AD8B-BBB675763104", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta5:*:*:*:*:*:*", "matchCriteriaId": "0086484D-0164-449C-8AAE-BE7479CB9706", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta6:*:*:*:*:*:*", "matchCriteriaId": "F9D1B031-96C7-44C0-A0A0-F67ABE55C93C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta7:*:*:*:*:*:*", "matchCriteriaId": "750D2AD9-35E7-4AC7-9C22-AA90DAA34F3F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta8:*:*:*:*:*:*", "matchCriteriaId": "B68E308A-BDAB-4614-A563-4460F7996CBE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:3.0.0:beta15:*:*:*:*:*:*", "matchCriteriaId": "F62275F8-11E9-4D94-8F2E-F83905F65031", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Discourse is an option source discussion platform. Prior to version 2.8.14 on the `stable` branch and version 2.9.0.beta16 on the `beta` and `tests-passed` branches, users can create posts with raw body longer than the `max_length` site setting by including html comments that are not counted toward the character limit. This issue is patched in versions 2.8.14 and 2.9.0.beta16. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23549", "lastModified": "2023-01-12T20:33:47.867", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-01-05T19:15:09.500", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/discourse/discourse/commit/bf6b08670a927cc80bb090b7a2e710b4b554e6a8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/discourse/discourse/security/advisories/GHSA-p47g-v5wr-p4xp"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-20"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/discourse/discourse/commit/bf6b08670a927cc80bb090b7a2e710b4b554e6a8"}, "type": "NVD-CWE-Other"}
232
Determine whether the {function_name} code is vulnerable or not.
[ "# frozen_string_literal: true", "RSpec.shared_examples 'finding and showing post' do\n let!(:post) { post_by_user }", " it \"ensures the user can't see the post\" do\n topic = post.topic\n topic.convert_to_private_message(Discourse.system_user)\n topic.remove_allowed_user(Discourse.system_user, user.username)\n get url\n expect(response).to be_forbidden\n end", " it 'succeeds' do\n get url\n expect(response.status).to eq(200)\n end", " it \"returns 404 when post's topic is deleted\" do\n post.topic.destroy!\n get url\n expect(response.status).to eq(404)\n end", " context \"with deleted post\" do\n before do\n post.trash!(user)\n end", " it \"can't find deleted posts as an anonymous user\" do\n get url\n expect(response.status).to eq(404)\n end", " it \"can't find deleted posts as a regular user\" do\n sign_in(user)\n get url\n expect(response.status).to eq(404)\n end", " it \"can find posts as a moderator\" do\n sign_in(moderator)\n get url\n expect(response.status).to eq(200)\n end", " it \"can find posts as a admin\" do\n sign_in(admin)\n get url\n expect(response.status).to eq(200)\n end", " context \"with category group moderator\" do\n fab!(:group_user) { Fabricate(:group_user) }\n let(:user_gm) { group_user.user }\n let(:group) { group_user.group }", " before do\n SiteSetting.enable_category_group_moderation = true\n sign_in(user_gm)\n end", " it \"can find posts in the allowed category\" do\n post.topic.category.update!(reviewable_by_group_id: group.id, topic_id: topic.id)\n get url\n expect(response.status).to eq(200)\n end", " it \"can't find posts outside of the allowed category\" do\n get url\n expect(response.status).to eq(404)\n end\n end\n end\nend", "RSpec.shared_examples 'action requires login' do |method, url, params = {}|\n it 'raises an exception when not logged in' do\n self.public_send(method, url, **params)\n expect(response.status).to eq(403)\n end\nend", "RSpec.describe PostsController do\n fab!(:admin) { Fabricate(:admin) }\n fab!(:moderator) { Fabricate(:moderator) }\n fab!(:user) { Fabricate(:user) }\n fab!(:user_trust_level_0) { Fabricate(:trust_level_0) }\n fab!(:user_trust_level_1) { Fabricate(:trust_level_1) }\n fab!(:category) { Fabricate(:category) }\n fab!(:topic) { Fabricate(:topic) }\n fab!(:post_by_user) { Fabricate(:post, user: user) }\n let(:public_post) { Fabricate(:post, user: user, topic: topic) }\n let(:topicless_post) { Fabricate(:post, user: user, raw: '<p>Car 54, where are you?</p>') }", " let(:private_topic) do\n Fabricate(:topic, archetype: Archetype.private_message, category_id: nil)\n end", " let(:private_post) { Fabricate(:post, user: user, topic: private_topic) }", " describe '#show' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/#{post.id}.json\" }\n end", " it 'gets all the expected fields' do\n # non fabricated test\n new_post = create_post", " get \"/posts/#{new_post.id}.json\"\n parsed = response.parsed_body", " expect(parsed[\"topic_slug\"]).to eq(new_post.topic.slug)\n expect(parsed[\"moderator\"]).to eq(false)\n expect(parsed[\"username\"]).to eq(new_post.user.username)\n expect(parsed[\"cooked\"]).to eq(new_post.cooked)\n end\n end", " describe '#by_number' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/by_number/#{post.topic_id}/#{post.post_number}.json\" }\n end\n end", " describe '#by_date' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/by-date/#{post.topic_id}/#{post.created_at.strftime(\"%Y-%m-%d\")}.json\" }\n end", " it 'returns the expected post' do\n first_post = Fabricate(:post, created_at: 10.days.ago)\n second_post = Fabricate(:post, topic: first_post.topic, created_at: 4.days.ago)\n _third_post = Fabricate(:post, topic: first_post.topic, created_at: 3.days.ago)", " get \"/posts/by-date/#{second_post.topic_id}/#{(second_post.created_at - 2.days).strftime(\"%Y-%m-%d\")}.json\"\n json = response.parsed_body", " expect(response.status).to eq(200)\n expect(json[\"id\"]).to eq(second_post.id)\n end", " it 'returns no post if date is > at last created post' do\n get \"/posts/by-date/#{post.topic_id}/2245-11-11.json\"\n _json = response.parsed_body\n expect(response.status).to eq(404)\n end\n end", " describe '#reply_history' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/#{post.id}/reply-history.json\" }\n end", " it \"returns the replies with allowlisted user custom fields\" do\n parent = Fabricate(:post)\n child = Fabricate(:post, topic: parent.topic, reply_to_post_number: parent.post_number)", " parent.user.upsert_custom_fields(hello: 'world', hidden: 'dontshow')\n SiteSetting.public_user_custom_fields = 'hello'", " get \"/posts/#{child.id}/reply-history.json\"\n expect(response.status).to eq(200)", " json = response.parsed_body\n expect(json[0]['id']).to eq(parent.id)\n expect(json[0]['user_custom_fields']['hello']).to eq('world')\n expect(json[0]['user_custom_fields']['hidden']).to be_blank\n end\n end", " describe '#reply_ids' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/#{post.id}/reply-ids.json\" }\n end", " it \"returns ids of post's replies\" do\n post = Fabricate(:post)\n reply1 = Fabricate(:post, topic: post.topic, reply_to_post_number: post.post_number)\n reply2 = Fabricate(:post, topic: post.topic, reply_to_post_number: post.post_number)\n PostReply.create(post_id: post.id, reply_post_id: reply1.id)\n PostReply.create(post_id: post.id, reply_post_id: reply2.id)", " get \"/posts/#{post.id}/reply-ids.json\"", " expect(response.status).to eq(200)\n expect(response.parsed_body).to eq([\n { \"id\" => reply1.id, \"level\" => 1 },\n { \"id\" => reply2.id, \"level\" => 1 },\n ])\n end\n end", " describe '#replies' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/#{post.id}/replies.json\" }\n end", " it 'asks post for replies' do\n parent = Fabricate(:post)\n child = Fabricate(:post, topic: parent.topic, reply_to_post_number: parent.post_number)\n PostReply.create!(post: parent, reply: child)", " child.user.upsert_custom_fields(hello: 'world', hidden: 'dontshow')\n SiteSetting.public_user_custom_fields = 'hello'", " get \"/posts/#{parent.id}/replies.json\"\n expect(response.status).to eq(200)", " json = response.parsed_body\n expect(json[0]['id']).to eq(child.id)\n expect(json[0]['user_custom_fields']['hello']).to eq('world')\n expect(json[0]['user_custom_fields']['hidden']).to be_blank\n end\n end", " describe '#destroy' do\n include_examples 'action requires login', :delete, \"/posts/123.json\"", " describe 'when logged in' do\n let(:topic) { Fabricate(:topic) }", " it \"raises an error when the user doesn't have permission to see the post\" do\n pm = Fabricate(:private_message_topic)\n post = Fabricate(:post, topic: pm, post_number: 3)", " sign_in(user)", " delete \"/posts/#{post.id}.json\"\n expect(response).to be_forbidden\n end", " it \"raises an error when the self deletions are disabled\" do\n SiteSetting.max_post_deletions_per_day = 0\n post = Fabricate(:post, user: user, topic: topic, post_number: 3)\n sign_in(user)", " delete \"/posts/#{post.id}.json\"\n expect(response).to be_forbidden\n end", " it \"uses a PostDestroyer\" do\n post = Fabricate(:post, topic_id: topic.id, post_number: 3)\n sign_in(moderator)", " destroyer = mock\n PostDestroyer.expects(:new).returns(destroyer)\n destroyer.expects(:destroy)", " delete \"/posts/#{post.id}.json\"\n end", " context \"with permanently destroy\" do\n let!(:post) { Fabricate(:post, topic_id: topic.id, post_number: 3) }", " before do\n SiteSetting.can_permanently_delete = true\n end", " it \"does not work for a post that was not deleted yet\" do\n sign_in(admin)", " delete \"/posts/#{post.id}.json\", params: { force_destroy: true }\n expect(response.status).to eq(403)\n end", " it \"needs some time to pass to permanently delete a topic\" do\n sign_in(admin)", " delete \"/posts/#{post.id}.json\"\n expect(response.status).to eq(200)\n expect(post.reload.deleted_by_id).to eq(admin.id)", " delete \"/posts/#{post.id}.json\", params: { force_destroy: true }\n expect(response.status).to eq(403)", " post.update!(deleted_at: 10.minutes.ago)", " delete \"/posts/#{post.id}.json\", params: { force_destroy: true }\n expect(response.status).to eq(200)\n expect { post.reload }.to raise_error(ActiveRecord::RecordNotFound)\n end", " it \"needs two users to permanently delete a topic\" do\n sign_in(admin)", " delete \"/posts/#{post.id}.json\"\n expect(response.status).to eq(200)\n expect(post.reload.deleted_by_id).to eq(admin.id)", " sign_in(Fabricate(:admin))", " delete \"/posts/#{post.id}.json\", params: { force_destroy: true }\n expect(response.status).to eq(200)\n expect { post.reload }.to raise_error(ActiveRecord::RecordNotFound)\n end", " it \"moderators cannot permanently delete topics\" do\n sign_in(admin)", " delete \"/posts/#{post.id}.json\"\n expect(response.status).to eq(200)\n expect(post.reload.deleted_by_id).to eq(admin.id)", " sign_in(moderator)", " delete \"/posts/#{post.id}.json\", params: { force_destroy: true }\n expect(response.status).to eq(403)\n end\n end\n end\n end", " describe '#destroy_many' do\n include_examples 'action requires login', :delete, \"/posts/destroy_many.json\", params: { post_ids: [123, 345] }", " describe 'when logged in' do\n fab!(:poster) { Fabricate(:moderator) }\n fab!(:post1) { Fabricate(:post, user: poster, post_number: 2) }\n fab!(:post2) { Fabricate(:post, topic: post1.topic, user: poster, post_number: 3, reply_to_post_number: post1.post_number) }", " it \"raises invalid parameters no post_ids\" do\n sign_in(poster)\n delete \"/posts/destroy_many.json\"\n expect(response.status).to eq(400)\n expect(response.message.downcase).to eq(\"bad request\")\n end", " it \"raises invalid parameters with missing ids\" do\n sign_in(poster)\n delete \"/posts/destroy_many.json\", params: { post_ids: [12345] }\n expect(response.status).to eq(400)\n end", " it \"raises an error when the user doesn't have permission to delete the posts\" do\n sign_in(user)\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id, post2.id] }\n expect(response).to be_forbidden\n end", " it \"deletes the post\" do\n sign_in(poster)\n PostDestroyer.any_instance.expects(:destroy).twice\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id, post2.id] }\n expect(response.status).to eq(200)\n end", " it \"updates the highest read data for the forum\" do\n sign_in(poster)\n Topic.expects(:reset_highest).twice\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id, post2.id] }\n end", " describe \"can delete replies\" do\n before do\n PostReply.create(post_id: post1.id, reply_post_id: post2.id)\n end", " it \"deletes the post and the reply to it\" do\n sign_in(poster)\n PostDestroyer.any_instance.expects(:destroy).twice\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id], reply_post_ids: [post1.id] }\n end\n end", " context \"when deleting flagged posts\" do\n before do\n sign_in(moderator)\n PostActionCreator.off_topic(moderator, post1)\n PostActionCreator.off_topic(moderator, post2)\n Jobs::SendSystemMessage.clear\n end", " it \"defers the child posts by default\" do\n expect(ReviewableFlaggedPost.pending.count).to eq(2)\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id, post2.id] }\n expect(Jobs::SendSystemMessage.jobs.size).to eq(1)\n expect(ReviewableFlaggedPost.pending.count).to eq(0)\n end", " it \"can defer all posts based on `agree_with_first_reply_flag` param\" do\n expect(ReviewableFlaggedPost.pending.count).to eq(2)\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id, post2.id], agree_with_first_reply_flag: false }\n PostActionCreator.off_topic(moderator, post1)\n PostActionCreator.off_topic(moderator, post2)\n Jobs::SendSystemMessage.clear\n end\n end\n end\n end", " describe '#recover' do\n include_examples 'action requires login', :put, \"/posts/123/recover.json\"", " describe 'when logged in' do\n it \"raises an error when the user doesn't have permission to see the post\" do\n post = Fabricate(:post, topic: Fabricate(:private_message_topic), post_number: 3)\n sign_in(user)", " put \"/posts/#{post.id}/recover.json\"\n expect(response).to be_forbidden\n end", " it \"raises an error when self deletion/recovery is disabled\" do\n SiteSetting.max_post_deletions_per_day = 0\n post = Fabricate(:post, user: user, topic: topic, post_number: 3)\n sign_in(user)", " put \"/posts/#{post.id}/recover.json\"\n expect(response).to be_forbidden\n end", " it \"recovers a post correctly\" do\n topic_id = create_post.topic_id\n post = create_post(topic_id: topic_id)\n sign_in(user)", " PostDestroyer.new(user, post).destroy\n put \"/posts/#{post.id}/recover.json\"\n post.reload\n expect(post.trashed?).to be_falsey\n end\n end\n end", " describe '#update' do\n include_examples 'action requires login', :put, \"/posts/2.json\"", " let!(:post) { post_by_user }\n let(:update_params) do\n {\n post: { raw: 'edited body', edit_reason: 'typo' },\n image_sizes: { 'http://image.com/image.jpg' => { 'width' => 123, 'height' => 456 } },\n }\n end", " describe 'when logged in as a regular user' do\n before do\n sign_in(user)\n end", " it 'does not allow TL0 or TL1 to update when edit time limit expired' do\n SiteSetting.post_edit_time_limit = 5\n SiteSetting.tl2_post_edit_time_limit = 30", " post = Fabricate(:post, created_at: 10.minutes.ago, user: user)", " user.update_columns(trust_level: 1)", " put \"/posts/#{post.id}.json\", params: update_params", " expect(response.status).to eq(422)\n expect(response.parsed_body['errors']).to include(I18n.t('too_late_to_edit'))\n end", " it 'does not allow TL2 to update when edit time limit expired' do\n SiteSetting.post_edit_time_limit = 12\n SiteSetting.tl2_post_edit_time_limit = 8", " user.update_columns(trust_level: 2)", " post = Fabricate(:post, created_at: 10.minutes.ago, user: user)", " put \"/posts/#{post.id}.json\", params: update_params", " expect(response.status).to eq(422)\n expect(response.parsed_body['errors']).to include(I18n.t('too_late_to_edit'))\n end", " it 'passes the image sizes through' do\n Post.any_instance.expects(:image_sizes=)\n put \"/posts/#{post.id}.json\", params: update_params\n end", " it 'passes the edit reason through' do\n put \"/posts/#{post.id}.json\", params: update_params\n expect(response.status).to eq(200)\n post.reload\n expect(post.edit_reason).to eq(\"typo\")\n expect(post.raw).to eq(\"edited body\")\n end", " it 'checks for an edit conflict' do\n update_params[:post][:raw_old] = 'old body'\n put \"/posts/#{post.id}.json\", params: update_params", " expect(response.status).to eq(409)\n end", " it \"raises an error when the post parameter is missing\" do\n update_params.delete(:post)\n put \"/posts/#{post.id}.json\", params: update_params\n expect(response.status).to eq(400)\n expect(response.message.downcase).to eq(\"bad request\")\n end", " it \"raises an error when the user doesn't have permission to see the post\" do\n post = Fabricate(:private_message_post, post_number: 3)\n put \"/posts/#{post.id}.json\", params: update_params\n expect(response).to be_forbidden\n end", " it \"updates post's raw attribute\" do\n put \"/posts/#{post.id}.json\", params: { post: { raw: 'edited body ' } }", " expect(response.status).to eq(200)\n expect(response.parsed_body['post']['raw']).to eq('edited body')\n expect(post.reload.raw).to eq('edited body')\n end", " it \"extracts links from the new body\" do\n param = update_params\n param[:post][:raw] = 'I just visited this https://google.com so many cool links'", " put \"/posts/#{post.id}.json\", params: param", " expect(response.status).to eq(200)\n expect(TopicLink.count).to eq(1)\n end", " it \"doesn't allow updating of deleted posts\" do\n first_post = post.topic.ordered_posts.first\n PostDestroyer.new(moderator, first_post).destroy", " put \"/posts/#{first_post.id}.json\", params: update_params\n expect(response).not_to be_successful\n end\n end", " describe \"when logged in as staff\" do\n before do\n sign_in(moderator)\n end", " it \"supports updating posts in deleted topics\" do\n first_post = post.topic.ordered_posts.first\n PostDestroyer.new(moderator, first_post).destroy", " put \"/posts/#{first_post.id}.json\", params: update_params\n expect(response.status).to eq(200)", " post.reload\n expect(post.raw).to eq('edited body')\n end", " it \"won't update bump date if post is a whisper\" do\n created_at = freeze_time 1.day.ago\n post = Fabricate(:post, post_type: Post.types[:whisper], user: user)", " unfreeze_time\n put \"/posts/#{post.id}.json\", params: update_params", " expect(response.status).to eq(200)\n expect(post.topic.reload.bumped_at).to eq_time(created_at)\n end\n end", " describe \"when logged in as group moderator\" do\n fab!(:topic) { Fabricate(:topic, category: category) }\n fab!(:post) { Fabricate(:post, user: user, topic: topic) }\n fab!(:group_user) { Fabricate(:group_user) }\n let(:user_gm) { group_user.user }\n let(:group) { group_user.group }", " before do\n SiteSetting.enable_category_group_moderation = true\n post.topic.category.update!(reviewable_by_group_id: group.id, topic_id: topic.id)\n sign_in(user_gm)\n end", " it \"allows updating the category description\" do\n put \"/posts/#{post.id}.json\", params: update_params\n expect(response.status).to eq(200)", " post.reload\n expect(post.raw).to eq('edited body')\n expect(UserHistory.where(action: UserHistory.actions[:post_edit]).count).to eq(1)\n end", " it \"can not update category descriptions in other categories\" do\n second_category = Fabricate(:category)\n topic.update!(category: second_category)", " put \"/posts/#{post.id}.json\", params: update_params\n expect(response.status).to eq(403)\n end", " end", " it 'can not change category to a disallowed category' do\n post = create_post\n sign_in(post.user)", " category = Fabricate(:category)\n category.set_permissions(staff: :full)\n category.save!", " put \"/posts/#{post.id}.json\", params: {\n post: { category_id: category.id, raw: \"this is a test edit to post\" }\n }", " expect(response.status).not_to eq(200)\n expect(post.topic.category_id).not_to eq(category.id)\n end", " it 'can not move to a category that requires topic approval' do\n post = create_post\n sign_in(post.user)", " category = Fabricate(:category)\n category.custom_fields[Category::REQUIRE_TOPIC_APPROVAL] = true\n category.save!", " put \"/posts/#{post.id}.json\", params: { post: { category_id: category.id, raw: \"this is a test edit to post\" } }", " expect(response.status).to eq(403)\n expect(post.topic.reload.category_id).not_to eq(category.id)\n end", " describe \"with Post.plugin_permitted_update_params\" do\n before do\n plugin = Plugin::Instance.new\n plugin.add_permitted_post_update_param(:random_number) do |post, value|\n post.custom_fields[:random_number] = value\n post.save\n end\n end", " after do\n DiscoursePluginRegistry.reset!\n end", " it \"calls blocks passed into `add_permitted_post_update_param`\" do\n sign_in(post.user)\n put \"/posts/#{post.id}.json\", params: {\n post: {\n raw: \"this is a random post\",\n raw_old: post.raw,\n random_number: 244\n }\n }", " expect(response.status).to eq(200)\n expect(post.reload.custom_fields[:random_number]).to eq(\"244\")\n end\n end\n end", " describe \"#destroy_bookmark\" do\n fab!(:post) { Fabricate(:post) }\n fab!(:bookmark) { Fabricate(:bookmark, user: user, bookmarkable: post) }", " before do\n sign_in(user)\n end", " it \"deletes the bookmark\" do\n bookmark_id = bookmark.id\n delete \"/posts/#{post.id}/bookmark.json\"\n expect(Bookmark.find_by(id: bookmark_id)).to eq(nil)\n end", " context \"when the user still has bookmarks in the topic\" do\n before do\n Fabricate(:bookmark, user: user, bookmarkable: Fabricate(:post, topic: post.topic))\n end\n it \"marks topic_bookmarked as true\" do\n delete \"/posts/#{post.id}/bookmark.json\"\n expect(response.parsed_body['topic_bookmarked']).to eq(true)\n end\n end\n end", " describe '#wiki' do\n include_examples \"action requires login\", :put, \"/posts/2/wiki.json\"", " describe \"when logged in\" do\n before do\n sign_in(user)\n end", " let!(:post) { post_by_user }", " it \"returns 400 when wiki parameter is not present\" do\n sign_in(admin)", " put \"/posts/#{post.id}/wiki.json\", params: {}", " expect(response.status).to eq(400)\n end", " it \"raises an error if the user doesn't have permission to wiki the post\" do\n put \"/posts/#{post.id}/wiki.json\", params: { wiki: 'true' }\n expect(response).to be_forbidden\n end", " it \"toggle wiki status should create a new version\" do\n sign_in(admin)\n another_user = Fabricate(:user)\n another_post = Fabricate(:post, user: another_user)", " expect do\n put \"/posts/#{another_post.id}/wiki.json\", params: { wiki: 'true' }\n end.to change { another_post.reload.version }.by(1)", " expect do\n put \"/posts/#{another_post.id}/wiki.json\", params: { wiki: 'false' }\n end.to change { another_post.reload.version }.by(-1)", " sign_in(Fabricate(:admin))", " expect do\n put \"/posts/#{another_post.id}/wiki.json\", params: { wiki: 'true' }\n end.to change { another_post.reload.version }.by(1)\n end", " it \"can wiki a post\" do\n sign_in(admin)\n put \"/posts/#{post.id}/wiki.json\", params: { wiki: 'true' }", " post.reload\n expect(post.wiki).to eq(true)\n end", " it \"can unwiki a post\" do\n wikied_post = Fabricate(:post, user: user, wiki: true)\n sign_in(admin)", " put \"/posts/#{wikied_post.id}/wiki.json\", params: { wiki: 'false' }", " wikied_post.reload\n expect(wikied_post.wiki).to eq(false)\n end\n end\n end", " describe '#post_type' do\n include_examples \"action requires login\", :put, \"/posts/2/post_type.json\"", " describe \"when logged in\" do\n before do\n sign_in(moderator)\n end", " let!(:post) { post_by_user }", " it \"raises an error if the user doesn't have permission to change the post type\" do\n sign_in(user)", " put \"/posts/#{post.id}/post_type.json\", params: { post_type: 2 }\n expect(response).to be_forbidden\n end", " it \"returns 400 if post_type parameter is not present\" do\n put \"/posts/#{post.id}/post_type.json\", params: {}", " expect(response.status).to eq(400)\n end", " it \"returns 400 if post_type parameters is invalid\" do\n put \"/posts/#{post.id}/post_type.json\", params: { post_type: -1 }", " expect(response.status).to eq(400)\n end", " it \"can change the post type\" do\n put \"/posts/#{post.id}/post_type.json\", params: { post_type: 2 }", " post.reload\n expect(post.post_type).to eq(2)\n end\n end\n end", " describe '#rebake' do\n include_examples \"action requires login\", :put, \"/posts/2/rebake.json\"", " describe \"when logged in\" do\n let!(:post) { post_by_user }", " it \"raises an error if the user doesn't have permission to rebake the post\" do\n sign_in(user)\n put \"/posts/#{post.id}/rebake.json\"\n expect(response).to be_forbidden\n end", " it \"can rebake the post\" do\n sign_in(moderator)\n put \"/posts/#{post.id}/rebake.json\"\n expect(response.status).to eq(200)\n end", " it \"will invalidate broken images cache\" do\n sign_in(moderator)\n PostHotlinkedMedia.create!(url: \"https://example.com/image.jpg\", post: post, status: 'download_failed')\n put \"/posts/#{post.id}/rebake.json\"\n post.reload\n expect(post.post_hotlinked_media).to eq([])\n end\n end\n end", " describe '#create' do\n include_examples 'action requires login', :post, \"/posts.json\"", " before do\n SiteSetting.min_first_post_typing_time = 0\n SiteSetting.whispers_allowed_groups = \"#{Group::AUTO_GROUPS[:staff]}\"\n end", " context 'with api' do\n it 'memoizes duplicate requests' do\n raw = \"this is a test post 123 #{SecureRandom.hash}\"\n title = \"this is a title #{SecureRandom.hash}\"", " master_key = Fabricate(:api_key).key", " post \"/posts.json\",\n params: { raw: raw, title: title, wpid: 1 },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)\n original = response.body", " post \"/posts.json\",\n params: { raw: raw, title: title, wpid: 2 },\n headers: { HTTP_API_USERNAME: user.username_lower, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)\n expect(response.body).to eq(original)\n end", " it 'allows to create posts in import_mode' do\n Jobs.run_immediately!\n NotificationEmailer.enable\n post_1 = Fabricate(:post)\n master_key = Fabricate(:api_key).key", " post \"/posts.json\",\n params: { raw: 'this is test reply 1', topic_id: post_1.topic.id, reply_to_post_number: 1 },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)\n expect(post_1.topic.user.notifications.count).to eq(1)\n post_1.topic.user.notifications.destroy_all", " post \"/posts.json\",\n params: { raw: 'this is test reply 2', topic_id: post_1.topic.id, reply_to_post_number: 1, import_mode: true },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)\n expect(post_1.topic.user.notifications.count).to eq(0)", " post \"/posts.json\",\n params: { raw: 'this is test reply 3', topic_id: post_1.topic.id, reply_to_post_number: 1, import_mode: false },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)\n expect(post_1.topic.user.notifications.count).to eq(1)\n end", " it 'allows a topic to be created with an external_id' do\n master_key = Fabricate(:api_key).key\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: \"this is some post\",\n external_id: 'external_id'\n }, headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)", " new_topic = Topic.last", " expect(new_topic.external_id).to eq('external_id')\n end", " it 'prevents whispers for regular users' do\n post_1 = Fabricate(:post)\n user_key = ApiKey.create!(user: user).key", " post \"/posts.json\",\n params: { raw: 'this is test whisper', topic_id: post_1.topic.id, reply_to_post_number: 1, whisper: true },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: user_key }", " expect(response.status).to eq(403)\n end", " it 'does not advance draft' do\n Draft.set(user, Draft::NEW_TOPIC, 0, \"test\")\n user_key = ApiKey.create!(user: user).key", " post \"/posts.json\",\n params: { title: 'this is a test topic', raw: 'this is test whisper' },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: user_key }", " expect(response.status).to eq(200)\n expect(Draft.get(user, Draft::NEW_TOPIC, 0)).to eq(\"test\")\n end", " it 'will raise an error if specified category cannot be found' do\n user = Fabricate(:admin)\n master_key = Fabricate(:api_key).key", " post \"/posts.json\",\n params: { title: 'this is a test title', raw: 'this is test body', category: 'invalid' },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(400)", " expect(response.parsed_body[\"errors\"]).to include(\n I18n.t(\"invalid_params\", message: \"category\")\n )\n end", " it 'will raise an error if specified embed_url is invalid' do\n user = Fabricate(:admin)\n master_key = Fabricate(:api_key).key", " post \"/posts.json\",\n params: { title: 'this is a test title', raw: 'this is test body', embed_url: '/test.txt' },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(422)\n end", " it \"creates unlisted topic with admin master key\" do\n master_key = Fabricate(:api_key).key", " expect do\n post \"/posts.json\",\n params: { raw: \"this is a test title\", title: \"this is test body\", unlist_topic: true },\n headers: { HTTP_API_USERNAME: admin.username, HTTP_API_KEY: master_key }\n end.to change { Topic.count }.by(1)", " expect(response.status).to eq(200)\n expect(Topic.find(response.parsed_body[\"topic_id\"]).visible).to eq(false)\n end", " it \"prevents creation of unlisted topic with non-admin key\" do\n user_key = ApiKey.create!(user: user).key", " expect do\n post \"/posts.json\",\n params: { raw: \"this is a test title\", title: \"this is test body\", unlist_topic: true },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: user_key }\n end.not_to change { Topic.count }", " expect(response.status).to eq(422)\n expect(response.parsed_body[\"errors\"]).to include(\n I18n.t(\"activerecord.errors.models.topic.attributes.base.unable_to_unlist\")\n )\n end\n end", " describe \"when logged in\" do\n fab!(:user) { Fabricate(:user) }", " before do\n sign_in(user)\n end", " context \"when fast typing\" do\n before do\n SiteSetting.min_first_post_typing_time = 3000\n SiteSetting.auto_silence_fast_typers_max_trust_level = 1\n end", " it 'queues the post if min_first_post_typing_time is not met' do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n composer_open_duration_msecs: 204,\n typing_duration_msecs: 100,\n reply_to_post_number: 123\n }", " expect(response.status).to eq(200)\n parsed = response.parsed_body", " expect(parsed[\"action\"]).to eq(\"enqueued\")", " user.reload\n expect(user).to be_silenced", " rp = ReviewableQueuedPost.find_by(created_by: user)\n expect(rp.payload['typing_duration_msecs']).to eq(100)\n expect(rp.payload['composer_open_duration_msecs']).to eq(204)\n expect(rp.payload['reply_to_post_number']).to eq(123)\n expect(rp.reviewable_scores.first.reason).to eq('fast_typer')", " expect(parsed['pending_post']).to be_present\n expect(parsed['pending_post']['id']).to eq(rp.id)\n expect(parsed['pending_post']['raw']).to eq(\"this is the test content\")", " mod = moderator\n rp.perform(mod, :approve_post)", " user.reload\n expect(user).not_to be_silenced\n end", " it \"doesn't enqueue posts when user first creates a topic\" do\n topic = Fabricate(:post, user: user).topic", " Draft.set(user, \"should_clear\", 0, \"{'a' : 'b'}\")", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n composer_open_duration_msecs: 204,\n typing_duration_msecs: 100,\n topic_id: topic.id,\n draft_key: \"should_clear\"\n }", " expect(response.status).to eq(200)\n parsed = response.parsed_body", " expect(parsed[\"action\"]).not_to be_present", " expect {\n Draft.get(user, \"should_clear\", 0)\n }.to raise_error(Draft::OutOfSequence)\n end", " it \"doesn't enqueue replies when the topic is closed\" do\n topic = Fabricate(:closed_topic)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n topic_id: topic.id\n }", " expect(response).not_to be_successful\n parsed = response.parsed_body\n expect(parsed[\"action\"]).not_to eq(\"enqueued\")\n end", " it \"doesn't enqueue replies when the post is too long\" do\n SiteSetting.max_post_length = 10", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic'", "", " }", " expect(response).not_to be_successful\n parsed = response.parsed_body\n expect(parsed[\"action\"]).not_to eq(\"enqueued\")\n end\n end", " it 'silences correctly based on auto_silence_first_post_regex' do\n SiteSetting.auto_silence_first_post_regex = \"I love candy|i eat s[1-5]\"", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'when I eat s3 sometimes when not looking'\n }", " expect(response.status).to eq(200)\n parsed = response.parsed_body", " expect(parsed[\"action\"]).to eq(\"enqueued\")\n reviewable = ReviewableQueuedPost.find_by(created_by: user)\n score = reviewable.reviewable_scores.first\n expect(score.reason).to eq('auto_silence_regex')", " user.reload\n expect(user).to be_silenced\n end", " it 'silences correctly based on silence watched words' do\n SiteSetting.watched_words_regular_expressions = true\n WatchedWord.create!(action: WatchedWord.actions[:silence], word: 'I love candy')\n WatchedWord.create!(action: WatchedWord.actions[:silence], word: 'i eat s[1-5]')", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'when I eat s3 sometimes when not looking'\n }", " expect(response.status).to eq(200)\n parsed = response.parsed_body", " expect(parsed[\"action\"]).to eq(\"enqueued\")\n reviewable = ReviewableQueuedPost.find_by(created_by: user)\n score = reviewable.reviewable_scores.first\n expect(score.reason).to eq('auto_silence_regex')", " user.reload\n expect(user).to be_silenced\n end", " it \"can send a message to a group\" do\n Group.refresh_automatic_groups!\n group = Group.create(name: 'test_group', messageable_level: Group::ALIAS_LEVELS[:nobody])\n user1 = user\n group.add(user1)", " post \"/posts.json\", params: {\n raw: 'I can haz a test',\n title: 'I loves my test',\n target_recipients: group.name,\n archetype: Archetype.private_message\n }", " expect(response).not_to be_successful", " # allow pm to this group\n group.update_columns(messageable_level: Group::ALIAS_LEVELS[:everyone])", " post \"/posts.json\", params: {\n raw: 'I can haz a test',\n title: 'I loves my test',\n target_recipients: \"test_Group\",\n archetype: Archetype.private_message\n }", " expect(response.status).to eq(200)", " parsed = response.parsed_body\n post = Post.find(parsed['id'])", " expect(post.topic.topic_allowed_users.length).to eq(1)\n expect(post.topic.topic_allowed_groups.length).to eq(1)\n end", " it \"can send a message to a group with caps\" do\n Group.refresh_automatic_groups!\n group = Group.create(name: 'Test_group', messageable_level: Group::ALIAS_LEVELS[:nobody])\n user1 = user\n group.add(user1)", " # allow pm to this group\n group.update_columns(messageable_level: Group::ALIAS_LEVELS[:everyone])", " post \"/posts.json\", params: {\n raw: 'I can haz a test',\n title: 'I loves my test',\n target_recipients: \"test_Group\",\n archetype: Archetype.private_message\n }", " expect(response.status).to eq(200)", " parsed = response.parsed_body\n post = Post.find(parsed['id'])", " expect(post.topic.topic_allowed_users.length).to eq(1)\n expect(post.topic.topic_allowed_groups.length).to eq(1)\n end", " it \"returns the nested post with a param\" do\n post \"/posts.json\", params: {\n raw: 'this is the test content ',\n title: 'this is the test title for the topic',\n nested_post: true\n }", " expect(response.status).to eq(200)\n parsed = response.parsed_body\n expect(parsed['post']).to be_present\n expect(parsed['post']['raw']).to eq('this is the test content')\n expect(parsed['post']['cooked']).to be_present\n end", " it 'protects against dupes' do\n raw = \"this is a test post 123 #{SecureRandom.hash}\"\n title = \"this is a title #{SecureRandom.hash}\"", " expect do\n post \"/posts.json\", params: { raw: raw, title: title, wpid: 1 }\n end.to change { Post.count }", " expect(response.status).to eq(200)", " expect do\n post \"/posts.json\", params: { raw: raw, title: title, wpid: 2 }\n end.to_not change { Post.count }", " expect(response.status).to eq(422)\n end", " it 'cannot create a post in a disallowed category' do\n category.set_permissions(staff: :full)\n category.save!", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n category: category.id,\n meta_data: { xyz: 'abc' }\n }", " expect(response.status).to eq(403)\n end", " it 'cannot create a post with a tag that is restricted' do\n SiteSetting.tagging_enabled = true\n tag = Fabricate(:tag)\n category.allowed_tags = [tag.name]\n category.save!", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n tags: [tag.name],\n }", " expect(response.status).to eq(422)\n json = response.parsed_body\n expect(json['errors']).to be_present\n end", " it 'cannot create a post with a tag when tagging is disabled' do\n SiteSetting.tagging_enabled = false\n tag = Fabricate(:tag)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n tags: [tag.name],\n }", " expect(response.status).to eq(422)\n json = response.parsed_body\n expect(json['errors']).to be_present\n end", " it 'cannot create a post with a tag without tagging permission' do\n SiteSetting.tagging_enabled = true\n SiteSetting.min_trust_level_to_tag_topics = 4\n tag = Fabricate(:tag)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n tags: [tag.name],\n }", " expect(response.status).to eq(422)\n json = response.parsed_body\n expect(json['errors']).to be_present\n end", " it 'can create a post with a tag when tagging is enabled' do\n SiteSetting.tagging_enabled = true\n tag = Fabricate(:tag)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n tags: [tag.name],\n }", " expect(response.status).to eq(200)\n expect(Post.last.topic.tags.count).to eq(1)\n end", " it 'creates the post' do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n category: category.id,\n meta_data: { xyz: 'abc' }\n }", " expect(response.status).to eq(200)", " new_post = Post.last\n topic = new_post.topic", " expect(new_post.user).to eq(user)\n expect(new_post.raw).to eq('this is the test content')\n expect(topic.title).to eq('This is the test title for the topic')\n expect(topic.category).to eq(category)\n expect(topic.meta_data).to eq(\"xyz\" => 'abc')\n expect(topic.visible).to eq(true)\n end", " it 'can create an uncategorized topic' do\n title = 'this is the test title for the topic'", " expect do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: title,\n category: \"\"\n }", " expect(response.status).to eq(200)\n end.to change { Topic.count }.by(1)", " topic = Topic.last", " expect(topic.title).to eq(title.capitalize)\n expect(topic.category_id).to eq(SiteSetting.uncategorized_category_id)\n end", " it 'can create a reply to a post' do\n topic = Fabricate(:private_message_post, user: user).topic\n post_2 = Fabricate(:private_message_post, user: user, topic: topic)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n topic_id: topic.id,\n reply_to_post_number: post_2.post_number,\n image_sizes: { width: '100', height: '200' }\n }", " expect(response.status).to eq(200)", " new_post = Post.last\n topic = new_post.topic", " expect(new_post.user).to eq(user)\n expect(new_post.raw).to eq('this is the test content')\n expect(new_post.reply_to_post_number).to eq(post_2.post_number)", " job_args = Jobs::ProcessPost.jobs.first[\"args\"].first", " expect(job_args[\"image_sizes\"]).to eq(\"width\" => '100', \"height\" => '200')\n end", " it 'creates a private post' do\n user_2 = Fabricate(:user)\n user_3 = Fabricate(:user, username: \"foo_bar\")", " # In certain edge cases, it's possible to end up with a username\n # containing characters that would normally fail to validate\n user_4 = Fabricate(:user, username: \"Iyi_Iyi\")\n user_4.update_attribute(:username, \"İyi_İyi\")\n user_4.update_attribute(:username_lower, \"İyi_İyi\".downcase)\n Group.refresh_automatic_groups!", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: \"#{user_2.username},Foo_Bar,İyi_İyi\"\n }", " expect(response.status).to eq(200)", " new_post = Post.last\n new_topic = Topic.last", " expect(new_post.user).to eq(user)\n expect(new_topic.private_message?).to eq(true)\n expect(new_topic.allowed_users).to contain_exactly(user, user_2, user_3, user_4)\n end", " context \"when target_recipients not provided\" do\n it \"errors when creating a private post\" do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: \"\"\n }", " expect(response.status).to eq(422)\n expect(response.parsed_body[\"errors\"]).to include(\n I18n.t(\"activerecord.errors.models.topic.attributes.base.no_user_selected\")\n )\n end\n end", " context \"when topic_id is set\" do\n fab!(:topic) { Fabricate(:topic) }", " it \"errors when creating a private post\" do\n user_2 = Fabricate(:user)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: user_2.username,\n topic_id: topic.id\n }", " expect(response.status).to eq(422)\n expect(response.parsed_body[\"errors\"]).to include(\n I18n.t(\"create_pm_on_existing_topic\")\n )\n end\n end", " context \"with errors\" do\n it \"does not succeed\" do\n post \"/posts.json\", params: { raw: 'test' }\n expect(response).not_to be_successful\n expect(response.status).to eq(422)\n end", " it \"it triggers flag_linked_posts_as_spam when the post creator returns spam\" do\n SiteSetting.newuser_spam_host_threshold = 1\n sign_in(Fabricate(:user, trust_level: 0))", " post \"/posts.json\", params: {\n raw: 'this is the test content http://fakespamwebsite.com http://fakespamwebsite.com/spam http://fakespamwebsite.com/spammy',\n title: 'this is the test title for the topic',\n meta_data: { xyz: 'abc' }\n }", " expect(response.parsed_body[\"errors\"]).to include(I18n.t(:spamming_host))\n end", " context \"when allow_uncategorized_topics is false\" do\n before do\n SiteSetting.allow_uncategorized_topics = false\n end", " it \"cant create an uncategorized post\" do\n post \"/posts.json\", params: {\n raw: \"a new post with no category\",\n title: \"a new post with no category\"\n }\n expect(response).not_to be_successful\n end", " context \"as staff\" do\n before do\n sign_in(admin)\n end", " it \"cant create an uncategorized post\" do\n post \"/posts.json\", params: {\n raw: \"a new post with no category\",\n title: \"a new post with no category\"\n }\n expect(response).not_to be_successful\n end\n end\n end\n end", " context \"with mentions\" do\n fab!(:user_to_mention) { Fabricate(:user) }", " it \"returns mentioned users\" do\n post \"/posts.json\", params: {\n raw: \"I am mentioning @#{user_to_mention.username}\",\n topic_id: topic.id,\n }", " expect(response.status).to eq(200)\n json = response.parsed_body\n expect(json[\"mentioned_users\"].length).to be(1)", " mentioned_user = json[\"mentioned_users\"][0]\n expect(mentioned_user[\"id\"]).to be(user_to_mention.id)\n expect(mentioned_user[\"name\"]).to eq(user_to_mention.name)\n expect(mentioned_user[\"username\"]).to eq(user_to_mention.username)\n end", " it \"returns an empty list of mentioned users if nobody was mentioned\" do\n post \"/posts.json\", params: {\n raw: \"No mentions here\",\n topic_id: topic.id,\n }", " expect(response.status).to eq(200)\n expect(response.parsed_body[\"mentioned_users\"].length).to be(0)\n end", " it \"returns an empty list of mentioned users if an nonexistent user was mentioned\" do\n post \"/posts.json\", params: {\n raw: \"Mentioning a @stranger\",\n topic_id: topic.id,\n }", " expect(response.status).to eq(200)\n expect(response.parsed_body[\"mentioned_users\"].length).to be(0)\n end", " it \"doesn't return user status on mentions by default\" do\n user_to_mention.set_status!(\"off to dentist\", \"tooth\")", " post \"/posts.json\", params: {\n raw: \"I am mentioning @#{user_to_mention.username}\",\n topic_id: topic.id,\n }", " expect(response.status).to eq(200)\n json = response.parsed_body\n expect(json[\"mentioned_users\"].length).to be(1)", " status = json[\"mentioned_users\"][0][\"status\"]\n expect(status).to be_nil\n end", " it \"returns user status on mentions if status is enabled in site settings\" do\n SiteSetting.enable_user_status = true\n user_to_mention.set_status!(\"off to dentist\", \"tooth\")", " post \"/posts.json\", params: {\n raw: \"I am mentioning @#{user_to_mention.username}\",\n topic_id: topic.id,\n }", " expect(response.status).to eq(200)\n json = response.parsed_body\n expect(json[\"mentioned_users\"].length).to be(1)", " status = json[\"mentioned_users\"][0][\"status\"]\n expect(status).to be_present\n expect(status[\"emoji\"]).to eq(user_to_mention.user_status.emoji)\n expect(status[\"description\"]).to eq(user_to_mention.user_status.description)\n end\n end\n end", " context \"with topic unlisting\" do\n context \"when logged in as staff\" do\n before do\n sign_in(admin)\n end", " it \"creates an unlisted topic\" do\n expect do\n post \"/posts.json\", params: {\n raw: \"this is the test content\",\n title: \"this is the test title for the topic\",\n unlist_topic: true\n }\n end.to change { Topic.count }.by(1)", " expect(response.status).to eq(200)\n expect(Topic.find(response.parsed_body[\"topic_id\"]).visible).to eq(false)\n end\n end", " context \"when logged in as a non-staff user\" do\n before do\n sign_in(user)\n end", " it \"prevents creation of an unlisted topic\" do\n expect do\n post \"/posts.json\", params: {\n raw: \"this is the test content\",\n title: \"this is the test title for the topic\",\n unlist_topic: true\n }\n end.not_to change { Topic.count }", " expect(response.status).to eq(422)\n expect(response.parsed_body[\"errors\"]).to include(\n I18n.t(\"activerecord.errors.models.topic.attributes.base.unable_to_unlist\")\n )\n end\n end\n end", " describe 'shared draft' do\n fab!(:destination_category) { Fabricate(:category) }", " it \"will raise an error for regular users\" do\n post \"/posts.json\", params: {\n raw: 'this is the shared draft content',\n title: \"this is the shared draft title\",\n category: destination_category.id,\n shared_draft: 'true'\n }\n expect(response).not_to be_successful\n end", " describe \"as a staff user\" do\n before do\n sign_in(moderator)\n end", " it \"will raise an error if there is no shared draft category\" do\n post \"/posts.json\", params: {\n raw: 'this is the shared draft content',\n title: \"this is the shared draft title\",\n category: destination_category.id,\n shared_draft: 'true'\n }\n expect(response).not_to be_successful\n end", " context \"with a shared category\" do\n fab!(:shared_category) { Fabricate(:category) }\n before do\n SiteSetting.shared_drafts_category = shared_category.id\n end", " it \"will work if the shared draft category is present\" do\n post \"/posts.json\", params: {\n raw: 'this is the shared draft content',\n title: \"this is the shared draft title\",\n category: destination_category.id,\n shared_draft: 'true'\n }\n expect(response.status).to eq(200)\n result = response.parsed_body\n topic = Topic.find(result['topic_id'])\n expect(topic.category_id).to eq(shared_category.id)\n expect(topic.shared_draft.category_id).to eq(destination_category.id)\n end\n end\n end\n end", " describe 'warnings' do\n fab!(:user_2) { Fabricate(:user) }", " before do\n Group.refresh_automatic_groups!\n end", " context 'as a staff user' do\n before do\n sign_in(admin)\n end", " it 'should be able to mark a topic as warning' do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: user_2.username,\n is_warning: true\n }", " expect(response.status).to eq(200)", " new_topic = Topic.last", " expect(new_topic.title).to eq('This is some post')\n expect(new_topic.is_official_warning?).to eq(true)\n end", " it 'should be able to mark a topic as not a warning' do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: user_2.username,\n is_warning: false\n }", " expect(response.status).to eq(200)", " new_topic = Topic.last", " expect(new_topic.title).to eq('This is some post')\n expect(new_topic.is_official_warning?).to eq(false)\n end\n end", " context 'as a normal user' do\n it 'should not be able to mark a topic as warning' do\n sign_in(user)\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: user_2.username,\n is_warning: true\n }", " expect(response.status).to eq(200)", " new_topic = Topic.last", " expect(new_topic.title).to eq('This is some post')\n expect(new_topic.is_official_warning?).to eq(false)\n end\n end\n end", " context \"with topic bump\" do\n shared_examples \"it works\" do\n it \"should be able to skip topic bumping\" do\n original_bumped_at = 1.day.ago\n topic = Fabricate(:topic, bumped_at: original_bumped_at)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n topic_id: topic.id,\n no_bump: true\n }", " expect(response.status).to eq(200)\n expect(topic.reload.bumped_at).to eq_time(original_bumped_at)\n end", " it \"should be able to post with topic bumping\" do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n topic_id: topic.id\n }", " expect(response.status).to eq(200)\n expect(topic.reload.bumped_at).to eq_time(topic.posts.last.created_at)\n end\n end", " context \"with admins\" do\n before do\n sign_in(admin)\n end", " include_examples \"it works\"\n end", " context \"with moderators\" do\n before do\n sign_in(moderator)\n end", " include_examples \"it works\"\n end", " context \"with TL4 users\" do\n fab!(:trust_level_4) { Fabricate(:trust_level_4) }", " before do\n sign_in(trust_level_4)\n end", " include_examples \"it works\"\n end", " context \"with users\" do\n fab!(:topic) { Fabricate(:topic) }", " [:user].each do |user|\n it \"will raise an error for #{user}\" do\n sign_in(Fabricate(user))\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n topic_id: topic.id,\n no_bump: true\n }\n expect(response.status).to eq(400)\n end\n end\n end\n end", " context \"with featured links\" do\n it \"allows to create topics with featured links\" do\n sign_in(user_trust_level_1)", " post \"/posts.json\", params: {\n title: \"this is the test title for the topic\",\n raw: \"this is the test content\",\n featured_link: \"https://discourse.org\"\n }", " expect(response.status).to eq(200)\n end", " it \"doesn't allow TL0 users to create topics with featured links\" do\n sign_in(user_trust_level_0)", " post \"/posts.json\", params: {\n title: \"this is the test title for the topic\",\n raw: \"this is the test content\",\n featured_link: \"https://discourse.org\"\n }", " expect(response.status).to eq(422)\n end", " it \"doesn't allow to create topics with featured links if featured links are disabled in settings\" do\n SiteSetting.topic_featured_link_enabled = false\n sign_in(user_trust_level_1)", " post \"/posts.json\", params: {\n title: \"this is the test title for the topic\",\n raw: \"this is the test content\",\n featured_link: \"https://discourse.org\"\n }", " expect(response.status).to eq(422)\n end", " it \"doesn't allow to create topics with featured links in the category with forbidden feature links\" do\n category = Fabricate(:category, topic_featured_link_allowed: false)\n sign_in(user_trust_level_1)", " post \"/posts.json\", params: {\n title: \"this is the test title for the topic\",\n raw: \"this is the test content\",\n featured_link: \"https://discourse.org\",\n category: category.id\n }", " expect(response.status).to eq(422)\n end\n end\n end", " describe '#revisions' do\n fab!(:post) { Fabricate(:post, version: 2) }\n let(:post_revision) { Fabricate(:post_revision, post: post) }", " it \"throws an exception when revision is < 2\" do\n get \"/posts/#{post.id}/revisions/1.json\"\n expect(response.status).to eq(400)\n end", " context \"when edit history is not visible to the public\" do", " before { SiteSetting.edit_history_visible_to_public = false }", " it \"ensures anonymous cannot see the revisions\" do\n get \"/posts/#{post.id}/revisions/#{post_revision.number}.json\"\n expect(response).to be_forbidden\n end", " it \"ensures regular user cannot see the revisions\" do\n sign_in(user)\n get \"/posts/#{post.id}/revisions/#{post_revision.number}.json\"\n expect(response).to be_forbidden\n end", " it \"ensures staff can see the revisions\" do\n sign_in(admin)\n get \"/posts/#{post.id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(200)\n end", " it \"ensures poster can see the revisions\" do\n user = Fabricate(:active_user)\n sign_in(user)", " post = Fabricate(:post, user: user, version: 3)\n pr = Fabricate(:post_revision, user: user, post: post)", " get \"/posts/#{pr.post_id}/revisions/#{pr.number}.json\"\n expect(response.status).to eq(200)\n end", " it \"ensures trust level 4 cannot see the revisions\" do\n sign_in(Fabricate(:user, trust_level: 4))\n get \"/posts/#{post_revision.post_id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(403)\n end\n end", " context \"when post is hidden\" do\n before {\n post.hidden = true\n post.save\n }", " it \"throws an exception for users\" do\n sign_in(user)\n get \"/posts/#{post.id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(404)\n end", " it \"works for admins\" do\n sign_in(admin)\n get \"/posts/#{post.id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(200)\n end\n end", " context \"when edit history is visible to everyone\" do", " before { SiteSetting.edit_history_visible_to_public = true }", " it \"ensures anyone can see the revisions\" do\n get \"/posts/#{post_revision.post_id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(200)\n end\n end", " context \"with deleted post\" do\n fab!(:deleted_post) { Fabricate(:post, user: admin, version: 3) }\n fab!(:deleted_post_revision) { Fabricate(:post_revision, user: admin, post: deleted_post) }", " before { deleted_post.trash!(admin) }", " it \"also work on deleted post\" do\n sign_in(admin)\n get \"/posts/#{deleted_post_revision.post_id}/revisions/#{deleted_post_revision.number}.json\"\n expect(response.status).to eq(200)\n end\n end", " context \"with deleted topic\" do\n fab!(:deleted_topic) { Fabricate(:topic, user: admin) }\n fab!(:post) { Fabricate(:post, user: admin, topic: deleted_topic, version: 3) }\n fab!(:post_revision) { Fabricate(:post_revision, user: admin, post: post) }", " before { deleted_topic.trash!(admin) }", " it \"also work on deleted topic\" do\n sign_in(admin)\n get \"/posts/#{post_revision.post_id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(200)\n end\n end", " context \"with a tagged topic\" do\n let(:tag) { Fabricate(:tag) }\n it \"works\" do\n SiteSetting.tagging_enabled = true", " post_revision.post.topic.update(tags: [tag])", " get \"/posts/#{post_revision.post_id}/revisions/latest.json\"\n expect(response.status).to eq(200)", " SiteSetting.tagging_enabled = false", " get \"/posts/#{post_revision.post_id}/revisions/latest.json\"\n expect(response.status).to eq(200)\n end\n end\n end", " describe '#revert' do\n include_examples 'action requires login', :put, \"/posts/123/revisions/2/revert.json\"", " fab!(:post) { Fabricate(:post, user: Fabricate(:user), raw: \"Lorem ipsum dolor sit amet, cu nam libris tractatos, ancillae senserit ius ex\") }\n let(:post_revision) { Fabricate(:post_revision, post: post, modifications: { \"raw\" => [\"this is original post body.\", \"this is edited post body.\"] }) }\n let(:blank_post_revision) { Fabricate(:post_revision, post: post, modifications: { \"edit_reason\" => [\"edit reason #1\", \"edit reason #2\"] }) }\n let(:same_post_revision) { Fabricate(:post_revision, post: post, modifications: { \"raw\" => [\"Lorem ipsum dolor sit amet, cu nam libris tractatos, ancillae senserit ius ex\", \"this is edited post body.\"] }) }", " let(:post_id) { post.id }\n let(:revision_id) { post_revision.number }", " describe 'when logged in as a regular user' do\n it \"does not work\" do\n sign_in(user)\n put \"/posts/#{post_id}/revisions/#{revision_id}/revert.json\"\n expect(response).to_not be_successful\n end\n end", " describe \"when logged in as staff\" do\n before do\n sign_in(moderator)\n end", " it \"fails when revision is < 2\" do\n put \"/posts/#{post_id}/revisions/1/revert.json\"\n expect(response.status).to eq(400)\n end", " it \"fails when post_revision record is not found\" do\n put \"/posts/#{post_id}/revisions/#{revision_id + 1}/revert.json\"\n expect(response).to_not be_successful\n end", " it \"fails when post record is not found\" do\n put \"/posts/#{post_id + 1}/revisions/#{revision_id}/revert.json\"\n expect(response).to_not be_successful\n end", " it \"fails when revision is blank\" do\n put \"/posts/#{post_id}/revisions/#{blank_post_revision.number}/revert.json\"\n expect(response.status).to eq(422)\n expect(response.parsed_body['errors']).to include(I18n.t('revert_version_same'))\n end", " it \"fails when revised version is same as current version\" do\n put \"/posts/#{post_id}/revisions/#{same_post_revision.number}/revert.json\"\n expect(response.status).to eq(422)\n expect(response.parsed_body['errors']).to include(I18n.t('revert_version_same'))\n end", " it \"works!\" do\n put \"/posts/#{post_id}/revisions/#{revision_id}/revert.json\"\n expect(response.status).to eq(200)\n end", " it \"supports reverting posts in deleted topics\" do\n first_post = post.topic.ordered_posts.first\n PostDestroyer.new(moderator, first_post).destroy", " put \"/posts/#{post_id}/revisions/#{revision_id}/revert.json\"\n expect(response.status).to eq(200)\n end\n end\n end", " describe '#expand_embed' do\n before do\n sign_in(user)\n end", " fab!(:post) { Fabricate(:post) }", " it \"raises an error when you can't see the post\" do\n post = Fabricate(:private_message_post)\n get \"/posts/#{post.id}/expand-embed.json\"\n expect(response).not_to be_successful\n end", " it \"retrieves the body when you can see the post\" do\n TopicEmbed.expects(:expanded_for).with(post).returns(\"full content\")\n get \"/posts/#{post.id}/expand-embed.json\"\n expect(response.status).to eq(200)\n expect(response.parsed_body['cooked']).to eq(\"full content\")\n end\n end", " describe '#flagged_posts' do\n include_examples \"action requires login\", :get, \"/posts/system/flagged.json\"", " describe \"when logged in\" do\n it \"raises an error if the user doesn't have permission to see the flagged posts\" do\n sign_in(user)\n get \"/posts/system/flagged.json\"\n expect(response).to be_forbidden\n end", " it \"can see the flagged posts when authorized\" do\n sign_in(moderator)\n get \"/posts/system/flagged.json\"\n expect(response.status).to eq(200)\n end", " it \"only shows agreed and deferred flags\" do\n post_agreed = create_post(user: user)\n post_deferred = create_post(user: user)\n post_disagreed = create_post(user: user)", " r0 = PostActionCreator.spam(moderator, post_agreed).reviewable\n r1 = PostActionCreator.off_topic(moderator, post_deferred).reviewable\n r2 = PostActionCreator.inappropriate(moderator, post_disagreed).reviewable", " r0.perform(admin, :agree_and_keep)\n r1.perform(admin, :ignore)\n r2.perform(admin, :disagree)", " sign_in(Fabricate(:moderator))\n get \"/posts/#{user.username}/flagged.json\"\n expect(response.status).to eq(200)", " expect(response.parsed_body.length).to eq(2)\n end\n end\n end", " describe '#deleted_posts' do\n include_examples \"action requires login\", :get, \"/posts/system/deleted.json\"", " describe \"when logged in\" do\n before do\n Group.refresh_automatic_groups!\n end", " it \"raises an error if the user doesn't have permission to see the deleted posts\" do\n sign_in(user)\n get \"/posts/system/deleted.json\"\n expect(response).to be_forbidden\n end", " it \"can see the deleted posts when authorized\" do\n sign_in(moderator)\n get \"/posts/system/deleted.json\"\n expect(response.status).to eq(200)\n end", " it \"does not raise if topic has been permanently deleted\" do\n post = Fabricate(:post, user: admin)\n PostDestroyer.new(admin, post).destroy\n post.update!(topic_id: -1000)", " sign_in(admin)\n get \"/posts/#{admin.username}/deleted.json\"\n expect(response.status).to eq(200)\n end", " it \"doesn't return secured categories for moderators if they don't have access\" do\n Fabricate(:moderator)", " group = Fabricate(:group)\n group.add_owner(user)", " secured_category = Fabricate(:private_category, group: group)\n secured_post = create_post(user: user, category: secured_category)\n PostDestroyer.new(admin, secured_post).destroy", " sign_in(moderator)\n get \"/posts/#{user.username}/deleted.json\"\n expect(response.status).to eq(200)", " data = response.parsed_body\n expect(data.length).to eq(0)\n end", " it \"doesn't return PMs for moderators\" do\n Fabricate(:moderator)", " pm_post = create_post(user: user, archetype: 'private_message', target_usernames: [admin.username])\n PostDestroyer.new(admin, pm_post).destroy", " sign_in(moderator)\n get \"/posts/#{user.username}/deleted.json\"\n expect(response.status).to eq(200)", " data = response.parsed_body\n expect(data.length).to eq(0)\n end", " it \"only shows posts deleted by other users\" do\n create_post(user: user)\n post_deleted_by_user = create_post(user: user)\n post_deleted_by_admin = create_post(user: user)", " PostDestroyer.new(user, post_deleted_by_user).destroy\n PostDestroyer.new(admin, post_deleted_by_admin).destroy", " sign_in(admin)\n get \"/posts/#{user.username}/deleted.json\"\n expect(response.status).to eq(200)", " data = response.parsed_body\n expect(data.length).to eq(1)\n expect(data[0][\"id\"]).to eq(post_deleted_by_admin.id)\n expect(data[0][\"deleted_by\"][\"id\"]).to eq(admin.id)\n end\n end\n end", " describe '#markdown_id' do\n it \"can be viewed by anonymous\" do\n post = Fabricate(:post, raw: \"123456789\")\n get \"/posts/#{post.id}/raw.json\"\n expect(response.status).to eq(200)\n expect(response.body).to eq(\"123456789\")\n end", " it \"renders a 404 page\" do\n get \"/posts/0/raw\"\n expect(response.status).to eq(404)\n expect(response.body).to include(I18n.t(\"page_not_found.title\"))\n end\n end", " describe '#markdown_num' do\n it \"can be viewed by anonymous\" do\n topic = Fabricate(:topic)\n post = Fabricate(:post, topic: topic, post_number: 1, raw: \"123456789\")\n post.save\n get \"/raw/#{topic.id}/1.json\"\n expect(response.status).to eq(200)\n expect(response.body).to eq(\"123456789\")\n end", " it \"can show whole topics\" do\n topic = Fabricate(:topic)\n post = Fabricate(:post, topic: topic, post_number: 1, raw: \"123456789\")\n post_2 = Fabricate(:post, topic: topic, post_number: 2, raw: \"abcdefghij\")\n post.save\n get \"/raw/#{topic.id}\"\n expect(response.status).to eq(200)\n expect(response.body).to include(\"123456789\", \"abcdefghij\")\n end\n end", " describe '#short_link' do\n fab!(:topic) { Fabricate(:topic) }\n fab!(:post) { Fabricate(:post, topic: topic) }", " it \"redirects to the topic\" do\n get \"/p/#{post.id}.json\"\n expect(response).to be_redirect\n end", " it \"returns a 403 when access is denied for JSON format\" do\n post = Fabricate(:private_message_post)\n get \"/p/#{post.id}.json\"\n expect(response).to be_forbidden\n end", " it \"returns a 403 when access is denied for HTML format\" do\n post = Fabricate(:private_message_post)\n get \"/p/#{post.id}\"\n expect(response).to be_forbidden\n expect(response.body).to have_tag(\"body.no-ember\")\n end", " it \"renders a 404 page\" do\n get \"/p/0\"\n expect(response.status).to eq(404)\n expect(response.body).to include(I18n.t(\"page_not_found.title\"))\n end\n end", " describe '#user_posts_feed' do\n it 'returns public posts rss feed' do\n public_post\n private_post", " get \"/u/#{user.username}/activity.rss\"", " expect(response.status).to eq(200)", " body = response.body", " expect(body).to_not include(private_post.url)\n expect(body).to include(public_post.url)\n end", " it \"doesn't include posts from hidden topics\" do\n public_post.topic.update!(visible: false)", " get \"/u/#{user.username}/activity.rss\"", " expect(response.status).to eq(200)", " body = response.body\n expect(body).not_to include(public_post.url)\n end", " it \"excludes small actions\" do\n small_action = Fabricate(:small_action, user: user)", " get \"/u/#{user.username}/activity.rss\"", " expect(response.status).to eq(200)", " body = response.body", " expect(body).not_to include(small_action.canonical_url)\n end", " it 'returns public posts as JSON' do\n public_post\n private_post", " get \"/u/#{user.username}/activity.json\"", " expect(response.status).to eq(200)", " body = response.body", " expect(body).to_not include(private_post.topic.slug)\n expect(body).to include(public_post.topic.slug)\n end", " it \"returns 404 if `hide_profile_and_presence` user option is checked\" do\n user.user_option.update_columns(hide_profile_and_presence: true)", " get \"/u/#{user.username}/activity.rss\"\n expect(response.status).to eq(404)", " get \"/u/#{user.username}/activity.json\"\n expect(response.status).to eq(404)\n end", " it \"succeeds when `allow_users_to_hide_profile` is false\" do\n user.user_option.update_columns(hide_profile_and_presence: true)\n SiteSetting.allow_users_to_hide_profile = false", " get \"/u/#{user.username}/activity.rss\"\n expect(response.status).to eq(200)", " get \"/u/#{user.username}/activity.json\"\n expect(response.status).to eq(200)\n end\n end", " describe '#latest' do\n context 'with private posts' do\n describe 'when not logged in' do\n it 'should return the right response' do\n Fabricate(:post)", " get \"/private-posts.rss\"", " expect(response.status).to eq(404)", " expect(response.body).to have_tag(\n \"input\", with: { value: \"private_posts\" }\n )\n end\n end", " it 'returns private posts rss feed' do\n sign_in(admin)", " public_post\n private_post\n get \"/private-posts.rss\"", " expect(response.status).to eq(200)", " body = response.body", " expect(body).to include(private_post.url)\n expect(body).to_not include(public_post.url)\n end", " it 'returns private posts for json' do\n sign_in(admin)", " public_post\n private_post\n get \"/private-posts.json\"\n expect(response.status).to eq(200)", " json = response.parsed_body\n post_ids = json['private_posts'].map { |p| p['id'] }", " expect(post_ids).to include private_post.id\n expect(post_ids).to_not include public_post.id\n end\n end", " context 'with public posts' do\n it 'returns public posts with topic rss feed' do\n public_post\n private_post", " get \"/posts.rss\"", " expect(response.status).to eq(200)", " body = response.body", " # we cache in redis, in rare cases this can cause a flaky test\n PostsHelper.clear_canonical_cache!(public_post)", " expect(body).to include(public_post.canonical_url)\n expect(body).to_not include(private_post.url)\n end", " it \"doesn't include posts from hidden topics\" do\n public_post.topic.update!(visible: false)", " get \"/posts.rss\"", " expect(response.status).to eq(200)", " body = response.body", " # we cache in redis, in rare cases this can cause a flaky test\n PostsHelper.clear_canonical_cache!(public_post)", " expect(body).not_to include(public_post.canonical_url)\n end", " it \"excludes small actions\" do\n small_action = Fabricate(:small_action)", " get \"/posts.rss\"", " expect(response.status).to eq(200)", " body = response.body", " expect(body).not_to include(small_action.canonical_url)\n end", " it 'returns public posts with topic for json' do\n topicless_post.update topic_id: -100", " public_post\n private_post\n topicless_post", " get \"/posts.json\"\n expect(response.status).to eq(200)", " json = response.parsed_body\n post_ids = json['latest_posts'].map { |p| p['id'] }", " expect(post_ids).to include public_post.id\n expect(post_ids).to_not include private_post.id\n expect(post_ids).to_not include topicless_post.id\n end\n end\n end", " describe '#cooked' do\n it 'returns the cooked content' do\n post = Fabricate(:post, cooked: \"WAt\")\n get \"/posts/#{post.id}/cooked.json\"", " expect(response.status).to eq(200)\n json = response.parsed_body", " expect(json).to be_present\n expect(json['cooked']).to eq('WAt')\n end\n end", " describe '#raw_email' do\n include_examples \"action requires login\", :get, \"/posts/2/raw-email.json\"", " describe \"when logged in\" do\n let(:post) { Fabricate(:post, deleted_at: 2.hours.ago, user: Fabricate(:user), raw_email: 'email_content') }", " it 'returns 403 when trying to view raw as user that created the post' do\n sign_in(post.user)", " get \"/posts/#{post.id}/raw-email.json\"\n expect(response.status).to eq(403)\n end", " it \"returns 403 when trying to view raw email as a normal user\" do\n sign_in(user)", " get \"/posts/#{post.id}/raw-email.json\"\n expect(response.status).to eq(403)\n end", " it \"can view raw email\" do\n sign_in(moderator)", " get \"/posts/#{post.id}/raw-email.json\"\n expect(response.status).to eq(200)", " json = response.parsed_body\n expect(json['raw_email']).to eq('email_content')\n end\n end\n end", " describe \"#locked\" do\n before do\n sign_in(moderator)\n end", " it 'can lock and unlock the post' do\n put \"/posts/#{public_post.id}/locked.json\", params: { locked: \"true\" }\n expect(response.status).to eq(200)\n public_post.reload\n expect(public_post).to be_locked", " put \"/posts/#{public_post.id}/locked.json\", params: { locked: \"false\" }\n expect(response.status).to eq(200)\n public_post.reload\n expect(public_post).not_to be_locked\n end\n end", " describe \"#notice\" do\n it 'can create and remove notices as a moderator' do\n sign_in(moderator)", " raw_notice = \"Hello *world*!\\n\\nhttps://github.com/discourse/discourse\"\n put \"/posts/#{public_post.id}/notice.json\", params: { notice: raw_notice }", " expect(response.status).to eq(200)\n expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(\"type\" => Post.notices[:custom], \"raw\" => raw_notice, \"cooked\" => PrettyText.cook(raw_notice, features: { onebox: false }))\n expect(UserHistory.where(action: UserHistory.actions[:post_staff_note_create]).count).to eq(1)", " put \"/posts/#{public_post.id}/notice.json\", params: { notice: nil }", " expect(response.status).to eq(200)\n expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(nil)\n expect(UserHistory.where(action: UserHistory.actions[:post_staff_note_destroy]).count).to eq(1)\n end", " describe 'group moderators' do\n fab!(:group_user) { Fabricate(:group_user) }\n let(:user) { group_user.user }\n let(:group) { group_user.group }", " before do\n SiteSetting.enable_category_group_moderation = true\n topic.category.update!(reviewable_by_group_id: group.id)", " sign_in(user)\n end", " it 'can create and remove notices as a group moderator' do\n raw_notice = \"Hello *world*!\\n\\nhttps://github.com/discourse/discourse\"\n put \"/posts/#{public_post.id}/notice.json\", params: { notice: raw_notice }", " expect(response.status).to eq(200)\n expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(\"type\" => Post.notices[:custom], \"raw\" => raw_notice, \"cooked\" => PrettyText.cook(raw_notice, features: { onebox: false }))", " put \"/posts/#{public_post.id}/notice.json\", params: { notice: nil }", " expect(response.status).to eq(200)\n expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(nil)\n end", " it 'prevents a group moderator from altering notes outside of their category' do\n moderatable_group = Fabricate(:group)\n topic.category.update!(reviewable_by_group_id: moderatable_group.id)", " put \"/posts/#{public_post.id}/notice.json\", params: { notice: \"Hello\" }", " expect(response.status).to eq(404)\n end", " it 'prevents a normal user from altering notes' do\n group_user.destroy!\n put \"/posts/#{public_post.id}/notice.json\", params: { notice: \"Hello\" }", " expect(response.status).to eq(404)\n end\n end\n end", " describe \"#pending\" do\n subject(:request) { get \"/posts/#{user.username}/pending.json\" }", " context \"when user is not logged in\" do\n it_behaves_like \"action requires login\", :get, \"/posts/system/pending.json\"\n end", " context \"when user is logged in\" do\n let(:pending_posts) { response.parsed_body[\"pending_posts\"] }", " before { sign_in(current_user) }", " context \"when current user is the same as user\" do\n let(:current_user) { user }", " context \"when there are existing pending posts\" do\n let!(:owner_pending_posts) { Fabricate.times(2, :reviewable_queued_post, created_by: user) }\n let!(:other_pending_post) { Fabricate(:reviewable_queued_post) }\n let(:expected_keys) do\n %w[\n avatar_template\n category_id\n created_at\n created_by_id\n name\n raw_text\n title\n topic_id\n topic_url\n username\n ]\n end", " it \"returns user's pending posts\" do\n request\n expect(pending_posts).to all include \"id\" => be_in(owner_pending_posts.map(&:id))\n expect(pending_posts).to all include(*expected_keys)\n end\n end", " context \"when there aren't any pending posts\" do\n it \"returns an empty array\" do\n request\n expect(pending_posts).to be_empty\n end\n end\n end", " context \"when current user is a staff member\" do\n let(:current_user) { moderator }", " context \"when there are existing pending posts\" do\n let!(:owner_pending_posts) { Fabricate.times(2, :reviewable_queued_post, created_by: user) }\n let!(:other_pending_post) { Fabricate(:reviewable_queued_post) }\n let(:expected_keys) do\n %w[\n avatar_template\n category_id\n created_at\n created_by_id\n name\n raw_text\n title\n topic_id\n topic_url\n username\n ]\n end", " it \"returns user's pending posts\" do\n request\n expect(pending_posts).to all include \"id\" => be_in(owner_pending_posts.map(&:id))\n expect(pending_posts).to all include(*expected_keys)\n end\n end", " context \"when there aren't any pending posts\" do\n it \"returns an empty array\" do\n request\n expect(pending_posts).to be_empty\n end\n end\n end", " context \"when current user is another user\" do\n let(:current_user) { Fabricate(:user) }", " it \"does not allow access\" do\n request\n expect(response).to have_http_status :not_found\n end\n end\n end\n end", " describe Plugin::Instance do\n describe '#add_permitted_post_create_param' do\n fab!(:user) { Fabricate(:user) }\n let(:instance) { Plugin::Instance.new }\n let(:request) do\n Proc.new {\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n composer_open_duration_msecs: 204,\n typing_duration_msecs: 100,\n reply_to_post_number: 123,\n string_arg: '123',\n hash_arg: { key1: 'val' },\n array_arg: ['1', '2', '3']\n }\n }\n end", " before do\n sign_in(user)\n SiteSetting.min_first_post_typing_time = 0\n end", " it 'allows strings to be added' do\n request.call\n expect(@controller.send(:create_params)).not_to include(string_arg: '123')", " instance.add_permitted_post_create_param(:string_arg)\n request.call\n expect(@controller.send(:create_params)).to include(string_arg: '123')\n end", " it 'allows hashes to be added' do\n instance.add_permitted_post_create_param(:hash_arg)\n request.call\n expect(@controller.send(:create_params)).not_to include(hash_arg: { key1: 'val' })", " instance.add_permitted_post_create_param(:hash_arg, :hash)\n request.call\n expect(@controller.send(:create_params)).to include(hash_arg: { key1: 'val' })\n end", " it 'allows strings to be added' do\n instance.add_permitted_post_create_param(:array_arg)\n request.call\n expect(@controller.send(:create_params)).not_to include(array_arg: ['1', '2', '3'])", " instance.add_permitted_post_create_param(:array_arg, :array)\n request.call\n expect(@controller.send(:create_params)).to include(array_arg: ['1', '2', '3'])\n end", " end\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
PreciseBugs
{"buggy_code_end_loc": [11, 1046], "buggy_code_start_loc": [5, 1046], "filenames": ["lib/validators/stripped_length_validator.rb", "spec/requests/posts_controller_spec.rb"], "fixing_code_end_loc": [15, 1061], "fixing_code_start_loc": [5, 1047], "message": "Discourse is an option source discussion platform. Prior to version 2.8.14 on the `stable` branch and version 2.9.0.beta16 on the `beta` and `tests-passed` branches, users can create posts with raw body longer than the `max_length` site setting by including html comments that are not counted toward the character limit. This issue is patched in versions 2.8.14 and 2.9.0.beta16. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:discourse:discourse:*:*:*:*:*:*:*:*", "matchCriteriaId": "9C13BCBA-EF34-4F4B-9F4A-33392EB45196", "versionEndExcluding": "2.8.14", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta1:*:*:*:*:*:*", "matchCriteriaId": "B3803EF9-A296-42B7-887F-93C5E68E94C4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta10:*:*:*:*:*:*", "matchCriteriaId": "35BAC488-3622-4B0B-B8EA-879E8C68E8CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta11:*:*:*:*:*:*", "matchCriteriaId": "406A23B4-B971-4DC8-A132-EE9854FE8546", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta12:*:*:*:*:*:*", "matchCriteriaId": "1DD3C47F-E49F-4E19-9EA7-A322C4CFD541", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta13:*:*:*:*:*:*", "matchCriteriaId": "E924AC08-6978-4DFF-B616-9E3E9D6FBE1B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta14:*:*:*:*:*:*", "matchCriteriaId": "B5A3C7FB-B3B6-45F0-AD7D-062A50490AD7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta2:*:*:*:*:*:*", "matchCriteriaId": "8BA3D313-3C11-43E2-A47D-CBB532D1B6F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta3:*:*:*:*:*:*", "matchCriteriaId": "6F42673E-65F3-4807-9484-20CB747420FB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta4:*:*:*:*:*:*", "matchCriteriaId": "0B91D023-FCE5-4866-AD8B-BBB675763104", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta5:*:*:*:*:*:*", "matchCriteriaId": "0086484D-0164-449C-8AAE-BE7479CB9706", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta6:*:*:*:*:*:*", "matchCriteriaId": "F9D1B031-96C7-44C0-A0A0-F67ABE55C93C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta7:*:*:*:*:*:*", "matchCriteriaId": "750D2AD9-35E7-4AC7-9C22-AA90DAA34F3F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta8:*:*:*:*:*:*", "matchCriteriaId": "B68E308A-BDAB-4614-A563-4460F7996CBE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:3.0.0:beta15:*:*:*:*:*:*", "matchCriteriaId": "F62275F8-11E9-4D94-8F2E-F83905F65031", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Discourse is an option source discussion platform. Prior to version 2.8.14 on the `stable` branch and version 2.9.0.beta16 on the `beta` and `tests-passed` branches, users can create posts with raw body longer than the `max_length` site setting by including html comments that are not counted toward the character limit. This issue is patched in versions 2.8.14 and 2.9.0.beta16. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23549", "lastModified": "2023-01-12T20:33:47.867", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-01-05T19:15:09.500", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/discourse/discourse/commit/bf6b08670a927cc80bb090b7a2e710b4b554e6a8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/discourse/discourse/security/advisories/GHSA-p47g-v5wr-p4xp"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-20"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/discourse/discourse/commit/bf6b08670a927cc80bb090b7a2e710b4b554e6a8"}, "type": "NVD-CWE-Other"}
232
Determine whether the {function_name} code is vulnerable or not.
[ "# frozen_string_literal: true", "RSpec.shared_examples 'finding and showing post' do\n let!(:post) { post_by_user }", " it \"ensures the user can't see the post\" do\n topic = post.topic\n topic.convert_to_private_message(Discourse.system_user)\n topic.remove_allowed_user(Discourse.system_user, user.username)\n get url\n expect(response).to be_forbidden\n end", " it 'succeeds' do\n get url\n expect(response.status).to eq(200)\n end", " it \"returns 404 when post's topic is deleted\" do\n post.topic.destroy!\n get url\n expect(response.status).to eq(404)\n end", " context \"with deleted post\" do\n before do\n post.trash!(user)\n end", " it \"can't find deleted posts as an anonymous user\" do\n get url\n expect(response.status).to eq(404)\n end", " it \"can't find deleted posts as a regular user\" do\n sign_in(user)\n get url\n expect(response.status).to eq(404)\n end", " it \"can find posts as a moderator\" do\n sign_in(moderator)\n get url\n expect(response.status).to eq(200)\n end", " it \"can find posts as a admin\" do\n sign_in(admin)\n get url\n expect(response.status).to eq(200)\n end", " context \"with category group moderator\" do\n fab!(:group_user) { Fabricate(:group_user) }\n let(:user_gm) { group_user.user }\n let(:group) { group_user.group }", " before do\n SiteSetting.enable_category_group_moderation = true\n sign_in(user_gm)\n end", " it \"can find posts in the allowed category\" do\n post.topic.category.update!(reviewable_by_group_id: group.id, topic_id: topic.id)\n get url\n expect(response.status).to eq(200)\n end", " it \"can't find posts outside of the allowed category\" do\n get url\n expect(response.status).to eq(404)\n end\n end\n end\nend", "RSpec.shared_examples 'action requires login' do |method, url, params = {}|\n it 'raises an exception when not logged in' do\n self.public_send(method, url, **params)\n expect(response.status).to eq(403)\n end\nend", "RSpec.describe PostsController do\n fab!(:admin) { Fabricate(:admin) }\n fab!(:moderator) { Fabricate(:moderator) }\n fab!(:user) { Fabricate(:user) }\n fab!(:user_trust_level_0) { Fabricate(:trust_level_0) }\n fab!(:user_trust_level_1) { Fabricate(:trust_level_1) }\n fab!(:category) { Fabricate(:category) }\n fab!(:topic) { Fabricate(:topic) }\n fab!(:post_by_user) { Fabricate(:post, user: user) }\n let(:public_post) { Fabricate(:post, user: user, topic: topic) }\n let(:topicless_post) { Fabricate(:post, user: user, raw: '<p>Car 54, where are you?</p>') }", " let(:private_topic) do\n Fabricate(:topic, archetype: Archetype.private_message, category_id: nil)\n end", " let(:private_post) { Fabricate(:post, user: user, topic: private_topic) }", " describe '#show' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/#{post.id}.json\" }\n end", " it 'gets all the expected fields' do\n # non fabricated test\n new_post = create_post", " get \"/posts/#{new_post.id}.json\"\n parsed = response.parsed_body", " expect(parsed[\"topic_slug\"]).to eq(new_post.topic.slug)\n expect(parsed[\"moderator\"]).to eq(false)\n expect(parsed[\"username\"]).to eq(new_post.user.username)\n expect(parsed[\"cooked\"]).to eq(new_post.cooked)\n end\n end", " describe '#by_number' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/by_number/#{post.topic_id}/#{post.post_number}.json\" }\n end\n end", " describe '#by_date' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/by-date/#{post.topic_id}/#{post.created_at.strftime(\"%Y-%m-%d\")}.json\" }\n end", " it 'returns the expected post' do\n first_post = Fabricate(:post, created_at: 10.days.ago)\n second_post = Fabricate(:post, topic: first_post.topic, created_at: 4.days.ago)\n _third_post = Fabricate(:post, topic: first_post.topic, created_at: 3.days.ago)", " get \"/posts/by-date/#{second_post.topic_id}/#{(second_post.created_at - 2.days).strftime(\"%Y-%m-%d\")}.json\"\n json = response.parsed_body", " expect(response.status).to eq(200)\n expect(json[\"id\"]).to eq(second_post.id)\n end", " it 'returns no post if date is > at last created post' do\n get \"/posts/by-date/#{post.topic_id}/2245-11-11.json\"\n _json = response.parsed_body\n expect(response.status).to eq(404)\n end\n end", " describe '#reply_history' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/#{post.id}/reply-history.json\" }\n end", " it \"returns the replies with allowlisted user custom fields\" do\n parent = Fabricate(:post)\n child = Fabricate(:post, topic: parent.topic, reply_to_post_number: parent.post_number)", " parent.user.upsert_custom_fields(hello: 'world', hidden: 'dontshow')\n SiteSetting.public_user_custom_fields = 'hello'", " get \"/posts/#{child.id}/reply-history.json\"\n expect(response.status).to eq(200)", " json = response.parsed_body\n expect(json[0]['id']).to eq(parent.id)\n expect(json[0]['user_custom_fields']['hello']).to eq('world')\n expect(json[0]['user_custom_fields']['hidden']).to be_blank\n end\n end", " describe '#reply_ids' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/#{post.id}/reply-ids.json\" }\n end", " it \"returns ids of post's replies\" do\n post = Fabricate(:post)\n reply1 = Fabricate(:post, topic: post.topic, reply_to_post_number: post.post_number)\n reply2 = Fabricate(:post, topic: post.topic, reply_to_post_number: post.post_number)\n PostReply.create(post_id: post.id, reply_post_id: reply1.id)\n PostReply.create(post_id: post.id, reply_post_id: reply2.id)", " get \"/posts/#{post.id}/reply-ids.json\"", " expect(response.status).to eq(200)\n expect(response.parsed_body).to eq([\n { \"id\" => reply1.id, \"level\" => 1 },\n { \"id\" => reply2.id, \"level\" => 1 },\n ])\n end\n end", " describe '#replies' do\n include_examples 'finding and showing post' do\n let(:url) { \"/posts/#{post.id}/replies.json\" }\n end", " it 'asks post for replies' do\n parent = Fabricate(:post)\n child = Fabricate(:post, topic: parent.topic, reply_to_post_number: parent.post_number)\n PostReply.create!(post: parent, reply: child)", " child.user.upsert_custom_fields(hello: 'world', hidden: 'dontshow')\n SiteSetting.public_user_custom_fields = 'hello'", " get \"/posts/#{parent.id}/replies.json\"\n expect(response.status).to eq(200)", " json = response.parsed_body\n expect(json[0]['id']).to eq(child.id)\n expect(json[0]['user_custom_fields']['hello']).to eq('world')\n expect(json[0]['user_custom_fields']['hidden']).to be_blank\n end\n end", " describe '#destroy' do\n include_examples 'action requires login', :delete, \"/posts/123.json\"", " describe 'when logged in' do\n let(:topic) { Fabricate(:topic) }", " it \"raises an error when the user doesn't have permission to see the post\" do\n pm = Fabricate(:private_message_topic)\n post = Fabricate(:post, topic: pm, post_number: 3)", " sign_in(user)", " delete \"/posts/#{post.id}.json\"\n expect(response).to be_forbidden\n end", " it \"raises an error when the self deletions are disabled\" do\n SiteSetting.max_post_deletions_per_day = 0\n post = Fabricate(:post, user: user, topic: topic, post_number: 3)\n sign_in(user)", " delete \"/posts/#{post.id}.json\"\n expect(response).to be_forbidden\n end", " it \"uses a PostDestroyer\" do\n post = Fabricate(:post, topic_id: topic.id, post_number: 3)\n sign_in(moderator)", " destroyer = mock\n PostDestroyer.expects(:new).returns(destroyer)\n destroyer.expects(:destroy)", " delete \"/posts/#{post.id}.json\"\n end", " context \"with permanently destroy\" do\n let!(:post) { Fabricate(:post, topic_id: topic.id, post_number: 3) }", " before do\n SiteSetting.can_permanently_delete = true\n end", " it \"does not work for a post that was not deleted yet\" do\n sign_in(admin)", " delete \"/posts/#{post.id}.json\", params: { force_destroy: true }\n expect(response.status).to eq(403)\n end", " it \"needs some time to pass to permanently delete a topic\" do\n sign_in(admin)", " delete \"/posts/#{post.id}.json\"\n expect(response.status).to eq(200)\n expect(post.reload.deleted_by_id).to eq(admin.id)", " delete \"/posts/#{post.id}.json\", params: { force_destroy: true }\n expect(response.status).to eq(403)", " post.update!(deleted_at: 10.minutes.ago)", " delete \"/posts/#{post.id}.json\", params: { force_destroy: true }\n expect(response.status).to eq(200)\n expect { post.reload }.to raise_error(ActiveRecord::RecordNotFound)\n end", " it \"needs two users to permanently delete a topic\" do\n sign_in(admin)", " delete \"/posts/#{post.id}.json\"\n expect(response.status).to eq(200)\n expect(post.reload.deleted_by_id).to eq(admin.id)", " sign_in(Fabricate(:admin))", " delete \"/posts/#{post.id}.json\", params: { force_destroy: true }\n expect(response.status).to eq(200)\n expect { post.reload }.to raise_error(ActiveRecord::RecordNotFound)\n end", " it \"moderators cannot permanently delete topics\" do\n sign_in(admin)", " delete \"/posts/#{post.id}.json\"\n expect(response.status).to eq(200)\n expect(post.reload.deleted_by_id).to eq(admin.id)", " sign_in(moderator)", " delete \"/posts/#{post.id}.json\", params: { force_destroy: true }\n expect(response.status).to eq(403)\n end\n end\n end\n end", " describe '#destroy_many' do\n include_examples 'action requires login', :delete, \"/posts/destroy_many.json\", params: { post_ids: [123, 345] }", " describe 'when logged in' do\n fab!(:poster) { Fabricate(:moderator) }\n fab!(:post1) { Fabricate(:post, user: poster, post_number: 2) }\n fab!(:post2) { Fabricate(:post, topic: post1.topic, user: poster, post_number: 3, reply_to_post_number: post1.post_number) }", " it \"raises invalid parameters no post_ids\" do\n sign_in(poster)\n delete \"/posts/destroy_many.json\"\n expect(response.status).to eq(400)\n expect(response.message.downcase).to eq(\"bad request\")\n end", " it \"raises invalid parameters with missing ids\" do\n sign_in(poster)\n delete \"/posts/destroy_many.json\", params: { post_ids: [12345] }\n expect(response.status).to eq(400)\n end", " it \"raises an error when the user doesn't have permission to delete the posts\" do\n sign_in(user)\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id, post2.id] }\n expect(response).to be_forbidden\n end", " it \"deletes the post\" do\n sign_in(poster)\n PostDestroyer.any_instance.expects(:destroy).twice\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id, post2.id] }\n expect(response.status).to eq(200)\n end", " it \"updates the highest read data for the forum\" do\n sign_in(poster)\n Topic.expects(:reset_highest).twice\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id, post2.id] }\n end", " describe \"can delete replies\" do\n before do\n PostReply.create(post_id: post1.id, reply_post_id: post2.id)\n end", " it \"deletes the post and the reply to it\" do\n sign_in(poster)\n PostDestroyer.any_instance.expects(:destroy).twice\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id], reply_post_ids: [post1.id] }\n end\n end", " context \"when deleting flagged posts\" do\n before do\n sign_in(moderator)\n PostActionCreator.off_topic(moderator, post1)\n PostActionCreator.off_topic(moderator, post2)\n Jobs::SendSystemMessage.clear\n end", " it \"defers the child posts by default\" do\n expect(ReviewableFlaggedPost.pending.count).to eq(2)\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id, post2.id] }\n expect(Jobs::SendSystemMessage.jobs.size).to eq(1)\n expect(ReviewableFlaggedPost.pending.count).to eq(0)\n end", " it \"can defer all posts based on `agree_with_first_reply_flag` param\" do\n expect(ReviewableFlaggedPost.pending.count).to eq(2)\n delete \"/posts/destroy_many.json\", params: { post_ids: [post1.id, post2.id], agree_with_first_reply_flag: false }\n PostActionCreator.off_topic(moderator, post1)\n PostActionCreator.off_topic(moderator, post2)\n Jobs::SendSystemMessage.clear\n end\n end\n end\n end", " describe '#recover' do\n include_examples 'action requires login', :put, \"/posts/123/recover.json\"", " describe 'when logged in' do\n it \"raises an error when the user doesn't have permission to see the post\" do\n post = Fabricate(:post, topic: Fabricate(:private_message_topic), post_number: 3)\n sign_in(user)", " put \"/posts/#{post.id}/recover.json\"\n expect(response).to be_forbidden\n end", " it \"raises an error when self deletion/recovery is disabled\" do\n SiteSetting.max_post_deletions_per_day = 0\n post = Fabricate(:post, user: user, topic: topic, post_number: 3)\n sign_in(user)", " put \"/posts/#{post.id}/recover.json\"\n expect(response).to be_forbidden\n end", " it \"recovers a post correctly\" do\n topic_id = create_post.topic_id\n post = create_post(topic_id: topic_id)\n sign_in(user)", " PostDestroyer.new(user, post).destroy\n put \"/posts/#{post.id}/recover.json\"\n post.reload\n expect(post.trashed?).to be_falsey\n end\n end\n end", " describe '#update' do\n include_examples 'action requires login', :put, \"/posts/2.json\"", " let!(:post) { post_by_user }\n let(:update_params) do\n {\n post: { raw: 'edited body', edit_reason: 'typo' },\n image_sizes: { 'http://image.com/image.jpg' => { 'width' => 123, 'height' => 456 } },\n }\n end", " describe 'when logged in as a regular user' do\n before do\n sign_in(user)\n end", " it 'does not allow TL0 or TL1 to update when edit time limit expired' do\n SiteSetting.post_edit_time_limit = 5\n SiteSetting.tl2_post_edit_time_limit = 30", " post = Fabricate(:post, created_at: 10.minutes.ago, user: user)", " user.update_columns(trust_level: 1)", " put \"/posts/#{post.id}.json\", params: update_params", " expect(response.status).to eq(422)\n expect(response.parsed_body['errors']).to include(I18n.t('too_late_to_edit'))\n end", " it 'does not allow TL2 to update when edit time limit expired' do\n SiteSetting.post_edit_time_limit = 12\n SiteSetting.tl2_post_edit_time_limit = 8", " user.update_columns(trust_level: 2)", " post = Fabricate(:post, created_at: 10.minutes.ago, user: user)", " put \"/posts/#{post.id}.json\", params: update_params", " expect(response.status).to eq(422)\n expect(response.parsed_body['errors']).to include(I18n.t('too_late_to_edit'))\n end", " it 'passes the image sizes through' do\n Post.any_instance.expects(:image_sizes=)\n put \"/posts/#{post.id}.json\", params: update_params\n end", " it 'passes the edit reason through' do\n put \"/posts/#{post.id}.json\", params: update_params\n expect(response.status).to eq(200)\n post.reload\n expect(post.edit_reason).to eq(\"typo\")\n expect(post.raw).to eq(\"edited body\")\n end", " it 'checks for an edit conflict' do\n update_params[:post][:raw_old] = 'old body'\n put \"/posts/#{post.id}.json\", params: update_params", " expect(response.status).to eq(409)\n end", " it \"raises an error when the post parameter is missing\" do\n update_params.delete(:post)\n put \"/posts/#{post.id}.json\", params: update_params\n expect(response.status).to eq(400)\n expect(response.message.downcase).to eq(\"bad request\")\n end", " it \"raises an error when the user doesn't have permission to see the post\" do\n post = Fabricate(:private_message_post, post_number: 3)\n put \"/posts/#{post.id}.json\", params: update_params\n expect(response).to be_forbidden\n end", " it \"updates post's raw attribute\" do\n put \"/posts/#{post.id}.json\", params: { post: { raw: 'edited body ' } }", " expect(response.status).to eq(200)\n expect(response.parsed_body['post']['raw']).to eq('edited body')\n expect(post.reload.raw).to eq('edited body')\n end", " it \"extracts links from the new body\" do\n param = update_params\n param[:post][:raw] = 'I just visited this https://google.com so many cool links'", " put \"/posts/#{post.id}.json\", params: param", " expect(response.status).to eq(200)\n expect(TopicLink.count).to eq(1)\n end", " it \"doesn't allow updating of deleted posts\" do\n first_post = post.topic.ordered_posts.first\n PostDestroyer.new(moderator, first_post).destroy", " put \"/posts/#{first_post.id}.json\", params: update_params\n expect(response).not_to be_successful\n end\n end", " describe \"when logged in as staff\" do\n before do\n sign_in(moderator)\n end", " it \"supports updating posts in deleted topics\" do\n first_post = post.topic.ordered_posts.first\n PostDestroyer.new(moderator, first_post).destroy", " put \"/posts/#{first_post.id}.json\", params: update_params\n expect(response.status).to eq(200)", " post.reload\n expect(post.raw).to eq('edited body')\n end", " it \"won't update bump date if post is a whisper\" do\n created_at = freeze_time 1.day.ago\n post = Fabricate(:post, post_type: Post.types[:whisper], user: user)", " unfreeze_time\n put \"/posts/#{post.id}.json\", params: update_params", " expect(response.status).to eq(200)\n expect(post.topic.reload.bumped_at).to eq_time(created_at)\n end\n end", " describe \"when logged in as group moderator\" do\n fab!(:topic) { Fabricate(:topic, category: category) }\n fab!(:post) { Fabricate(:post, user: user, topic: topic) }\n fab!(:group_user) { Fabricate(:group_user) }\n let(:user_gm) { group_user.user }\n let(:group) { group_user.group }", " before do\n SiteSetting.enable_category_group_moderation = true\n post.topic.category.update!(reviewable_by_group_id: group.id, topic_id: topic.id)\n sign_in(user_gm)\n end", " it \"allows updating the category description\" do\n put \"/posts/#{post.id}.json\", params: update_params\n expect(response.status).to eq(200)", " post.reload\n expect(post.raw).to eq('edited body')\n expect(UserHistory.where(action: UserHistory.actions[:post_edit]).count).to eq(1)\n end", " it \"can not update category descriptions in other categories\" do\n second_category = Fabricate(:category)\n topic.update!(category: second_category)", " put \"/posts/#{post.id}.json\", params: update_params\n expect(response.status).to eq(403)\n end", " end", " it 'can not change category to a disallowed category' do\n post = create_post\n sign_in(post.user)", " category = Fabricate(:category)\n category.set_permissions(staff: :full)\n category.save!", " put \"/posts/#{post.id}.json\", params: {\n post: { category_id: category.id, raw: \"this is a test edit to post\" }\n }", " expect(response.status).not_to eq(200)\n expect(post.topic.category_id).not_to eq(category.id)\n end", " it 'can not move to a category that requires topic approval' do\n post = create_post\n sign_in(post.user)", " category = Fabricate(:category)\n category.custom_fields[Category::REQUIRE_TOPIC_APPROVAL] = true\n category.save!", " put \"/posts/#{post.id}.json\", params: { post: { category_id: category.id, raw: \"this is a test edit to post\" } }", " expect(response.status).to eq(403)\n expect(post.topic.reload.category_id).not_to eq(category.id)\n end", " describe \"with Post.plugin_permitted_update_params\" do\n before do\n plugin = Plugin::Instance.new\n plugin.add_permitted_post_update_param(:random_number) do |post, value|\n post.custom_fields[:random_number] = value\n post.save\n end\n end", " after do\n DiscoursePluginRegistry.reset!\n end", " it \"calls blocks passed into `add_permitted_post_update_param`\" do\n sign_in(post.user)\n put \"/posts/#{post.id}.json\", params: {\n post: {\n raw: \"this is a random post\",\n raw_old: post.raw,\n random_number: 244\n }\n }", " expect(response.status).to eq(200)\n expect(post.reload.custom_fields[:random_number]).to eq(\"244\")\n end\n end\n end", " describe \"#destroy_bookmark\" do\n fab!(:post) { Fabricate(:post) }\n fab!(:bookmark) { Fabricate(:bookmark, user: user, bookmarkable: post) }", " before do\n sign_in(user)\n end", " it \"deletes the bookmark\" do\n bookmark_id = bookmark.id\n delete \"/posts/#{post.id}/bookmark.json\"\n expect(Bookmark.find_by(id: bookmark_id)).to eq(nil)\n end", " context \"when the user still has bookmarks in the topic\" do\n before do\n Fabricate(:bookmark, user: user, bookmarkable: Fabricate(:post, topic: post.topic))\n end\n it \"marks topic_bookmarked as true\" do\n delete \"/posts/#{post.id}/bookmark.json\"\n expect(response.parsed_body['topic_bookmarked']).to eq(true)\n end\n end\n end", " describe '#wiki' do\n include_examples \"action requires login\", :put, \"/posts/2/wiki.json\"", " describe \"when logged in\" do\n before do\n sign_in(user)\n end", " let!(:post) { post_by_user }", " it \"returns 400 when wiki parameter is not present\" do\n sign_in(admin)", " put \"/posts/#{post.id}/wiki.json\", params: {}", " expect(response.status).to eq(400)\n end", " it \"raises an error if the user doesn't have permission to wiki the post\" do\n put \"/posts/#{post.id}/wiki.json\", params: { wiki: 'true' }\n expect(response).to be_forbidden\n end", " it \"toggle wiki status should create a new version\" do\n sign_in(admin)\n another_user = Fabricate(:user)\n another_post = Fabricate(:post, user: another_user)", " expect do\n put \"/posts/#{another_post.id}/wiki.json\", params: { wiki: 'true' }\n end.to change { another_post.reload.version }.by(1)", " expect do\n put \"/posts/#{another_post.id}/wiki.json\", params: { wiki: 'false' }\n end.to change { another_post.reload.version }.by(-1)", " sign_in(Fabricate(:admin))", " expect do\n put \"/posts/#{another_post.id}/wiki.json\", params: { wiki: 'true' }\n end.to change { another_post.reload.version }.by(1)\n end", " it \"can wiki a post\" do\n sign_in(admin)\n put \"/posts/#{post.id}/wiki.json\", params: { wiki: 'true' }", " post.reload\n expect(post.wiki).to eq(true)\n end", " it \"can unwiki a post\" do\n wikied_post = Fabricate(:post, user: user, wiki: true)\n sign_in(admin)", " put \"/posts/#{wikied_post.id}/wiki.json\", params: { wiki: 'false' }", " wikied_post.reload\n expect(wikied_post.wiki).to eq(false)\n end\n end\n end", " describe '#post_type' do\n include_examples \"action requires login\", :put, \"/posts/2/post_type.json\"", " describe \"when logged in\" do\n before do\n sign_in(moderator)\n end", " let!(:post) { post_by_user }", " it \"raises an error if the user doesn't have permission to change the post type\" do\n sign_in(user)", " put \"/posts/#{post.id}/post_type.json\", params: { post_type: 2 }\n expect(response).to be_forbidden\n end", " it \"returns 400 if post_type parameter is not present\" do\n put \"/posts/#{post.id}/post_type.json\", params: {}", " expect(response.status).to eq(400)\n end", " it \"returns 400 if post_type parameters is invalid\" do\n put \"/posts/#{post.id}/post_type.json\", params: { post_type: -1 }", " expect(response.status).to eq(400)\n end", " it \"can change the post type\" do\n put \"/posts/#{post.id}/post_type.json\", params: { post_type: 2 }", " post.reload\n expect(post.post_type).to eq(2)\n end\n end\n end", " describe '#rebake' do\n include_examples \"action requires login\", :put, \"/posts/2/rebake.json\"", " describe \"when logged in\" do\n let!(:post) { post_by_user }", " it \"raises an error if the user doesn't have permission to rebake the post\" do\n sign_in(user)\n put \"/posts/#{post.id}/rebake.json\"\n expect(response).to be_forbidden\n end", " it \"can rebake the post\" do\n sign_in(moderator)\n put \"/posts/#{post.id}/rebake.json\"\n expect(response.status).to eq(200)\n end", " it \"will invalidate broken images cache\" do\n sign_in(moderator)\n PostHotlinkedMedia.create!(url: \"https://example.com/image.jpg\", post: post, status: 'download_failed')\n put \"/posts/#{post.id}/rebake.json\"\n post.reload\n expect(post.post_hotlinked_media).to eq([])\n end\n end\n end", " describe '#create' do\n include_examples 'action requires login', :post, \"/posts.json\"", " before do\n SiteSetting.min_first_post_typing_time = 0\n SiteSetting.whispers_allowed_groups = \"#{Group::AUTO_GROUPS[:staff]}\"\n end", " context 'with api' do\n it 'memoizes duplicate requests' do\n raw = \"this is a test post 123 #{SecureRandom.hash}\"\n title = \"this is a title #{SecureRandom.hash}\"", " master_key = Fabricate(:api_key).key", " post \"/posts.json\",\n params: { raw: raw, title: title, wpid: 1 },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)\n original = response.body", " post \"/posts.json\",\n params: { raw: raw, title: title, wpid: 2 },\n headers: { HTTP_API_USERNAME: user.username_lower, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)\n expect(response.body).to eq(original)\n end", " it 'allows to create posts in import_mode' do\n Jobs.run_immediately!\n NotificationEmailer.enable\n post_1 = Fabricate(:post)\n master_key = Fabricate(:api_key).key", " post \"/posts.json\",\n params: { raw: 'this is test reply 1', topic_id: post_1.topic.id, reply_to_post_number: 1 },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)\n expect(post_1.topic.user.notifications.count).to eq(1)\n post_1.topic.user.notifications.destroy_all", " post \"/posts.json\",\n params: { raw: 'this is test reply 2', topic_id: post_1.topic.id, reply_to_post_number: 1, import_mode: true },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)\n expect(post_1.topic.user.notifications.count).to eq(0)", " post \"/posts.json\",\n params: { raw: 'this is test reply 3', topic_id: post_1.topic.id, reply_to_post_number: 1, import_mode: false },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)\n expect(post_1.topic.user.notifications.count).to eq(1)\n end", " it 'allows a topic to be created with an external_id' do\n master_key = Fabricate(:api_key).key\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: \"this is some post\",\n external_id: 'external_id'\n }, headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(200)", " new_topic = Topic.last", " expect(new_topic.external_id).to eq('external_id')\n end", " it 'prevents whispers for regular users' do\n post_1 = Fabricate(:post)\n user_key = ApiKey.create!(user: user).key", " post \"/posts.json\",\n params: { raw: 'this is test whisper', topic_id: post_1.topic.id, reply_to_post_number: 1, whisper: true },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: user_key }", " expect(response.status).to eq(403)\n end", " it 'does not advance draft' do\n Draft.set(user, Draft::NEW_TOPIC, 0, \"test\")\n user_key = ApiKey.create!(user: user).key", " post \"/posts.json\",\n params: { title: 'this is a test topic', raw: 'this is test whisper' },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: user_key }", " expect(response.status).to eq(200)\n expect(Draft.get(user, Draft::NEW_TOPIC, 0)).to eq(\"test\")\n end", " it 'will raise an error if specified category cannot be found' do\n user = Fabricate(:admin)\n master_key = Fabricate(:api_key).key", " post \"/posts.json\",\n params: { title: 'this is a test title', raw: 'this is test body', category: 'invalid' },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(400)", " expect(response.parsed_body[\"errors\"]).to include(\n I18n.t(\"invalid_params\", message: \"category\")\n )\n end", " it 'will raise an error if specified embed_url is invalid' do\n user = Fabricate(:admin)\n master_key = Fabricate(:api_key).key", " post \"/posts.json\",\n params: { title: 'this is a test title', raw: 'this is test body', embed_url: '/test.txt' },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: master_key }", " expect(response.status).to eq(422)\n end", " it \"creates unlisted topic with admin master key\" do\n master_key = Fabricate(:api_key).key", " expect do\n post \"/posts.json\",\n params: { raw: \"this is a test title\", title: \"this is test body\", unlist_topic: true },\n headers: { HTTP_API_USERNAME: admin.username, HTTP_API_KEY: master_key }\n end.to change { Topic.count }.by(1)", " expect(response.status).to eq(200)\n expect(Topic.find(response.parsed_body[\"topic_id\"]).visible).to eq(false)\n end", " it \"prevents creation of unlisted topic with non-admin key\" do\n user_key = ApiKey.create!(user: user).key", " expect do\n post \"/posts.json\",\n params: { raw: \"this is a test title\", title: \"this is test body\", unlist_topic: true },\n headers: { HTTP_API_USERNAME: user.username, HTTP_API_KEY: user_key }\n end.not_to change { Topic.count }", " expect(response.status).to eq(422)\n expect(response.parsed_body[\"errors\"]).to include(\n I18n.t(\"activerecord.errors.models.topic.attributes.base.unable_to_unlist\")\n )\n end\n end", " describe \"when logged in\" do\n fab!(:user) { Fabricate(:user) }", " before do\n sign_in(user)\n end", " context \"when fast typing\" do\n before do\n SiteSetting.min_first_post_typing_time = 3000\n SiteSetting.auto_silence_fast_typers_max_trust_level = 1\n end", " it 'queues the post if min_first_post_typing_time is not met' do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n composer_open_duration_msecs: 204,\n typing_duration_msecs: 100,\n reply_to_post_number: 123\n }", " expect(response.status).to eq(200)\n parsed = response.parsed_body", " expect(parsed[\"action\"]).to eq(\"enqueued\")", " user.reload\n expect(user).to be_silenced", " rp = ReviewableQueuedPost.find_by(created_by: user)\n expect(rp.payload['typing_duration_msecs']).to eq(100)\n expect(rp.payload['composer_open_duration_msecs']).to eq(204)\n expect(rp.payload['reply_to_post_number']).to eq(123)\n expect(rp.reviewable_scores.first.reason).to eq('fast_typer')", " expect(parsed['pending_post']).to be_present\n expect(parsed['pending_post']['id']).to eq(rp.id)\n expect(parsed['pending_post']['raw']).to eq(\"this is the test content\")", " mod = moderator\n rp.perform(mod, :approve_post)", " user.reload\n expect(user).not_to be_silenced\n end", " it \"doesn't enqueue posts when user first creates a topic\" do\n topic = Fabricate(:post, user: user).topic", " Draft.set(user, \"should_clear\", 0, \"{'a' : 'b'}\")", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n composer_open_duration_msecs: 204,\n typing_duration_msecs: 100,\n topic_id: topic.id,\n draft_key: \"should_clear\"\n }", " expect(response.status).to eq(200)\n parsed = response.parsed_body", " expect(parsed[\"action\"]).not_to be_present", " expect {\n Draft.get(user, \"should_clear\", 0)\n }.to raise_error(Draft::OutOfSequence)\n end", " it \"doesn't enqueue replies when the topic is closed\" do\n topic = Fabricate(:closed_topic)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n topic_id: topic.id\n }", " expect(response).not_to be_successful\n parsed = response.parsed_body\n expect(parsed[\"action\"]).not_to eq(\"enqueued\")\n end", " it \"doesn't enqueue replies when the post is too long\" do\n SiteSetting.max_post_length = 10", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic'", " }", " expect(response).not_to be_successful\n parsed = response.parsed_body\n expect(parsed[\"action\"]).not_to eq(\"enqueued\")\n end", " it \"doesn't enqueue replies when the post is too long (including a html comment)\" do\n SiteSetting.max_post_length = 10\n raw = \"A post <!-- \" + (\"a\" * 3000) + \"-->\"", " post \"/posts.json\", params: {\n raw: raw,\n title: \"this is the test title for the topic\"", " }", " expect(response).not_to be_successful\n parsed = response.parsed_body\n expect(parsed[\"action\"]).not_to eq(\"enqueued\")\n end\n end", " it 'silences correctly based on auto_silence_first_post_regex' do\n SiteSetting.auto_silence_first_post_regex = \"I love candy|i eat s[1-5]\"", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'when I eat s3 sometimes when not looking'\n }", " expect(response.status).to eq(200)\n parsed = response.parsed_body", " expect(parsed[\"action\"]).to eq(\"enqueued\")\n reviewable = ReviewableQueuedPost.find_by(created_by: user)\n score = reviewable.reviewable_scores.first\n expect(score.reason).to eq('auto_silence_regex')", " user.reload\n expect(user).to be_silenced\n end", " it 'silences correctly based on silence watched words' do\n SiteSetting.watched_words_regular_expressions = true\n WatchedWord.create!(action: WatchedWord.actions[:silence], word: 'I love candy')\n WatchedWord.create!(action: WatchedWord.actions[:silence], word: 'i eat s[1-5]')", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'when I eat s3 sometimes when not looking'\n }", " expect(response.status).to eq(200)\n parsed = response.parsed_body", " expect(parsed[\"action\"]).to eq(\"enqueued\")\n reviewable = ReviewableQueuedPost.find_by(created_by: user)\n score = reviewable.reviewable_scores.first\n expect(score.reason).to eq('auto_silence_regex')", " user.reload\n expect(user).to be_silenced\n end", " it \"can send a message to a group\" do\n Group.refresh_automatic_groups!\n group = Group.create(name: 'test_group', messageable_level: Group::ALIAS_LEVELS[:nobody])\n user1 = user\n group.add(user1)", " post \"/posts.json\", params: {\n raw: 'I can haz a test',\n title: 'I loves my test',\n target_recipients: group.name,\n archetype: Archetype.private_message\n }", " expect(response).not_to be_successful", " # allow pm to this group\n group.update_columns(messageable_level: Group::ALIAS_LEVELS[:everyone])", " post \"/posts.json\", params: {\n raw: 'I can haz a test',\n title: 'I loves my test',\n target_recipients: \"test_Group\",\n archetype: Archetype.private_message\n }", " expect(response.status).to eq(200)", " parsed = response.parsed_body\n post = Post.find(parsed['id'])", " expect(post.topic.topic_allowed_users.length).to eq(1)\n expect(post.topic.topic_allowed_groups.length).to eq(1)\n end", " it \"can send a message to a group with caps\" do\n Group.refresh_automatic_groups!\n group = Group.create(name: 'Test_group', messageable_level: Group::ALIAS_LEVELS[:nobody])\n user1 = user\n group.add(user1)", " # allow pm to this group\n group.update_columns(messageable_level: Group::ALIAS_LEVELS[:everyone])", " post \"/posts.json\", params: {\n raw: 'I can haz a test',\n title: 'I loves my test',\n target_recipients: \"test_Group\",\n archetype: Archetype.private_message\n }", " expect(response.status).to eq(200)", " parsed = response.parsed_body\n post = Post.find(parsed['id'])", " expect(post.topic.topic_allowed_users.length).to eq(1)\n expect(post.topic.topic_allowed_groups.length).to eq(1)\n end", " it \"returns the nested post with a param\" do\n post \"/posts.json\", params: {\n raw: 'this is the test content ',\n title: 'this is the test title for the topic',\n nested_post: true\n }", " expect(response.status).to eq(200)\n parsed = response.parsed_body\n expect(parsed['post']).to be_present\n expect(parsed['post']['raw']).to eq('this is the test content')\n expect(parsed['post']['cooked']).to be_present\n end", " it 'protects against dupes' do\n raw = \"this is a test post 123 #{SecureRandom.hash}\"\n title = \"this is a title #{SecureRandom.hash}\"", " expect do\n post \"/posts.json\", params: { raw: raw, title: title, wpid: 1 }\n end.to change { Post.count }", " expect(response.status).to eq(200)", " expect do\n post \"/posts.json\", params: { raw: raw, title: title, wpid: 2 }\n end.to_not change { Post.count }", " expect(response.status).to eq(422)\n end", " it 'cannot create a post in a disallowed category' do\n category.set_permissions(staff: :full)\n category.save!", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n category: category.id,\n meta_data: { xyz: 'abc' }\n }", " expect(response.status).to eq(403)\n end", " it 'cannot create a post with a tag that is restricted' do\n SiteSetting.tagging_enabled = true\n tag = Fabricate(:tag)\n category.allowed_tags = [tag.name]\n category.save!", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n tags: [tag.name],\n }", " expect(response.status).to eq(422)\n json = response.parsed_body\n expect(json['errors']).to be_present\n end", " it 'cannot create a post with a tag when tagging is disabled' do\n SiteSetting.tagging_enabled = false\n tag = Fabricate(:tag)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n tags: [tag.name],\n }", " expect(response.status).to eq(422)\n json = response.parsed_body\n expect(json['errors']).to be_present\n end", " it 'cannot create a post with a tag without tagging permission' do\n SiteSetting.tagging_enabled = true\n SiteSetting.min_trust_level_to_tag_topics = 4\n tag = Fabricate(:tag)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n tags: [tag.name],\n }", " expect(response.status).to eq(422)\n json = response.parsed_body\n expect(json['errors']).to be_present\n end", " it 'can create a post with a tag when tagging is enabled' do\n SiteSetting.tagging_enabled = true\n tag = Fabricate(:tag)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n tags: [tag.name],\n }", " expect(response.status).to eq(200)\n expect(Post.last.topic.tags.count).to eq(1)\n end", " it 'creates the post' do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n category: category.id,\n meta_data: { xyz: 'abc' }\n }", " expect(response.status).to eq(200)", " new_post = Post.last\n topic = new_post.topic", " expect(new_post.user).to eq(user)\n expect(new_post.raw).to eq('this is the test content')\n expect(topic.title).to eq('This is the test title for the topic')\n expect(topic.category).to eq(category)\n expect(topic.meta_data).to eq(\"xyz\" => 'abc')\n expect(topic.visible).to eq(true)\n end", " it 'can create an uncategorized topic' do\n title = 'this is the test title for the topic'", " expect do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: title,\n category: \"\"\n }", " expect(response.status).to eq(200)\n end.to change { Topic.count }.by(1)", " topic = Topic.last", " expect(topic.title).to eq(title.capitalize)\n expect(topic.category_id).to eq(SiteSetting.uncategorized_category_id)\n end", " it 'can create a reply to a post' do\n topic = Fabricate(:private_message_post, user: user).topic\n post_2 = Fabricate(:private_message_post, user: user, topic: topic)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n topic_id: topic.id,\n reply_to_post_number: post_2.post_number,\n image_sizes: { width: '100', height: '200' }\n }", " expect(response.status).to eq(200)", " new_post = Post.last\n topic = new_post.topic", " expect(new_post.user).to eq(user)\n expect(new_post.raw).to eq('this is the test content')\n expect(new_post.reply_to_post_number).to eq(post_2.post_number)", " job_args = Jobs::ProcessPost.jobs.first[\"args\"].first", " expect(job_args[\"image_sizes\"]).to eq(\"width\" => '100', \"height\" => '200')\n end", " it 'creates a private post' do\n user_2 = Fabricate(:user)\n user_3 = Fabricate(:user, username: \"foo_bar\")", " # In certain edge cases, it's possible to end up with a username\n # containing characters that would normally fail to validate\n user_4 = Fabricate(:user, username: \"Iyi_Iyi\")\n user_4.update_attribute(:username, \"İyi_İyi\")\n user_4.update_attribute(:username_lower, \"İyi_İyi\".downcase)\n Group.refresh_automatic_groups!", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: \"#{user_2.username},Foo_Bar,İyi_İyi\"\n }", " expect(response.status).to eq(200)", " new_post = Post.last\n new_topic = Topic.last", " expect(new_post.user).to eq(user)\n expect(new_topic.private_message?).to eq(true)\n expect(new_topic.allowed_users).to contain_exactly(user, user_2, user_3, user_4)\n end", " context \"when target_recipients not provided\" do\n it \"errors when creating a private post\" do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: \"\"\n }", " expect(response.status).to eq(422)\n expect(response.parsed_body[\"errors\"]).to include(\n I18n.t(\"activerecord.errors.models.topic.attributes.base.no_user_selected\")\n )\n end\n end", " context \"when topic_id is set\" do\n fab!(:topic) { Fabricate(:topic) }", " it \"errors when creating a private post\" do\n user_2 = Fabricate(:user)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: user_2.username,\n topic_id: topic.id\n }", " expect(response.status).to eq(422)\n expect(response.parsed_body[\"errors\"]).to include(\n I18n.t(\"create_pm_on_existing_topic\")\n )\n end\n end", " context \"with errors\" do\n it \"does not succeed\" do\n post \"/posts.json\", params: { raw: 'test' }\n expect(response).not_to be_successful\n expect(response.status).to eq(422)\n end", " it \"it triggers flag_linked_posts_as_spam when the post creator returns spam\" do\n SiteSetting.newuser_spam_host_threshold = 1\n sign_in(Fabricate(:user, trust_level: 0))", " post \"/posts.json\", params: {\n raw: 'this is the test content http://fakespamwebsite.com http://fakespamwebsite.com/spam http://fakespamwebsite.com/spammy',\n title: 'this is the test title for the topic',\n meta_data: { xyz: 'abc' }\n }", " expect(response.parsed_body[\"errors\"]).to include(I18n.t(:spamming_host))\n end", " context \"when allow_uncategorized_topics is false\" do\n before do\n SiteSetting.allow_uncategorized_topics = false\n end", " it \"cant create an uncategorized post\" do\n post \"/posts.json\", params: {\n raw: \"a new post with no category\",\n title: \"a new post with no category\"\n }\n expect(response).not_to be_successful\n end", " context \"as staff\" do\n before do\n sign_in(admin)\n end", " it \"cant create an uncategorized post\" do\n post \"/posts.json\", params: {\n raw: \"a new post with no category\",\n title: \"a new post with no category\"\n }\n expect(response).not_to be_successful\n end\n end\n end\n end", " context \"with mentions\" do\n fab!(:user_to_mention) { Fabricate(:user) }", " it \"returns mentioned users\" do\n post \"/posts.json\", params: {\n raw: \"I am mentioning @#{user_to_mention.username}\",\n topic_id: topic.id,\n }", " expect(response.status).to eq(200)\n json = response.parsed_body\n expect(json[\"mentioned_users\"].length).to be(1)", " mentioned_user = json[\"mentioned_users\"][0]\n expect(mentioned_user[\"id\"]).to be(user_to_mention.id)\n expect(mentioned_user[\"name\"]).to eq(user_to_mention.name)\n expect(mentioned_user[\"username\"]).to eq(user_to_mention.username)\n end", " it \"returns an empty list of mentioned users if nobody was mentioned\" do\n post \"/posts.json\", params: {\n raw: \"No mentions here\",\n topic_id: topic.id,\n }", " expect(response.status).to eq(200)\n expect(response.parsed_body[\"mentioned_users\"].length).to be(0)\n end", " it \"returns an empty list of mentioned users if an nonexistent user was mentioned\" do\n post \"/posts.json\", params: {\n raw: \"Mentioning a @stranger\",\n topic_id: topic.id,\n }", " expect(response.status).to eq(200)\n expect(response.parsed_body[\"mentioned_users\"].length).to be(0)\n end", " it \"doesn't return user status on mentions by default\" do\n user_to_mention.set_status!(\"off to dentist\", \"tooth\")", " post \"/posts.json\", params: {\n raw: \"I am mentioning @#{user_to_mention.username}\",\n topic_id: topic.id,\n }", " expect(response.status).to eq(200)\n json = response.parsed_body\n expect(json[\"mentioned_users\"].length).to be(1)", " status = json[\"mentioned_users\"][0][\"status\"]\n expect(status).to be_nil\n end", " it \"returns user status on mentions if status is enabled in site settings\" do\n SiteSetting.enable_user_status = true\n user_to_mention.set_status!(\"off to dentist\", \"tooth\")", " post \"/posts.json\", params: {\n raw: \"I am mentioning @#{user_to_mention.username}\",\n topic_id: topic.id,\n }", " expect(response.status).to eq(200)\n json = response.parsed_body\n expect(json[\"mentioned_users\"].length).to be(1)", " status = json[\"mentioned_users\"][0][\"status\"]\n expect(status).to be_present\n expect(status[\"emoji\"]).to eq(user_to_mention.user_status.emoji)\n expect(status[\"description\"]).to eq(user_to_mention.user_status.description)\n end\n end\n end", " context \"with topic unlisting\" do\n context \"when logged in as staff\" do\n before do\n sign_in(admin)\n end", " it \"creates an unlisted topic\" do\n expect do\n post \"/posts.json\", params: {\n raw: \"this is the test content\",\n title: \"this is the test title for the topic\",\n unlist_topic: true\n }\n end.to change { Topic.count }.by(1)", " expect(response.status).to eq(200)\n expect(Topic.find(response.parsed_body[\"topic_id\"]).visible).to eq(false)\n end\n end", " context \"when logged in as a non-staff user\" do\n before do\n sign_in(user)\n end", " it \"prevents creation of an unlisted topic\" do\n expect do\n post \"/posts.json\", params: {\n raw: \"this is the test content\",\n title: \"this is the test title for the topic\",\n unlist_topic: true\n }\n end.not_to change { Topic.count }", " expect(response.status).to eq(422)\n expect(response.parsed_body[\"errors\"]).to include(\n I18n.t(\"activerecord.errors.models.topic.attributes.base.unable_to_unlist\")\n )\n end\n end\n end", " describe 'shared draft' do\n fab!(:destination_category) { Fabricate(:category) }", " it \"will raise an error for regular users\" do\n post \"/posts.json\", params: {\n raw: 'this is the shared draft content',\n title: \"this is the shared draft title\",\n category: destination_category.id,\n shared_draft: 'true'\n }\n expect(response).not_to be_successful\n end", " describe \"as a staff user\" do\n before do\n sign_in(moderator)\n end", " it \"will raise an error if there is no shared draft category\" do\n post \"/posts.json\", params: {\n raw: 'this is the shared draft content',\n title: \"this is the shared draft title\",\n category: destination_category.id,\n shared_draft: 'true'\n }\n expect(response).not_to be_successful\n end", " context \"with a shared category\" do\n fab!(:shared_category) { Fabricate(:category) }\n before do\n SiteSetting.shared_drafts_category = shared_category.id\n end", " it \"will work if the shared draft category is present\" do\n post \"/posts.json\", params: {\n raw: 'this is the shared draft content',\n title: \"this is the shared draft title\",\n category: destination_category.id,\n shared_draft: 'true'\n }\n expect(response.status).to eq(200)\n result = response.parsed_body\n topic = Topic.find(result['topic_id'])\n expect(topic.category_id).to eq(shared_category.id)\n expect(topic.shared_draft.category_id).to eq(destination_category.id)\n end\n end\n end\n end", " describe 'warnings' do\n fab!(:user_2) { Fabricate(:user) }", " before do\n Group.refresh_automatic_groups!\n end", " context 'as a staff user' do\n before do\n sign_in(admin)\n end", " it 'should be able to mark a topic as warning' do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: user_2.username,\n is_warning: true\n }", " expect(response.status).to eq(200)", " new_topic = Topic.last", " expect(new_topic.title).to eq('This is some post')\n expect(new_topic.is_official_warning?).to eq(true)\n end", " it 'should be able to mark a topic as not a warning' do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: user_2.username,\n is_warning: false\n }", " expect(response.status).to eq(200)", " new_topic = Topic.last", " expect(new_topic.title).to eq('This is some post')\n expect(new_topic.is_official_warning?).to eq(false)\n end\n end", " context 'as a normal user' do\n it 'should not be able to mark a topic as warning' do\n sign_in(user)\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n archetype: 'private_message',\n title: \"this is some post\",\n target_recipients: user_2.username,\n is_warning: true\n }", " expect(response.status).to eq(200)", " new_topic = Topic.last", " expect(new_topic.title).to eq('This is some post')\n expect(new_topic.is_official_warning?).to eq(false)\n end\n end\n end", " context \"with topic bump\" do\n shared_examples \"it works\" do\n it \"should be able to skip topic bumping\" do\n original_bumped_at = 1.day.ago\n topic = Fabricate(:topic, bumped_at: original_bumped_at)", " post \"/posts.json\", params: {\n raw: 'this is the test content',\n topic_id: topic.id,\n no_bump: true\n }", " expect(response.status).to eq(200)\n expect(topic.reload.bumped_at).to eq_time(original_bumped_at)\n end", " it \"should be able to post with topic bumping\" do\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n topic_id: topic.id\n }", " expect(response.status).to eq(200)\n expect(topic.reload.bumped_at).to eq_time(topic.posts.last.created_at)\n end\n end", " context \"with admins\" do\n before do\n sign_in(admin)\n end", " include_examples \"it works\"\n end", " context \"with moderators\" do\n before do\n sign_in(moderator)\n end", " include_examples \"it works\"\n end", " context \"with TL4 users\" do\n fab!(:trust_level_4) { Fabricate(:trust_level_4) }", " before do\n sign_in(trust_level_4)\n end", " include_examples \"it works\"\n end", " context \"with users\" do\n fab!(:topic) { Fabricate(:topic) }", " [:user].each do |user|\n it \"will raise an error for #{user}\" do\n sign_in(Fabricate(user))\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n topic_id: topic.id,\n no_bump: true\n }\n expect(response.status).to eq(400)\n end\n end\n end\n end", " context \"with featured links\" do\n it \"allows to create topics with featured links\" do\n sign_in(user_trust_level_1)", " post \"/posts.json\", params: {\n title: \"this is the test title for the topic\",\n raw: \"this is the test content\",\n featured_link: \"https://discourse.org\"\n }", " expect(response.status).to eq(200)\n end", " it \"doesn't allow TL0 users to create topics with featured links\" do\n sign_in(user_trust_level_0)", " post \"/posts.json\", params: {\n title: \"this is the test title for the topic\",\n raw: \"this is the test content\",\n featured_link: \"https://discourse.org\"\n }", " expect(response.status).to eq(422)\n end", " it \"doesn't allow to create topics with featured links if featured links are disabled in settings\" do\n SiteSetting.topic_featured_link_enabled = false\n sign_in(user_trust_level_1)", " post \"/posts.json\", params: {\n title: \"this is the test title for the topic\",\n raw: \"this is the test content\",\n featured_link: \"https://discourse.org\"\n }", " expect(response.status).to eq(422)\n end", " it \"doesn't allow to create topics with featured links in the category with forbidden feature links\" do\n category = Fabricate(:category, topic_featured_link_allowed: false)\n sign_in(user_trust_level_1)", " post \"/posts.json\", params: {\n title: \"this is the test title for the topic\",\n raw: \"this is the test content\",\n featured_link: \"https://discourse.org\",\n category: category.id\n }", " expect(response.status).to eq(422)\n end\n end\n end", " describe '#revisions' do\n fab!(:post) { Fabricate(:post, version: 2) }\n let(:post_revision) { Fabricate(:post_revision, post: post) }", " it \"throws an exception when revision is < 2\" do\n get \"/posts/#{post.id}/revisions/1.json\"\n expect(response.status).to eq(400)\n end", " context \"when edit history is not visible to the public\" do", " before { SiteSetting.edit_history_visible_to_public = false }", " it \"ensures anonymous cannot see the revisions\" do\n get \"/posts/#{post.id}/revisions/#{post_revision.number}.json\"\n expect(response).to be_forbidden\n end", " it \"ensures regular user cannot see the revisions\" do\n sign_in(user)\n get \"/posts/#{post.id}/revisions/#{post_revision.number}.json\"\n expect(response).to be_forbidden\n end", " it \"ensures staff can see the revisions\" do\n sign_in(admin)\n get \"/posts/#{post.id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(200)\n end", " it \"ensures poster can see the revisions\" do\n user = Fabricate(:active_user)\n sign_in(user)", " post = Fabricate(:post, user: user, version: 3)\n pr = Fabricate(:post_revision, user: user, post: post)", " get \"/posts/#{pr.post_id}/revisions/#{pr.number}.json\"\n expect(response.status).to eq(200)\n end", " it \"ensures trust level 4 cannot see the revisions\" do\n sign_in(Fabricate(:user, trust_level: 4))\n get \"/posts/#{post_revision.post_id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(403)\n end\n end", " context \"when post is hidden\" do\n before {\n post.hidden = true\n post.save\n }", " it \"throws an exception for users\" do\n sign_in(user)\n get \"/posts/#{post.id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(404)\n end", " it \"works for admins\" do\n sign_in(admin)\n get \"/posts/#{post.id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(200)\n end\n end", " context \"when edit history is visible to everyone\" do", " before { SiteSetting.edit_history_visible_to_public = true }", " it \"ensures anyone can see the revisions\" do\n get \"/posts/#{post_revision.post_id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(200)\n end\n end", " context \"with deleted post\" do\n fab!(:deleted_post) { Fabricate(:post, user: admin, version: 3) }\n fab!(:deleted_post_revision) { Fabricate(:post_revision, user: admin, post: deleted_post) }", " before { deleted_post.trash!(admin) }", " it \"also work on deleted post\" do\n sign_in(admin)\n get \"/posts/#{deleted_post_revision.post_id}/revisions/#{deleted_post_revision.number}.json\"\n expect(response.status).to eq(200)\n end\n end", " context \"with deleted topic\" do\n fab!(:deleted_topic) { Fabricate(:topic, user: admin) }\n fab!(:post) { Fabricate(:post, user: admin, topic: deleted_topic, version: 3) }\n fab!(:post_revision) { Fabricate(:post_revision, user: admin, post: post) }", " before { deleted_topic.trash!(admin) }", " it \"also work on deleted topic\" do\n sign_in(admin)\n get \"/posts/#{post_revision.post_id}/revisions/#{post_revision.number}.json\"\n expect(response.status).to eq(200)\n end\n end", " context \"with a tagged topic\" do\n let(:tag) { Fabricate(:tag) }\n it \"works\" do\n SiteSetting.tagging_enabled = true", " post_revision.post.topic.update(tags: [tag])", " get \"/posts/#{post_revision.post_id}/revisions/latest.json\"\n expect(response.status).to eq(200)", " SiteSetting.tagging_enabled = false", " get \"/posts/#{post_revision.post_id}/revisions/latest.json\"\n expect(response.status).to eq(200)\n end\n end\n end", " describe '#revert' do\n include_examples 'action requires login', :put, \"/posts/123/revisions/2/revert.json\"", " fab!(:post) { Fabricate(:post, user: Fabricate(:user), raw: \"Lorem ipsum dolor sit amet, cu nam libris tractatos, ancillae senserit ius ex\") }\n let(:post_revision) { Fabricate(:post_revision, post: post, modifications: { \"raw\" => [\"this is original post body.\", \"this is edited post body.\"] }) }\n let(:blank_post_revision) { Fabricate(:post_revision, post: post, modifications: { \"edit_reason\" => [\"edit reason #1\", \"edit reason #2\"] }) }\n let(:same_post_revision) { Fabricate(:post_revision, post: post, modifications: { \"raw\" => [\"Lorem ipsum dolor sit amet, cu nam libris tractatos, ancillae senserit ius ex\", \"this is edited post body.\"] }) }", " let(:post_id) { post.id }\n let(:revision_id) { post_revision.number }", " describe 'when logged in as a regular user' do\n it \"does not work\" do\n sign_in(user)\n put \"/posts/#{post_id}/revisions/#{revision_id}/revert.json\"\n expect(response).to_not be_successful\n end\n end", " describe \"when logged in as staff\" do\n before do\n sign_in(moderator)\n end", " it \"fails when revision is < 2\" do\n put \"/posts/#{post_id}/revisions/1/revert.json\"\n expect(response.status).to eq(400)\n end", " it \"fails when post_revision record is not found\" do\n put \"/posts/#{post_id}/revisions/#{revision_id + 1}/revert.json\"\n expect(response).to_not be_successful\n end", " it \"fails when post record is not found\" do\n put \"/posts/#{post_id + 1}/revisions/#{revision_id}/revert.json\"\n expect(response).to_not be_successful\n end", " it \"fails when revision is blank\" do\n put \"/posts/#{post_id}/revisions/#{blank_post_revision.number}/revert.json\"\n expect(response.status).to eq(422)\n expect(response.parsed_body['errors']).to include(I18n.t('revert_version_same'))\n end", " it \"fails when revised version is same as current version\" do\n put \"/posts/#{post_id}/revisions/#{same_post_revision.number}/revert.json\"\n expect(response.status).to eq(422)\n expect(response.parsed_body['errors']).to include(I18n.t('revert_version_same'))\n end", " it \"works!\" do\n put \"/posts/#{post_id}/revisions/#{revision_id}/revert.json\"\n expect(response.status).to eq(200)\n end", " it \"supports reverting posts in deleted topics\" do\n first_post = post.topic.ordered_posts.first\n PostDestroyer.new(moderator, first_post).destroy", " put \"/posts/#{post_id}/revisions/#{revision_id}/revert.json\"\n expect(response.status).to eq(200)\n end\n end\n end", " describe '#expand_embed' do\n before do\n sign_in(user)\n end", " fab!(:post) { Fabricate(:post) }", " it \"raises an error when you can't see the post\" do\n post = Fabricate(:private_message_post)\n get \"/posts/#{post.id}/expand-embed.json\"\n expect(response).not_to be_successful\n end", " it \"retrieves the body when you can see the post\" do\n TopicEmbed.expects(:expanded_for).with(post).returns(\"full content\")\n get \"/posts/#{post.id}/expand-embed.json\"\n expect(response.status).to eq(200)\n expect(response.parsed_body['cooked']).to eq(\"full content\")\n end\n end", " describe '#flagged_posts' do\n include_examples \"action requires login\", :get, \"/posts/system/flagged.json\"", " describe \"when logged in\" do\n it \"raises an error if the user doesn't have permission to see the flagged posts\" do\n sign_in(user)\n get \"/posts/system/flagged.json\"\n expect(response).to be_forbidden\n end", " it \"can see the flagged posts when authorized\" do\n sign_in(moderator)\n get \"/posts/system/flagged.json\"\n expect(response.status).to eq(200)\n end", " it \"only shows agreed and deferred flags\" do\n post_agreed = create_post(user: user)\n post_deferred = create_post(user: user)\n post_disagreed = create_post(user: user)", " r0 = PostActionCreator.spam(moderator, post_agreed).reviewable\n r1 = PostActionCreator.off_topic(moderator, post_deferred).reviewable\n r2 = PostActionCreator.inappropriate(moderator, post_disagreed).reviewable", " r0.perform(admin, :agree_and_keep)\n r1.perform(admin, :ignore)\n r2.perform(admin, :disagree)", " sign_in(Fabricate(:moderator))\n get \"/posts/#{user.username}/flagged.json\"\n expect(response.status).to eq(200)", " expect(response.parsed_body.length).to eq(2)\n end\n end\n end", " describe '#deleted_posts' do\n include_examples \"action requires login\", :get, \"/posts/system/deleted.json\"", " describe \"when logged in\" do\n before do\n Group.refresh_automatic_groups!\n end", " it \"raises an error if the user doesn't have permission to see the deleted posts\" do\n sign_in(user)\n get \"/posts/system/deleted.json\"\n expect(response).to be_forbidden\n end", " it \"can see the deleted posts when authorized\" do\n sign_in(moderator)\n get \"/posts/system/deleted.json\"\n expect(response.status).to eq(200)\n end", " it \"does not raise if topic has been permanently deleted\" do\n post = Fabricate(:post, user: admin)\n PostDestroyer.new(admin, post).destroy\n post.update!(topic_id: -1000)", " sign_in(admin)\n get \"/posts/#{admin.username}/deleted.json\"\n expect(response.status).to eq(200)\n end", " it \"doesn't return secured categories for moderators if they don't have access\" do\n Fabricate(:moderator)", " group = Fabricate(:group)\n group.add_owner(user)", " secured_category = Fabricate(:private_category, group: group)\n secured_post = create_post(user: user, category: secured_category)\n PostDestroyer.new(admin, secured_post).destroy", " sign_in(moderator)\n get \"/posts/#{user.username}/deleted.json\"\n expect(response.status).to eq(200)", " data = response.parsed_body\n expect(data.length).to eq(0)\n end", " it \"doesn't return PMs for moderators\" do\n Fabricate(:moderator)", " pm_post = create_post(user: user, archetype: 'private_message', target_usernames: [admin.username])\n PostDestroyer.new(admin, pm_post).destroy", " sign_in(moderator)\n get \"/posts/#{user.username}/deleted.json\"\n expect(response.status).to eq(200)", " data = response.parsed_body\n expect(data.length).to eq(0)\n end", " it \"only shows posts deleted by other users\" do\n create_post(user: user)\n post_deleted_by_user = create_post(user: user)\n post_deleted_by_admin = create_post(user: user)", " PostDestroyer.new(user, post_deleted_by_user).destroy\n PostDestroyer.new(admin, post_deleted_by_admin).destroy", " sign_in(admin)\n get \"/posts/#{user.username}/deleted.json\"\n expect(response.status).to eq(200)", " data = response.parsed_body\n expect(data.length).to eq(1)\n expect(data[0][\"id\"]).to eq(post_deleted_by_admin.id)\n expect(data[0][\"deleted_by\"][\"id\"]).to eq(admin.id)\n end\n end\n end", " describe '#markdown_id' do\n it \"can be viewed by anonymous\" do\n post = Fabricate(:post, raw: \"123456789\")\n get \"/posts/#{post.id}/raw.json\"\n expect(response.status).to eq(200)\n expect(response.body).to eq(\"123456789\")\n end", " it \"renders a 404 page\" do\n get \"/posts/0/raw\"\n expect(response.status).to eq(404)\n expect(response.body).to include(I18n.t(\"page_not_found.title\"))\n end\n end", " describe '#markdown_num' do\n it \"can be viewed by anonymous\" do\n topic = Fabricate(:topic)\n post = Fabricate(:post, topic: topic, post_number: 1, raw: \"123456789\")\n post.save\n get \"/raw/#{topic.id}/1.json\"\n expect(response.status).to eq(200)\n expect(response.body).to eq(\"123456789\")\n end", " it \"can show whole topics\" do\n topic = Fabricate(:topic)\n post = Fabricate(:post, topic: topic, post_number: 1, raw: \"123456789\")\n post_2 = Fabricate(:post, topic: topic, post_number: 2, raw: \"abcdefghij\")\n post.save\n get \"/raw/#{topic.id}\"\n expect(response.status).to eq(200)\n expect(response.body).to include(\"123456789\", \"abcdefghij\")\n end\n end", " describe '#short_link' do\n fab!(:topic) { Fabricate(:topic) }\n fab!(:post) { Fabricate(:post, topic: topic) }", " it \"redirects to the topic\" do\n get \"/p/#{post.id}.json\"\n expect(response).to be_redirect\n end", " it \"returns a 403 when access is denied for JSON format\" do\n post = Fabricate(:private_message_post)\n get \"/p/#{post.id}.json\"\n expect(response).to be_forbidden\n end", " it \"returns a 403 when access is denied for HTML format\" do\n post = Fabricate(:private_message_post)\n get \"/p/#{post.id}\"\n expect(response).to be_forbidden\n expect(response.body).to have_tag(\"body.no-ember\")\n end", " it \"renders a 404 page\" do\n get \"/p/0\"\n expect(response.status).to eq(404)\n expect(response.body).to include(I18n.t(\"page_not_found.title\"))\n end\n end", " describe '#user_posts_feed' do\n it 'returns public posts rss feed' do\n public_post\n private_post", " get \"/u/#{user.username}/activity.rss\"", " expect(response.status).to eq(200)", " body = response.body", " expect(body).to_not include(private_post.url)\n expect(body).to include(public_post.url)\n end", " it \"doesn't include posts from hidden topics\" do\n public_post.topic.update!(visible: false)", " get \"/u/#{user.username}/activity.rss\"", " expect(response.status).to eq(200)", " body = response.body\n expect(body).not_to include(public_post.url)\n end", " it \"excludes small actions\" do\n small_action = Fabricate(:small_action, user: user)", " get \"/u/#{user.username}/activity.rss\"", " expect(response.status).to eq(200)", " body = response.body", " expect(body).not_to include(small_action.canonical_url)\n end", " it 'returns public posts as JSON' do\n public_post\n private_post", " get \"/u/#{user.username}/activity.json\"", " expect(response.status).to eq(200)", " body = response.body", " expect(body).to_not include(private_post.topic.slug)\n expect(body).to include(public_post.topic.slug)\n end", " it \"returns 404 if `hide_profile_and_presence` user option is checked\" do\n user.user_option.update_columns(hide_profile_and_presence: true)", " get \"/u/#{user.username}/activity.rss\"\n expect(response.status).to eq(404)", " get \"/u/#{user.username}/activity.json\"\n expect(response.status).to eq(404)\n end", " it \"succeeds when `allow_users_to_hide_profile` is false\" do\n user.user_option.update_columns(hide_profile_and_presence: true)\n SiteSetting.allow_users_to_hide_profile = false", " get \"/u/#{user.username}/activity.rss\"\n expect(response.status).to eq(200)", " get \"/u/#{user.username}/activity.json\"\n expect(response.status).to eq(200)\n end\n end", " describe '#latest' do\n context 'with private posts' do\n describe 'when not logged in' do\n it 'should return the right response' do\n Fabricate(:post)", " get \"/private-posts.rss\"", " expect(response.status).to eq(404)", " expect(response.body).to have_tag(\n \"input\", with: { value: \"private_posts\" }\n )\n end\n end", " it 'returns private posts rss feed' do\n sign_in(admin)", " public_post\n private_post\n get \"/private-posts.rss\"", " expect(response.status).to eq(200)", " body = response.body", " expect(body).to include(private_post.url)\n expect(body).to_not include(public_post.url)\n end", " it 'returns private posts for json' do\n sign_in(admin)", " public_post\n private_post\n get \"/private-posts.json\"\n expect(response.status).to eq(200)", " json = response.parsed_body\n post_ids = json['private_posts'].map { |p| p['id'] }", " expect(post_ids).to include private_post.id\n expect(post_ids).to_not include public_post.id\n end\n end", " context 'with public posts' do\n it 'returns public posts with topic rss feed' do\n public_post\n private_post", " get \"/posts.rss\"", " expect(response.status).to eq(200)", " body = response.body", " # we cache in redis, in rare cases this can cause a flaky test\n PostsHelper.clear_canonical_cache!(public_post)", " expect(body).to include(public_post.canonical_url)\n expect(body).to_not include(private_post.url)\n end", " it \"doesn't include posts from hidden topics\" do\n public_post.topic.update!(visible: false)", " get \"/posts.rss\"", " expect(response.status).to eq(200)", " body = response.body", " # we cache in redis, in rare cases this can cause a flaky test\n PostsHelper.clear_canonical_cache!(public_post)", " expect(body).not_to include(public_post.canonical_url)\n end", " it \"excludes small actions\" do\n small_action = Fabricate(:small_action)", " get \"/posts.rss\"", " expect(response.status).to eq(200)", " body = response.body", " expect(body).not_to include(small_action.canonical_url)\n end", " it 'returns public posts with topic for json' do\n topicless_post.update topic_id: -100", " public_post\n private_post\n topicless_post", " get \"/posts.json\"\n expect(response.status).to eq(200)", " json = response.parsed_body\n post_ids = json['latest_posts'].map { |p| p['id'] }", " expect(post_ids).to include public_post.id\n expect(post_ids).to_not include private_post.id\n expect(post_ids).to_not include topicless_post.id\n end\n end\n end", " describe '#cooked' do\n it 'returns the cooked content' do\n post = Fabricate(:post, cooked: \"WAt\")\n get \"/posts/#{post.id}/cooked.json\"", " expect(response.status).to eq(200)\n json = response.parsed_body", " expect(json).to be_present\n expect(json['cooked']).to eq('WAt')\n end\n end", " describe '#raw_email' do\n include_examples \"action requires login\", :get, \"/posts/2/raw-email.json\"", " describe \"when logged in\" do\n let(:post) { Fabricate(:post, deleted_at: 2.hours.ago, user: Fabricate(:user), raw_email: 'email_content') }", " it 'returns 403 when trying to view raw as user that created the post' do\n sign_in(post.user)", " get \"/posts/#{post.id}/raw-email.json\"\n expect(response.status).to eq(403)\n end", " it \"returns 403 when trying to view raw email as a normal user\" do\n sign_in(user)", " get \"/posts/#{post.id}/raw-email.json\"\n expect(response.status).to eq(403)\n end", " it \"can view raw email\" do\n sign_in(moderator)", " get \"/posts/#{post.id}/raw-email.json\"\n expect(response.status).to eq(200)", " json = response.parsed_body\n expect(json['raw_email']).to eq('email_content')\n end\n end\n end", " describe \"#locked\" do\n before do\n sign_in(moderator)\n end", " it 'can lock and unlock the post' do\n put \"/posts/#{public_post.id}/locked.json\", params: { locked: \"true\" }\n expect(response.status).to eq(200)\n public_post.reload\n expect(public_post).to be_locked", " put \"/posts/#{public_post.id}/locked.json\", params: { locked: \"false\" }\n expect(response.status).to eq(200)\n public_post.reload\n expect(public_post).not_to be_locked\n end\n end", " describe \"#notice\" do\n it 'can create and remove notices as a moderator' do\n sign_in(moderator)", " raw_notice = \"Hello *world*!\\n\\nhttps://github.com/discourse/discourse\"\n put \"/posts/#{public_post.id}/notice.json\", params: { notice: raw_notice }", " expect(response.status).to eq(200)\n expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(\"type\" => Post.notices[:custom], \"raw\" => raw_notice, \"cooked\" => PrettyText.cook(raw_notice, features: { onebox: false }))\n expect(UserHistory.where(action: UserHistory.actions[:post_staff_note_create]).count).to eq(1)", " put \"/posts/#{public_post.id}/notice.json\", params: { notice: nil }", " expect(response.status).to eq(200)\n expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(nil)\n expect(UserHistory.where(action: UserHistory.actions[:post_staff_note_destroy]).count).to eq(1)\n end", " describe 'group moderators' do\n fab!(:group_user) { Fabricate(:group_user) }\n let(:user) { group_user.user }\n let(:group) { group_user.group }", " before do\n SiteSetting.enable_category_group_moderation = true\n topic.category.update!(reviewable_by_group_id: group.id)", " sign_in(user)\n end", " it 'can create and remove notices as a group moderator' do\n raw_notice = \"Hello *world*!\\n\\nhttps://github.com/discourse/discourse\"\n put \"/posts/#{public_post.id}/notice.json\", params: { notice: raw_notice }", " expect(response.status).to eq(200)\n expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(\"type\" => Post.notices[:custom], \"raw\" => raw_notice, \"cooked\" => PrettyText.cook(raw_notice, features: { onebox: false }))", " put \"/posts/#{public_post.id}/notice.json\", params: { notice: nil }", " expect(response.status).to eq(200)\n expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(nil)\n end", " it 'prevents a group moderator from altering notes outside of their category' do\n moderatable_group = Fabricate(:group)\n topic.category.update!(reviewable_by_group_id: moderatable_group.id)", " put \"/posts/#{public_post.id}/notice.json\", params: { notice: \"Hello\" }", " expect(response.status).to eq(404)\n end", " it 'prevents a normal user from altering notes' do\n group_user.destroy!\n put \"/posts/#{public_post.id}/notice.json\", params: { notice: \"Hello\" }", " expect(response.status).to eq(404)\n end\n end\n end", " describe \"#pending\" do\n subject(:request) { get \"/posts/#{user.username}/pending.json\" }", " context \"when user is not logged in\" do\n it_behaves_like \"action requires login\", :get, \"/posts/system/pending.json\"\n end", " context \"when user is logged in\" do\n let(:pending_posts) { response.parsed_body[\"pending_posts\"] }", " before { sign_in(current_user) }", " context \"when current user is the same as user\" do\n let(:current_user) { user }", " context \"when there are existing pending posts\" do\n let!(:owner_pending_posts) { Fabricate.times(2, :reviewable_queued_post, created_by: user) }\n let!(:other_pending_post) { Fabricate(:reviewable_queued_post) }\n let(:expected_keys) do\n %w[\n avatar_template\n category_id\n created_at\n created_by_id\n name\n raw_text\n title\n topic_id\n topic_url\n username\n ]\n end", " it \"returns user's pending posts\" do\n request\n expect(pending_posts).to all include \"id\" => be_in(owner_pending_posts.map(&:id))\n expect(pending_posts).to all include(*expected_keys)\n end\n end", " context \"when there aren't any pending posts\" do\n it \"returns an empty array\" do\n request\n expect(pending_posts).to be_empty\n end\n end\n end", " context \"when current user is a staff member\" do\n let(:current_user) { moderator }", " context \"when there are existing pending posts\" do\n let!(:owner_pending_posts) { Fabricate.times(2, :reviewable_queued_post, created_by: user) }\n let!(:other_pending_post) { Fabricate(:reviewable_queued_post) }\n let(:expected_keys) do\n %w[\n avatar_template\n category_id\n created_at\n created_by_id\n name\n raw_text\n title\n topic_id\n topic_url\n username\n ]\n end", " it \"returns user's pending posts\" do\n request\n expect(pending_posts).to all include \"id\" => be_in(owner_pending_posts.map(&:id))\n expect(pending_posts).to all include(*expected_keys)\n end\n end", " context \"when there aren't any pending posts\" do\n it \"returns an empty array\" do\n request\n expect(pending_posts).to be_empty\n end\n end\n end", " context \"when current user is another user\" do\n let(:current_user) { Fabricate(:user) }", " it \"does not allow access\" do\n request\n expect(response).to have_http_status :not_found\n end\n end\n end\n end", " describe Plugin::Instance do\n describe '#add_permitted_post_create_param' do\n fab!(:user) { Fabricate(:user) }\n let(:instance) { Plugin::Instance.new }\n let(:request) do\n Proc.new {\n post \"/posts.json\", params: {\n raw: 'this is the test content',\n title: 'this is the test title for the topic',\n composer_open_duration_msecs: 204,\n typing_duration_msecs: 100,\n reply_to_post_number: 123,\n string_arg: '123',\n hash_arg: { key1: 'val' },\n array_arg: ['1', '2', '3']\n }\n }\n end", " before do\n sign_in(user)\n SiteSetting.min_first_post_typing_time = 0\n end", " it 'allows strings to be added' do\n request.call\n expect(@controller.send(:create_params)).not_to include(string_arg: '123')", " instance.add_permitted_post_create_param(:string_arg)\n request.call\n expect(@controller.send(:create_params)).to include(string_arg: '123')\n end", " it 'allows hashes to be added' do\n instance.add_permitted_post_create_param(:hash_arg)\n request.call\n expect(@controller.send(:create_params)).not_to include(hash_arg: { key1: 'val' })", " instance.add_permitted_post_create_param(:hash_arg, :hash)\n request.call\n expect(@controller.send(:create_params)).to include(hash_arg: { key1: 'val' })\n end", " it 'allows strings to be added' do\n instance.add_permitted_post_create_param(:array_arg)\n request.call\n expect(@controller.send(:create_params)).not_to include(array_arg: ['1', '2', '3'])", " instance.add_permitted_post_create_param(:array_arg, :array)\n request.call\n expect(@controller.send(:create_params)).to include(array_arg: ['1', '2', '3'])\n end", " end\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [11, 1046], "buggy_code_start_loc": [5, 1046], "filenames": ["lib/validators/stripped_length_validator.rb", "spec/requests/posts_controller_spec.rb"], "fixing_code_end_loc": [15, 1061], "fixing_code_start_loc": [5, 1047], "message": "Discourse is an option source discussion platform. Prior to version 2.8.14 on the `stable` branch and version 2.9.0.beta16 on the `beta` and `tests-passed` branches, users can create posts with raw body longer than the `max_length` site setting by including html comments that are not counted toward the character limit. This issue is patched in versions 2.8.14 and 2.9.0.beta16. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:discourse:discourse:*:*:*:*:*:*:*:*", "matchCriteriaId": "9C13BCBA-EF34-4F4B-9F4A-33392EB45196", "versionEndExcluding": "2.8.14", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta1:*:*:*:*:*:*", "matchCriteriaId": "B3803EF9-A296-42B7-887F-93C5E68E94C4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta10:*:*:*:*:*:*", "matchCriteriaId": "35BAC488-3622-4B0B-B8EA-879E8C68E8CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta11:*:*:*:*:*:*", "matchCriteriaId": "406A23B4-B971-4DC8-A132-EE9854FE8546", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta12:*:*:*:*:*:*", "matchCriteriaId": "1DD3C47F-E49F-4E19-9EA7-A322C4CFD541", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta13:*:*:*:*:*:*", "matchCriteriaId": "E924AC08-6978-4DFF-B616-9E3E9D6FBE1B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta14:*:*:*:*:*:*", "matchCriteriaId": "B5A3C7FB-B3B6-45F0-AD7D-062A50490AD7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta2:*:*:*:*:*:*", "matchCriteriaId": "8BA3D313-3C11-43E2-A47D-CBB532D1B6F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta3:*:*:*:*:*:*", "matchCriteriaId": "6F42673E-65F3-4807-9484-20CB747420FB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta4:*:*:*:*:*:*", "matchCriteriaId": "0B91D023-FCE5-4866-AD8B-BBB675763104", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta5:*:*:*:*:*:*", "matchCriteriaId": "0086484D-0164-449C-8AAE-BE7479CB9706", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta6:*:*:*:*:*:*", "matchCriteriaId": "F9D1B031-96C7-44C0-A0A0-F67ABE55C93C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta7:*:*:*:*:*:*", "matchCriteriaId": "750D2AD9-35E7-4AC7-9C22-AA90DAA34F3F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta8:*:*:*:*:*:*", "matchCriteriaId": "B68E308A-BDAB-4614-A563-4460F7996CBE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:3.0.0:beta15:*:*:*:*:*:*", "matchCriteriaId": "F62275F8-11E9-4D94-8F2E-F83905F65031", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Discourse is an option source discussion platform. Prior to version 2.8.14 on the `stable` branch and version 2.9.0.beta16 on the `beta` and `tests-passed` branches, users can create posts with raw body longer than the `max_length` site setting by including html comments that are not counted toward the character limit. This issue is patched in versions 2.8.14 and 2.9.0.beta16. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23549", "lastModified": "2023-01-12T20:33:47.867", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-01-05T19:15:09.500", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/discourse/discourse/commit/bf6b08670a927cc80bb090b7a2e710b4b554e6a8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/discourse/discourse/security/advisories/GHSA-p47g-v5wr-p4xp"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-20"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/discourse/discourse/commit/bf6b08670a927cc80bb090b7a2e710b4b554e6a8"}, "type": "NVD-CWE-Other"}
232
Determine whether the {function_name} code is vulnerable or not.
[ "C.P.Sub 公告系統\n=======\n<h4>前言</h4>", "PHP 公告系統,用 CSV 格式建構出來的小型 PHP 程式。", "基本上就是強化舊版的功能,改寫一下內部架構,並套用了 Bootstrap ,所以自行更換樣式!", "如果使用上有遇到什麼問題,或是有程式上的建議、架構上的建議、甚至是功能上的建議,都歡迎來信告知。", "當然,最重要的是要記得 Bug 回報~", "=======", "<h4>安裝方式</h4>", "<h3>1. Server 健康檢查</h3>\n<ul>\n <li>環境:PHP 5.3 以上 (建議)</li>\n <li>PHP.ini 設定:\n <ul>\n <ol>short_open_tag = on;</ol>\n <ol>file_uploads = on;</ol>\n <ol>allow_url_fopen = on;</ol>\n </ul>\n </li>\n</ul>\n<h3>2. 上傳至 FTP 目錄</h3>\n<h3>3. 修改資料夾/目錄權限,改成 777</h3>\n<ul> \n <li>cpsub/upload/</li>\n <li>cpsub/db/article.txt</li>\n <li>cpsub/db/settings.txt</li>\n</ul>\n<h3>4. 修改帳號密碼</h3>\n<ul>\n <li>開啟 cpsub/config/config.php</li>\n <li>修改陣列數值</li>\n <code>\n $add_user\t= array(\"username\" => \"admin\", // 帳號\n\t\t\t\t\t\"password\" => \"admin\", // 密碼\n\t\t\t\t\t\"nickname\" => \"管理員\" // 管理員\n\t\t\t\t\t); \n </code>\n</ul>\n<h3>5. 大功告成,開啟瀏覽器觀看!</h3>", "=======", "<h4>版本更新</h4>\n", "<b>2016-11-30: v5.1</b><br>\n<li>1.加入最後瀏覽時間,以阻擋過度瀏覽而導致文章消失的問題</li>\n<li>2.修改一些小 Bug</li>\n<li>3.加入 IP Checker ,但好像沒什麼用</li>", "", "\n=======", "This is a PHP bulletin project that made with CSV file system (which is not using SQL as the database)", "If you have any question or suggestion about this project, please contact with me by using E-mail, Facebook message, or Twitter.", "<h4>Installation</h4>", "<h3>1. Server Configuration</h3>\n<ul>\n <li>Environment:PHP 5.3 or higher</li>\n <li>PHP.ini config:\n <ul>\n <ol>short_open_tag = on;</ol>\n <ol>file_uploads = on;</ol>\n <ol>allow_url_fopen = on;</ol>\n </ul>\n </li>\n</ul>\n<h3>2. Upload the whole \"cpsub\" folder to your server</h3>\n<h3>3. Update the folder/files's permissions to 777</h3>\n<ul> \n <li>cpsub/upload/</li>\n <li>cpsub/db/article.txt</li>\n <li>cpsub/db/settings.txt</li>\n</ul>\n<h3>4. Update the user name and user password</h3>\n<ul>\n <li>Open cpsub/config/config.php</li>\n <li>Edit the array values</li>\n <code>\n $add_user\t= array(\"username\" => \"admin\", // account\n\t\t\t\t\t\"password\" => \"admin\", // password\n\t\t\t\t\t\"nickname\" => \"Admin\" // Nickname\n\t\t\t\t\t); \n </code>\n</ul>\n<h3>5. Finish!!</h3>", "\n=======", "<h4>Relsease Logs</h4>\n", "", "<b>2017-4-6: v5.21</b><br>\n<li>1. Filter Update</li>", "<b>2017-3-27: v5.2</b><br>\n<li>1. XSS issues resolved</li>", "<b>2016-11-30: v5.1</b><br>\n<li>1. Added a last-time-viewed date column to prevent the data format loses</li>\n<li>2. Remove some bugs</li>\n<li>2. Added an IP Checker</li>", "", "=======\n=======", "Demo 網址:http://cooltey.org/cpsub/\n", "目前程式版本 Current Version:v5.21", "\n作者 Author:Cooltey Feng", "E-mail:coolteygame@gmail.com", "Facebook:http://www.facebook.com/cooltey", "Twitter:http://twitter.com/cooltey", "網站 My Website:http://www.cooltey.org", "若有問題,歡迎交流!", "Contact me if you have any question!", "=======" ]
[ 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, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [122], "buggy_code_start_loc": [52], "filenames": ["README.md"], "fixing_code_end_loc": [123], "fixing_code_start_loc": [52], "message": "C.P.Sub before 5.3 allows CSRF via a manage.php?p=article_del&id= URI.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:c.p.sub_project:c.p.sub:*:*:*:*:*:*:*:*", "matchCriteriaId": "514B6779-FA33-4B6D-BCBD-D9CB49E2ED17", "versionEndExcluding": "5.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "C.P.Sub before 5.3 allows CSRF via a manage.php?p=article_del&id= URI."}, {"lang": "es", "value": "C.P.Sub, en versiones anteriores a la 5.3, permite Cross-Site Request Forgery (CSRF) mediante un URI manage.php?p=article_delid=."}], "evaluatorComment": null, "id": "CVE-2019-7738", "lastModified": "2019-02-13T12:31:45.517", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.8, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-02-11T21:29:00.413", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cooltey/C.P.Sub/commit/b2be52fd89b6fd4d69d63d504bc11742cd679ebe"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/cooltey/C.P.Sub/issues/3"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/cooltey/C.P.Sub/commit/b2be52fd89b6fd4d69d63d504bc11742cd679ebe"}, "type": "CWE-352"}
233
Determine whether the {function_name} code is vulnerable or not.
[ "C.P.Sub 公告系統\n=======\n<h4>前言</h4>", "PHP 公告系統,用 CSV 格式建構出來的小型 PHP 程式。", "基本上就是強化舊版的功能,改寫一下內部架構,並套用了 Bootstrap ,所以自行更換樣式!", "如果使用上有遇到什麼問題,或是有程式上的建議、架構上的建議、甚至是功能上的建議,都歡迎來信告知。", "當然,最重要的是要記得 Bug 回報~", "=======", "<h4>安裝方式</h4>", "<h3>1. Server 健康檢查</h3>\n<ul>\n <li>環境:PHP 5.3 以上 (建議)</li>\n <li>PHP.ini 設定:\n <ul>\n <ol>short_open_tag = on;</ol>\n <ol>file_uploads = on;</ol>\n <ol>allow_url_fopen = on;</ol>\n </ul>\n </li>\n</ul>\n<h3>2. 上傳至 FTP 目錄</h3>\n<h3>3. 修改資料夾/目錄權限,改成 777</h3>\n<ul> \n <li>cpsub/upload/</li>\n <li>cpsub/db/article.txt</li>\n <li>cpsub/db/settings.txt</li>\n</ul>\n<h3>4. 修改帳號密碼</h3>\n<ul>\n <li>開啟 cpsub/config/config.php</li>\n <li>修改陣列數值</li>\n <code>\n $add_user\t= array(\"username\" => \"admin\", // 帳號\n\t\t\t\t\t\"password\" => \"admin\", // 密碼\n\t\t\t\t\t\"nickname\" => \"管理員\" // 管理員\n\t\t\t\t\t); \n </code>\n</ul>\n<h3>5. 大功告成,開啟瀏覽器觀看!</h3>", "=======", "<h4>版本更新</h4>\n", "<b>2019-02-10: v5.3</b><br>\n<li>1.修正 CSRF 問題並新增開關 CSRF 防護的功能</li>", "", "\n=======", "This is a PHP bulletin project that made with CSV file system (which is not using SQL as the database)", "If you have any question or suggestion about this project, please contact with me by using E-mail, Facebook message, or Twitter.", "<h4>Installation</h4>", "<h3>1. Server Configuration</h3>\n<ul>\n <li>Environment:PHP 5.3 or higher</li>\n <li>PHP.ini config:\n <ul>\n <ol>short_open_tag = on;</ol>\n <ol>file_uploads = on;</ol>\n <ol>allow_url_fopen = on;</ol>\n </ul>\n </li>\n</ul>\n<h3>2. Upload the whole \"cpsub\" folder to your server</h3>\n<h3>3. Update the folder/files's permissions to 777</h3>\n<ul> \n <li>cpsub/upload/</li>\n <li>cpsub/db/article.txt</li>\n <li>cpsub/db/settings.txt</li>\n</ul>\n<h3>4. Update the user name and user password</h3>\n<ul>\n <li>Open cpsub/config/config.php</li>\n <li>Edit the array values</li>\n <code>\n $add_user\t= array(\"username\" => \"admin\", // account\n\t\t\t\t\t\"password\" => \"admin\", // password\n\t\t\t\t\t\"nickname\" => \"Admin\" // Nickname\n\t\t\t\t\t); \n </code>\n</ul>\n<h3>5. Finish!!</h3>", "\n=======", "<h4>Relsease Logs</h4>\n", "<b>2019-2-10: v5.3</b><br>\n<li>1. Added CSRF protection</li>\n", "<b>2017-4-6: v5.21</b><br>\n<li>1. Filter Update</li>", "<b>2017-3-27: v5.2</b><br>\n<li>1. XSS issues resolved</li>", "<b>2016-11-30: v5.1</b><br>\n<li>1. Added a last-time-viewed date column to prevent the data format loses</li>\n<li>2. Remove some bugs</li>\n<li>2. Added an IP Checker</li>", "", "=======\n=======", "Demo 網址:http://cooltey.org/cpsub/\n", "目前程式版本 Current Version:v5.3", "\n作者 Author:Cooltey Feng", "E-mail:coolteygame@gmail.com", "Facebook:http://www.facebook.com/cooltey", "Twitter:http://twitter.com/cooltey", "網站 My Website:http://www.cooltey.org", "若有問題,歡迎交流!", "Contact me if you have any question!", "=======" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [122], "buggy_code_start_loc": [52], "filenames": ["README.md"], "fixing_code_end_loc": [123], "fixing_code_start_loc": [52], "message": "C.P.Sub before 5.3 allows CSRF via a manage.php?p=article_del&id= URI.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:c.p.sub_project:c.p.sub:*:*:*:*:*:*:*:*", "matchCriteriaId": "514B6779-FA33-4B6D-BCBD-D9CB49E2ED17", "versionEndExcluding": "5.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "C.P.Sub before 5.3 allows CSRF via a manage.php?p=article_del&id= URI."}, {"lang": "es", "value": "C.P.Sub, en versiones anteriores a la 5.3, permite Cross-Site Request Forgery (CSRF) mediante un URI manage.php?p=article_delid=."}], "evaluatorComment": null, "id": "CVE-2019-7738", "lastModified": "2019-02-13T12:31:45.517", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.8, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-02-11T21:29:00.413", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cooltey/C.P.Sub/commit/b2be52fd89b6fd4d69d63d504bc11742cd679ebe"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/cooltey/C.P.Sub/issues/3"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/cooltey/C.P.Sub/commit/b2be52fd89b6fd4d69d63d504bc11742cd679ebe"}, "type": "CWE-352"}
233
Determine whether the {function_name} code is vulnerable or not.
[ "# For more information on configuration, see:\n# * Official English Documentation: http://nginx.org/en/docs/", "daemon on;\nworker_processes auto;\nerror_log /dev/stderr;\npid /tmp/nginx.pid;", "# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.\ninclude /usr/share/nginx/modules/*.conf;", "events {\n worker_connections 1024;\n}", "http {\n log_format main '$remote_addr - $remote_user [$time_local] \"$request\" '\n '$status $body_bytes_sent \"$http_referer\" '\n '\"$http_user_agent\" \"$http_x_forwarded_for\"';", " access_log /dev/stdout main;", " sendfile on;\n tcp_nopush on;\n tcp_nodelay on;\n keepalive_timeout 65;\n types_hash_max_size 4096;", " include /etc/nginx/mime.types;\n default_type application/octet-stream;", " gzip on;\n gzip_disable \"msie6\";", " # note: this should be bigger than\n # FILE_UPLOAD_MAX_SIZE from Kiwi TCMS which defaults to 5M.\n client_max_body_size 10m;", " # limit URI size, see\n # https://github.com/kiwitcms/Kiwi/issues/1054\n large_client_header_buffers 4 10k;", " ssl_certificate /Kiwi/ssl/localhost.crt;\n ssl_certificate_key /Kiwi/ssl/localhost.key;", " ssl_protocols TLSv1.2 TLSv1.3;\n ssl_ciphers HIGH:!aNULL:!MD5;\n ssl_prefer_server_ciphers off;", " # default proxy settings\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;", " map $request_uri $limit_key {\n default \"\";\n ~^/accounts/ $binary_remote_addr;\n }\n limit_req_zone $limit_key zone=ten-per-sec:10m rate=10r/s;\n limit_req_status 429;", " upstream kiwitcms {\n server unix:///tmp/kiwitcms.sock;\n }\n", "", " add_header X-Frame-Options DENY;\n add_header X-Content-Type-Options nosniff;", "", "\n server {\n listen 8080;\n listen [::]:8080;\n server_name _;", " location / {\n return 301 https://$host$request_uri;\n }\n }", " server {\n listen 8443 ssl;\n listen [::]:8443 ssl;\n server_name _;", " location /uploads/ {\n alias /Kiwi/uploads/;\n }", " location /static/ {\n alias /Kiwi/static/;\n }", " location / {\n include /etc/nginx/uwsgi_params;\n uwsgi_pass kiwitcms;", " limit_req zone=ten-per-sec burst=20 nodelay;\n }\n }\n}" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [66, 20, 34, 89], "buggy_code_start_loc": [64, 20, 33, 89], "filenames": ["etc/nginx.conf", "tcms/core/middleware.py", "tcms/settings/devel.py", "tests/test_http.sh"], "fixing_code_end_loc": [69, 38, 37, 94], "fixing_code_start_loc": [65, 21, 33, 90], "message": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kiwitcms:kiwi_tcms:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4287F3C-2839-4274-8D5D-74C9143F1949", "versionEndExcluding": "12.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually."}], "evaluatorComment": null, "id": "CVE-2023-27489", "lastModified": "2023-04-06T17:42:45.403", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-29T19:15:22.277", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/kiwitcms/Kiwi/security/advisories/GHSA-2wcr-87wf-cf9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, "type": "CWE-79"}
234
Determine whether the {function_name} code is vulnerable or not.
[ "# For more information on configuration, see:\n# * Official English Documentation: http://nginx.org/en/docs/", "daemon on;\nworker_processes auto;\nerror_log /dev/stderr;\npid /tmp/nginx.pid;", "# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.\ninclude /usr/share/nginx/modules/*.conf;", "events {\n worker_connections 1024;\n}", "http {\n log_format main '$remote_addr - $remote_user [$time_local] \"$request\" '\n '$status $body_bytes_sent \"$http_referer\" '\n '\"$http_user_agent\" \"$http_x_forwarded_for\"';", " access_log /dev/stdout main;", " sendfile on;\n tcp_nopush on;\n tcp_nodelay on;\n keepalive_timeout 65;\n types_hash_max_size 4096;", " include /etc/nginx/mime.types;\n default_type application/octet-stream;", " gzip on;\n gzip_disable \"msie6\";", " # note: this should be bigger than\n # FILE_UPLOAD_MAX_SIZE from Kiwi TCMS which defaults to 5M.\n client_max_body_size 10m;", " # limit URI size, see\n # https://github.com/kiwitcms/Kiwi/issues/1054\n large_client_header_buffers 4 10k;", " ssl_certificate /Kiwi/ssl/localhost.crt;\n ssl_certificate_key /Kiwi/ssl/localhost.key;", " ssl_protocols TLSv1.2 TLSv1.3;\n ssl_ciphers HIGH:!aNULL:!MD5;\n ssl_prefer_server_ciphers off;", " # default proxy settings\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;", " map $request_uri $limit_key {\n default \"\";\n ~^/accounts/ $binary_remote_addr;\n }\n limit_req_zone $limit_key zone=ten-per-sec:10m rate=10r/s;\n limit_req_status 429;", " upstream kiwitcms {\n server unix:///tmp/kiwitcms.sock;\n }\n", " # WARNING: make sure these match tcms.core.middleware.ExtraHeadersMiddleware", " add_header X-Frame-Options DENY;\n add_header X-Content-Type-Options nosniff;", " add_header Content-Security-Policy \"script-src 'self' cdn.crowdin.com;\";", "\n server {\n listen 8080;\n listen [::]:8080;\n server_name _;", " location / {\n return 301 https://$host$request_uri;\n }\n }", " server {\n listen 8443 ssl;\n listen [::]:8443 ssl;\n server_name _;", " location /uploads/ {\n alias /Kiwi/uploads/;\n }", " location /static/ {\n alias /Kiwi/static/;\n }", " location / {\n include /etc/nginx/uwsgi_params;\n uwsgi_pass kiwitcms;", " limit_req zone=ten-per-sec burst=20 nodelay;\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 ]
PreciseBugs
{"buggy_code_end_loc": [66, 20, 34, 89], "buggy_code_start_loc": [64, 20, 33, 89], "filenames": ["etc/nginx.conf", "tcms/core/middleware.py", "tcms/settings/devel.py", "tests/test_http.sh"], "fixing_code_end_loc": [69, 38, 37, 94], "fixing_code_start_loc": [65, 21, 33, 90], "message": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kiwitcms:kiwi_tcms:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4287F3C-2839-4274-8D5D-74C9143F1949", "versionEndExcluding": "12.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually."}], "evaluatorComment": null, "id": "CVE-2023-27489", "lastModified": "2023-04-06T17:42:45.403", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-29T19:15:22.277", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/kiwitcms/Kiwi/security/advisories/GHSA-2wcr-87wf-cf9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, "type": "CWE-79"}
234
Determine whether the {function_name} code is vulnerable or not.
[ "# pylint: disable=no-self-use, too-few-public-methods", "from django.conf import settings\nfrom django.contrib.sites.models import Site\nfrom django.db.utils import OperationalError, ProgrammingError\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.utils.deprecation import MiddlewareMixin", "\nclass CheckDBStructureExistsMiddleware(MiddlewareMixin):\n def process_request(self, request):\n if request.path == \"/init-db/\":\n return None\n try:\n Site.objects.get(pk=settings.SITE_ID)\n except (OperationalError, ProgrammingError):\n # Redirect to Setup view\n return HttpResponseRedirect(reverse(\"init-db\"))\n return None", "" ]
[ 1, 1, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [66, 20, 34, 89], "buggy_code_start_loc": [64, 20, 33, 89], "filenames": ["etc/nginx.conf", "tcms/core/middleware.py", "tcms/settings/devel.py", "tests/test_http.sh"], "fixing_code_end_loc": [69, 38, 37, 94], "fixing_code_start_loc": [65, 21, 33, 90], "message": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kiwitcms:kiwi_tcms:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4287F3C-2839-4274-8D5D-74C9143F1949", "versionEndExcluding": "12.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually."}], "evaluatorComment": null, "id": "CVE-2023-27489", "lastModified": "2023-04-06T17:42:45.403", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-29T19:15:22.277", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/kiwitcms/Kiwi/security/advisories/GHSA-2wcr-87wf-cf9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, "type": "CWE-79"}
234
Determine whether the {function_name} code is vulnerable or not.
[ "# pylint: disable=no-self-use, too-few-public-methods", "from django.conf import settings\nfrom django.contrib.sites.models import Site\nfrom django.db.utils import OperationalError, ProgrammingError\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.utils.deprecation import MiddlewareMixin", "\nclass CheckDBStructureExistsMiddleware(MiddlewareMixin):\n def process_request(self, request):\n if request.path == \"/init-db/\":\n return None\n try:\n Site.objects.get(pk=settings.SITE_ID)\n except (OperationalError, ProgrammingError):\n # Redirect to Setup view\n return HttpResponseRedirect(reverse(\"init-db\"))\n return None", "", "class ExtraHeadersMiddleware(MiddlewareMixin):\n \"\"\"\n This is enabled only during testing and development. The actual headers\n are configured in `etc/nginx.conf`!\n \"\"\"", " def process_response(self, request, response):\n if settings.DEBUG:\n response.headers[\"X-Frame-Options\"] = \"DENY\"\n response.headers[\"X-Content-Type-Options\"] = \"nosniff\"\n response.headers[\n \"Content-Security-Policy\"\n ] = \"script-src 'self' cdn.crowdin.com;\"", " return response" ]
[ 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [66, 20, 34, 89], "buggy_code_start_loc": [64, 20, 33, 89], "filenames": ["etc/nginx.conf", "tcms/core/middleware.py", "tcms/settings/devel.py", "tests/test_http.sh"], "fixing_code_end_loc": [69, 38, 37, 94], "fixing_code_start_loc": [65, 21, 33, 90], "message": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kiwitcms:kiwi_tcms:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4287F3C-2839-4274-8D5D-74C9143F1949", "versionEndExcluding": "12.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually."}], "evaluatorComment": null, "id": "CVE-2023-27489", "lastModified": "2023-04-06T17:42:45.403", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-29T19:15:22.277", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/kiwitcms/Kiwi/security/advisories/GHSA-2wcr-87wf-cf9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, "type": "CWE-79"}
234
Determine whether the {function_name} code is vulnerable or not.
[ "# pylint: disable=wildcard-import, unused-wildcard-import\n\"\"\"\n Django settings for devel env.\n\"\"\"", "import os", "from .common import * # noqa: F403", "# Debug settings\nDEBUG = True", "# Database settings\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": str(TEMP_DIR / \"kiwi.devel.sqlite\"), # noqa: F405\n \"USER\": \"root\",\n \"PASSWORD\": \"\",\n \"HOST\": \"\",\n \"PORT\": \"\",\n }\n}", "\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django.core.cache.backends.dummy.DummyCache\",\n }\n}\n# django-debug-toolbar settings\n", "MIDDLEWARE += [\"debug_toolbar.middleware.DebugToolbarMiddleware\"] # noqa: F405", "\nINSTALLED_APPS += [\"debug_toolbar\"] # noqa: F405", "MEDIA_ROOT = os.path.join(TCMS_ROOT_PATH, \"..\", \"uploads\") # noqa: F405", "# Needed by django.template.context_processors.debug:\n# See:\n# http://docs.djangoproject.com/en/dev/ref/templates/api/#django-template-context-processors-debug\nINTERNAL_IPS = (\"127.0.0.1\",)", "STATICFILES_STORAGE = \"tcms.tests.storage.RaiseWhenFileNotFound\"" ]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [66, 20, 34, 89], "buggy_code_start_loc": [64, 20, 33, 89], "filenames": ["etc/nginx.conf", "tcms/core/middleware.py", "tcms/settings/devel.py", "tests/test_http.sh"], "fixing_code_end_loc": [69, 38, 37, 94], "fixing_code_start_loc": [65, 21, 33, 90], "message": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kiwitcms:kiwi_tcms:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4287F3C-2839-4274-8D5D-74C9143F1949", "versionEndExcluding": "12.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually."}], "evaluatorComment": null, "id": "CVE-2023-27489", "lastModified": "2023-04-06T17:42:45.403", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-29T19:15:22.277", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/kiwitcms/Kiwi/security/advisories/GHSA-2wcr-87wf-cf9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, "type": "CWE-79"}
234
Determine whether the {function_name} code is vulnerable or not.
[ "# pylint: disable=wildcard-import, unused-wildcard-import\n\"\"\"\n Django settings for devel env.\n\"\"\"", "import os", "from .common import * # noqa: F403", "# Debug settings\nDEBUG = True", "# Database settings\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": str(TEMP_DIR / \"kiwi.devel.sqlite\"), # noqa: F405\n \"USER\": \"root\",\n \"PASSWORD\": \"\",\n \"HOST\": \"\",\n \"PORT\": \"\",\n }\n}", "\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django.core.cache.backends.dummy.DummyCache\",\n }\n}\n# django-debug-toolbar settings\n", "MIDDLEWARE += [ # noqa: F405\n \"debug_toolbar.middleware.DebugToolbarMiddleware\",\n \"tcms.core.middleware.ExtraHeadersMiddleware\",\n]", "\nINSTALLED_APPS += [\"debug_toolbar\"] # noqa: F405", "MEDIA_ROOT = os.path.join(TCMS_ROOT_PATH, \"..\", \"uploads\") # noqa: F405", "# Needed by django.template.context_processors.debug:\n# See:\n# http://docs.djangoproject.com/en/dev/ref/templates/api/#django-template-context-processors-debug\nINTERNAL_IPS = (\"127.0.0.1\",)", "STATICFILES_STORAGE = \"tcms.tests.storage.RaiseWhenFileNotFound\"" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [66, 20, 34, 89], "buggy_code_start_loc": [64, 20, 33, 89], "filenames": ["etc/nginx.conf", "tcms/core/middleware.py", "tcms/settings/devel.py", "tests/test_http.sh"], "fixing_code_end_loc": [69, 38, 37, 94], "fixing_code_start_loc": [65, 21, 33, 90], "message": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kiwitcms:kiwi_tcms:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4287F3C-2839-4274-8D5D-74C9143F1949", "versionEndExcluding": "12.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually."}], "evaluatorComment": null, "id": "CVE-2023-27489", "lastModified": "2023-04-06T17:42:45.403", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-29T19:15:22.277", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/kiwitcms/Kiwi/security/advisories/GHSA-2wcr-87wf-cf9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, "type": "CWE-79"}
234
Determine whether the {function_name} code is vulnerable or not.
[ "#!/bin/bash", ". /usr/share/beakerlib/beakerlib.sh", "assert_up_and_running() {\n sleep 10\n # HTTP redirects; HTTPS display the login page\n rlRun -t -c \"curl -o- http://localhost/ | grep '301 Moved Permanently'\"\n rlRun -t -c \"curl -k -L -o- https://localhost/ | grep 'Welcome to Kiwi TCMS'\"\n}", "get_dashboard() {\n rlRun -t -c \"curl -k -L -o- -c /tmp/testcookies.txt $1/\"\n CSRF_TOKEN=$(grep csrftoken /tmp/testcookies.txt | cut -f 7)\n rlRun -t -c \"curl -e $1/accounts/login/ -d username=testadmin -d password=password \\\n -d csrfmiddlewaretoken=$CSRF_TOKEN -k -L -i -o /tmp/testdata.txt \\\n -b /tmp/testcookies.txt -c /tmp/login-cookies.txt $1/accounts/login/\"\n rlAssertGrep \"<title>Kiwi TCMS - Dashboard</title>\" /tmp/testdata.txt\n}", "exec_wrk() {\n URL=$1\n LOGS_DIR=$2\n LOG_BASENAME=$3\n EXTRA_HEADERS=${4:-\"X-Dummy-Header: 1\"}", " WRK_FILE=\"$LOGS_DIR/$LOG_BASENAME.log\"", " wrk -d10s -t4 -c4 -H \"$EXTRA_HEADERS\" \"$URL\" > \"$WRK_FILE\"", " TOTAL_REQUESTS=$(grep 'requests in ' \"$WRK_FILE\" | tr -s ' ' | cut -f2 -d' ')\n FAILED_REQUESTS=$(grep 'Non-2xx or 3xx responses:' \"$WRK_FILE\" | tr -d ' ' | cut -f2 -d:)\n test -z \"$FAILED_REQUESTS\" && FAILED_REQUESTS=\"0\"\n COMPLETED_REQUESTS=$((TOTAL_REQUESTS - FAILED_REQUESTS))", " return \"$COMPLETED_REQUESTS\"\n}", "rlJournalStart\n rlPhaseStartSetup\n # wait for tear-down from previous script b/c\n # in CI subsequent tests can't find the db host\n sleep 5", " WRK_DIR=$(mktemp -d ./wrk-logs-XXXX)\n chmod go+rwx \"$WRK_DIR\"", " rlRun -t -c \"docker-compose up -d\"\n sleep 10\n rlRun -t -c \"docker exec -i kiwi_web /Kiwi/manage.py migrate\"\n assert_up_and_running\n rlPhaseEnd", " rlPhaseStartTest \"Should not display SSL warning for HTTPS connection\"\n rlRun -t -c \"docker exec -i kiwi_web /Kiwi/manage.py createsuperuser \\\n --username testadmin --email testadmin@domain.com --noinput\"\n rlRun -t -c \"cat tests/set_testadmin_pass.py | docker exec -i kiwi_web /Kiwi/manage.py shell\"", " get_dashboard \"https://localhost\"\n rlAssertNotGrep \"You are not using a secure connection.\" /tmp/testdata.txt\n rlPhaseEnd", " rlPhaseStartTest \"Should allow file upload with UTF-8 filenames\"\n cat > ~/.tcms.conf << _EOF_\n[tcms]\nurl = https://localhost/xml-rpc/\nusername = testadmin\npassword = password\n_EOF_", " rlRun -t -c \"./tests/test_utf8_uploads.py -v\"\n rlPhaseEnd", " rlPhaseStartTest \"Should send ETag header\"\n rlRun -t -c \"curl -k -D- https://localhost/static/images/kiwi_h20.png 2>/dev/null | grep 'ETag'\"\n rlPhaseEnd", " rlPhaseStartTest \"Should NOT send Cache-Control header\"\n rlRun -t -c \"curl -k -D- https://localhost/static/images/kiwi_h20.png 2>/dev/null | grep 'Cache-Control'\" 1\n rlPhaseEnd", " rlPhaseStartTest \"Should send X-Frame-Options header\"\n rlRun -t -c \"curl -k -D- https://localhost 2>/dev/null | grep 'X-Frame-Options: DENY'\"\n rlPhaseEnd", " rlPhaseStartTest \"Should send X-Content-Type-Options header\"\n rlRun -t -c \"curl -k -D- https://localhost 2>/dev/null | grep 'X-Content-Type-Options: nosniff'\"\n rlPhaseEnd\n", "", " rlPhaseStartTest \"Performance baseline for /accounts/register/\"\n exec_wrk \"https://localhost/accounts/login/\" \"$WRK_DIR\" \"register-account-page\"\n rlPhaseEnd", " rlPhaseStartTest \"Performance baseline for /accounts/login/\"\n exec_wrk \"https://localhost/accounts/login/\" \"$WRK_DIR\" \"login-page\"\n rlPhaseEnd", " rlPhaseStartTest \"Performance baseline for /accounts/passwordreset/\"\n exec_wrk \"https://localhost/accounts/login/\" \"$WRK_DIR\" \"password-reset-page\"\n rlPhaseEnd", " rlPhaseStartTest \"Performance baseline for static file\"\n exec_wrk \"https://localhost/static/images/kiwi_h20.png\" \"$WRK_DIR\" \"static-image\"\n rlPhaseEnd", " rlPhaseStartTest \"Performance baseline for / aka dashboard\"\n # Note: the cookies file is created in get_dashboard() above\n SESSION_ID=$(grep sessionid /tmp/login-cookies.txt | cut -f 7)\n exec_wrk \"https://localhost/\" \"$WRK_DIR\" \"dashboard\" \"Cookie: sessionid=$SESSION_ID\"\n rlPhaseEnd", " rlPhaseStartCleanup\n rlRun -t -c \"docker-compose down\"\n rm -f /tmp/testcookies.txt\n rm -f /tmp/testdata.txt\n if [ -n \"$ImageOS\" ]; then\n rlRun -t -c \"docker volume rm kiwi_db_data\"\n fi\n rlPhaseEnd\nrlJournalEnd", "rlJournalPrintText" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [66, 20, 34, 89], "buggy_code_start_loc": [64, 20, 33, 89], "filenames": ["etc/nginx.conf", "tcms/core/middleware.py", "tcms/settings/devel.py", "tests/test_http.sh"], "fixing_code_end_loc": [69, 38, 37, 94], "fixing_code_start_loc": [65, 21, 33, 90], "message": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kiwitcms:kiwi_tcms:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4287F3C-2839-4274-8D5D-74C9143F1949", "versionEndExcluding": "12.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually."}], "evaluatorComment": null, "id": "CVE-2023-27489", "lastModified": "2023-04-06T17:42:45.403", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-29T19:15:22.277", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/kiwitcms/Kiwi/security/advisories/GHSA-2wcr-87wf-cf9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, "type": "CWE-79"}
234
Determine whether the {function_name} code is vulnerable or not.
[ "#!/bin/bash", ". /usr/share/beakerlib/beakerlib.sh", "assert_up_and_running() {\n sleep 10\n # HTTP redirects; HTTPS display the login page\n rlRun -t -c \"curl -o- http://localhost/ | grep '301 Moved Permanently'\"\n rlRun -t -c \"curl -k -L -o- https://localhost/ | grep 'Welcome to Kiwi TCMS'\"\n}", "get_dashboard() {\n rlRun -t -c \"curl -k -L -o- -c /tmp/testcookies.txt $1/\"\n CSRF_TOKEN=$(grep csrftoken /tmp/testcookies.txt | cut -f 7)\n rlRun -t -c \"curl -e $1/accounts/login/ -d username=testadmin -d password=password \\\n -d csrfmiddlewaretoken=$CSRF_TOKEN -k -L -i -o /tmp/testdata.txt \\\n -b /tmp/testcookies.txt -c /tmp/login-cookies.txt $1/accounts/login/\"\n rlAssertGrep \"<title>Kiwi TCMS - Dashboard</title>\" /tmp/testdata.txt\n}", "exec_wrk() {\n URL=$1\n LOGS_DIR=$2\n LOG_BASENAME=$3\n EXTRA_HEADERS=${4:-\"X-Dummy-Header: 1\"}", " WRK_FILE=\"$LOGS_DIR/$LOG_BASENAME.log\"", " wrk -d10s -t4 -c4 -H \"$EXTRA_HEADERS\" \"$URL\" > \"$WRK_FILE\"", " TOTAL_REQUESTS=$(grep 'requests in ' \"$WRK_FILE\" | tr -s ' ' | cut -f2 -d' ')\n FAILED_REQUESTS=$(grep 'Non-2xx or 3xx responses:' \"$WRK_FILE\" | tr -d ' ' | cut -f2 -d:)\n test -z \"$FAILED_REQUESTS\" && FAILED_REQUESTS=\"0\"\n COMPLETED_REQUESTS=$((TOTAL_REQUESTS - FAILED_REQUESTS))", " return \"$COMPLETED_REQUESTS\"\n}", "rlJournalStart\n rlPhaseStartSetup\n # wait for tear-down from previous script b/c\n # in CI subsequent tests can't find the db host\n sleep 5", " WRK_DIR=$(mktemp -d ./wrk-logs-XXXX)\n chmod go+rwx \"$WRK_DIR\"", " rlRun -t -c \"docker-compose up -d\"\n sleep 10\n rlRun -t -c \"docker exec -i kiwi_web /Kiwi/manage.py migrate\"\n assert_up_and_running\n rlPhaseEnd", " rlPhaseStartTest \"Should not display SSL warning for HTTPS connection\"\n rlRun -t -c \"docker exec -i kiwi_web /Kiwi/manage.py createsuperuser \\\n --username testadmin --email testadmin@domain.com --noinput\"\n rlRun -t -c \"cat tests/set_testadmin_pass.py | docker exec -i kiwi_web /Kiwi/manage.py shell\"", " get_dashboard \"https://localhost\"\n rlAssertNotGrep \"You are not using a secure connection.\" /tmp/testdata.txt\n rlPhaseEnd", " rlPhaseStartTest \"Should allow file upload with UTF-8 filenames\"\n cat > ~/.tcms.conf << _EOF_\n[tcms]\nurl = https://localhost/xml-rpc/\nusername = testadmin\npassword = password\n_EOF_", " rlRun -t -c \"./tests/test_utf8_uploads.py -v\"\n rlPhaseEnd", " rlPhaseStartTest \"Should send ETag header\"\n rlRun -t -c \"curl -k -D- https://localhost/static/images/kiwi_h20.png 2>/dev/null | grep 'ETag'\"\n rlPhaseEnd", " rlPhaseStartTest \"Should NOT send Cache-Control header\"\n rlRun -t -c \"curl -k -D- https://localhost/static/images/kiwi_h20.png 2>/dev/null | grep 'Cache-Control'\" 1\n rlPhaseEnd", " rlPhaseStartTest \"Should send X-Frame-Options header\"\n rlRun -t -c \"curl -k -D- https://localhost 2>/dev/null | grep 'X-Frame-Options: DENY'\"\n rlPhaseEnd", " rlPhaseStartTest \"Should send X-Content-Type-Options header\"\n rlRun -t -c \"curl -k -D- https://localhost 2>/dev/null | grep 'X-Content-Type-Options: nosniff'\"\n rlPhaseEnd\n", " rlPhaseStartTest \"Should send Content-Security-Policy header\"\n rlRun -t -c \"curl -k -D- https://localhost 2>/dev/null | grep $'Content-Security-Policy: script-src \\'self\\' cdn.crowdin.com;'\"\n rlPhaseEnd\n", " rlPhaseStartTest \"Performance baseline for /accounts/register/\"\n exec_wrk \"https://localhost/accounts/login/\" \"$WRK_DIR\" \"register-account-page\"\n rlPhaseEnd", " rlPhaseStartTest \"Performance baseline for /accounts/login/\"\n exec_wrk \"https://localhost/accounts/login/\" \"$WRK_DIR\" \"login-page\"\n rlPhaseEnd", " rlPhaseStartTest \"Performance baseline for /accounts/passwordreset/\"\n exec_wrk \"https://localhost/accounts/login/\" \"$WRK_DIR\" \"password-reset-page\"\n rlPhaseEnd", " rlPhaseStartTest \"Performance baseline for static file\"\n exec_wrk \"https://localhost/static/images/kiwi_h20.png\" \"$WRK_DIR\" \"static-image\"\n rlPhaseEnd", " rlPhaseStartTest \"Performance baseline for / aka dashboard\"\n # Note: the cookies file is created in get_dashboard() above\n SESSION_ID=$(grep sessionid /tmp/login-cookies.txt | cut -f 7)\n exec_wrk \"https://localhost/\" \"$WRK_DIR\" \"dashboard\" \"Cookie: sessionid=$SESSION_ID\"\n rlPhaseEnd", " rlPhaseStartCleanup\n rlRun -t -c \"docker-compose down\"\n rm -f /tmp/testcookies.txt\n rm -f /tmp/testdata.txt\n if [ -n \"$ImageOS\" ]; then\n rlRun -t -c \"docker volume rm kiwi_db_data\"\n fi\n rlPhaseEnd\nrlJournalEnd", "rlJournalPrintText" ]
[ 1, 1, 1, 1, 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": [66, 20, 34, 89], "buggy_code_start_loc": [64, 20, 33, 89], "filenames": ["etc/nginx.conf", "tcms/core/middleware.py", "tcms/settings/devel.py", "tests/test_http.sh"], "fixing_code_end_loc": [69, 38, 37, 94], "fixing_code_start_loc": [65, 21, 33, 90], "message": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kiwitcms:kiwi_tcms:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4287F3C-2839-4274-8D5D-74C9143F1949", "versionEndExcluding": "12.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Kiwi TCMS is an open source test management system for both manual and automated testing. Kiwi TCMS accepts SVG files uploaded by users which could potentially contain JavaScript code. If SVG images are viewed directly, i.e. not rendered in an HTML page, this JavaScript code could execute. This vulnerability has been fixed by configuring Kiwi TCMS to serve with the Content-Security-Policy HTTP header which blocks inline JavaScript in all modern browsers. This configuration change is provided in version 12.1 and users are advised to upgrade. Users unable to upgrade may set their Content-Security-Policy HTTP header manually."}], "evaluatorComment": null, "id": "CVE-2023-27489", "lastModified": "2023-04-06T17:42:45.403", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-03-29T19:15:22.277", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/kiwitcms/Kiwi/security/advisories/GHSA-2wcr-87wf-cf9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kiwitcms/Kiwi/commit/6617cee0fb70cc394b7be6bbc86ef84e6e9de077"}, "type": "CWE-79"}
234
Determine whether the {function_name} code is vulnerable or not.
[ "/* Wireless extensions support.\n *\n * See copyright notice in main.c\n */\n#include <linux/slab.h>\n#include <linux/kernel.h>\n#include <linux/if_arp.h>\n#include <linux/wireless.h>\n#include <linux/ieee80211.h>\n#include <net/iw_handler.h>\n#include <net/cfg80211.h>", "#include \"hermes.h\"\n#include \"hermes_rid.h\"\n#include \"orinoco.h\"", "#include \"hw.h\"\n#include \"mic.h\"\n#include \"scan.h\"\n#include \"main.h\"", "#include \"wext.h\"", "#define MAX_RID_LEN 1024", "/* Helper routine to record keys\n * It is called under orinoco_lock so it may not sleep */\nstatic int orinoco_set_key(struct orinoco_private *priv, int index,\n\t\t\t enum orinoco_alg alg, const u8 *key, int key_len,\n\t\t\t const u8 *seq, int seq_len)\n{\n\tkzfree(priv->keys[index].key);\n\tkzfree(priv->keys[index].seq);", "\tif (key_len) {\n\t\tpriv->keys[index].key = kzalloc(key_len, GFP_ATOMIC);\n\t\tif (!priv->keys[index].key)\n\t\t\tgoto nomem;\n\t} else\n\t\tpriv->keys[index].key = NULL;", "\tif (seq_len) {\n\t\tpriv->keys[index].seq = kzalloc(seq_len, GFP_ATOMIC);\n\t\tif (!priv->keys[index].seq)\n\t\t\tgoto free_key;\n\t} else\n\t\tpriv->keys[index].seq = NULL;", "\tpriv->keys[index].key_len = key_len;\n\tpriv->keys[index].seq_len = seq_len;", "\tif (key_len)\n\t\tmemcpy(priv->keys[index].key, key, key_len);\n\tif (seq_len)\n\t\tmemcpy(priv->keys[index].seq, seq, seq_len);", "\tswitch (alg) {\n\tcase ORINOCO_ALG_TKIP:\n\t\tpriv->keys[index].cipher = WLAN_CIPHER_SUITE_TKIP;\n\t\tbreak;", "\tcase ORINOCO_ALG_WEP:\n\t\tpriv->keys[index].cipher = (key_len > SMALL_KEY_SIZE) ?\n\t\t\tWLAN_CIPHER_SUITE_WEP104 : WLAN_CIPHER_SUITE_WEP40;\n\t\tbreak;", "\tcase ORINOCO_ALG_NONE:\n\tdefault:\n\t\tpriv->keys[index].cipher = 0;\n\t\tbreak;\n\t}", "\treturn 0;", "free_key:\n\tkfree(priv->keys[index].key);\n\tpriv->keys[index].key = NULL;", "nomem:\n\tpriv->keys[index].key_len = 0;\n\tpriv->keys[index].seq_len = 0;\n\tpriv->keys[index].cipher = 0;", "\treturn -ENOMEM;\n}", "static struct iw_statistics *orinoco_get_wireless_stats(struct net_device *dev)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\thermes_t *hw = &priv->hw;\n\tstruct iw_statistics *wstats = &priv->wstats;\n\tint err;\n\tunsigned long flags;", "\tif (!netif_device_present(dev)) {\n\t\tprintk(KERN_WARNING \"%s: get_wireless_stats() called while device not present\\n\",\n\t\t dev->name);\n\t\treturn NULL; /* FIXME: Can we do better than this? */\n\t}", "\t/* If busy, return the old stats. Returning NULL may cause\n\t * the interface to disappear from /proc/net/wireless */\n\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn wstats;", "\t/* We can't really wait for the tallies inquiry command to\n\t * complete, so we just use the previous results and trigger\n\t * a new tallies inquiry command for next time - Jean II */\n\t/* FIXME: Really we should wait for the inquiry to come back -\n\t * as it is the stats we give don't make a whole lot of sense.\n\t * Unfortunately, it's not clear how to do that within the\n\t * wireless extensions framework: I think we're in user\n\t * context, but a lock seems to be held by the time we get in\n\t * here so we're not safe to sleep here. */\n\thermes_inquire(hw, HERMES_INQ_TALLIES);", "\tif (priv->iw_mode == NL80211_IFTYPE_ADHOC) {\n\t\tmemset(&wstats->qual, 0, sizeof(wstats->qual));\n\t\t/* If a spy address is defined, we report stats of the\n\t\t * first spy address - Jean II */\n\t\tif (SPY_NUMBER(priv)) {\n\t\t\twstats->qual.qual = priv->spy_data.spy_stat[0].qual;\n\t\t\twstats->qual.level = priv->spy_data.spy_stat[0].level;\n\t\t\twstats->qual.noise = priv->spy_data.spy_stat[0].noise;\n\t\t\twstats->qual.updated =\n\t\t\t\tpriv->spy_data.spy_stat[0].updated;\n\t\t}\n\t} else {\n\t\tstruct {\n\t\t\t__le16 qual, signal, noise, unused;\n\t\t} __packed cq;", "\t\terr = HERMES_READ_RECORD(hw, USER_BAP,\n\t\t\t\t\t HERMES_RID_COMMSQUALITY, &cq);", "\t\tif (!err) {\n\t\t\twstats->qual.qual = (int)le16_to_cpu(cq.qual);\n\t\t\twstats->qual.level = (int)le16_to_cpu(cq.signal) - 0x95;\n\t\t\twstats->qual.noise = (int)le16_to_cpu(cq.noise) - 0x95;\n\t\t\twstats->qual.updated =\n\t\t\t\tIW_QUAL_ALL_UPDATED | IW_QUAL_DBM;\n\t\t}\n\t}", "\torinoco_unlock(priv, &flags);\n\treturn wstats;\n}", "/********************************************************************/\n/* Wireless extensions */\n/********************************************************************/", "static int orinoco_ioctl_setwap(struct net_device *dev,\n\t\t\t\tstruct iw_request_info *info,\n\t\t\t\tstruct sockaddr *ap_addr,\n\t\t\t\tchar *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint err = -EINPROGRESS;\t\t/* Call commit handler */\n\tunsigned long flags;\n\tstatic const u8 off_addr[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\tstatic const u8 any_addr[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\t/* Enable automatic roaming - no sanity checks are needed */\n\tif (memcmp(&ap_addr->sa_data, off_addr, ETH_ALEN) == 0 ||\n\t memcmp(&ap_addr->sa_data, any_addr, ETH_ALEN) == 0) {\n\t\tpriv->bssid_fixed = 0;\n\t\tmemset(priv->desired_bssid, 0, ETH_ALEN);", "\t\t/* \"off\" means keep existing connection */\n\t\tif (ap_addr->sa_data[0] == 0) {\n\t\t\t__orinoco_hw_set_wap(priv);\n\t\t\terr = 0;\n\t\t}\n\t\tgoto out;\n\t}", "\tif (priv->firmware_type == FIRMWARE_TYPE_AGERE) {\n\t\tprintk(KERN_WARNING \"%s: Lucent/Agere firmware doesn't \"\n\t\t \"support manual roaming\\n\",\n\t\t dev->name);\n\t\terr = -EOPNOTSUPP;\n\t\tgoto out;\n\t}", "\tif (priv->iw_mode != NL80211_IFTYPE_STATION) {\n\t\tprintk(KERN_WARNING \"%s: Manual roaming supported only in \"\n\t\t \"managed mode\\n\", dev->name);\n\t\terr = -EOPNOTSUPP;\n\t\tgoto out;\n\t}", "\t/* Intersil firmware hangs without Desired ESSID */\n\tif (priv->firmware_type == FIRMWARE_TYPE_INTERSIL &&\n\t strlen(priv->desired_essid) == 0) {\n\t\tprintk(KERN_WARNING \"%s: Desired ESSID must be set for \"\n\t\t \"manual roaming\\n\", dev->name);\n\t\terr = -EOPNOTSUPP;\n\t\tgoto out;\n\t}", "\t/* Finally, enable manual roaming */\n\tpriv->bssid_fixed = 1;\n\tmemcpy(priv->desired_bssid, &ap_addr->sa_data, ETH_ALEN);", " out:\n\torinoco_unlock(priv, &flags);\n\treturn err;\n}", "static int orinoco_ioctl_getwap(struct net_device *dev,\n\t\t\t\tstruct iw_request_info *info,\n\t\t\t\tstruct sockaddr *ap_addr,\n\t\t\t\tchar *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);", "\tint err = 0;\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tap_addr->sa_family = ARPHRD_ETHER;\n\terr = orinoco_hw_get_current_bssid(priv, ap_addr->sa_data);", "\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_setiwencode(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_point *erq,\n\t\t\t\t char *keybuf)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint index = (erq->flags & IW_ENCODE_INDEX) - 1;\n\tint setindex = priv->tx_key;\n\tenum orinoco_alg encode_alg = priv->encode_alg;\n\tint restricted = priv->wep_restrict;\n\tint err = -EINPROGRESS;\t\t/* Call commit handler */\n\tunsigned long flags;", "\tif (!priv->has_wep)\n\t\treturn -EOPNOTSUPP;", "\tif (erq->pointer) {\n\t\t/* We actually have a key to set - check its length */\n\t\tif (erq->length > LARGE_KEY_SIZE)\n\t\t\treturn -E2BIG;", "\t\tif ((erq->length > SMALL_KEY_SIZE) && !priv->has_big_wep)\n\t\t\treturn -E2BIG;\n\t}", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\t/* Clear any TKIP key we have */\n\tif ((priv->has_wpa) && (priv->encode_alg == ORINOCO_ALG_TKIP))\n\t\t(void) orinoco_clear_tkip_key(priv, setindex);", "\tif (erq->length > 0) {\n\t\tif ((index < 0) || (index >= ORINOCO_MAX_KEYS))\n\t\t\tindex = priv->tx_key;", "\t\t/* Switch on WEP if off */\n\t\tif (encode_alg != ORINOCO_ALG_WEP) {\n\t\t\tsetindex = index;\n\t\t\tencode_alg = ORINOCO_ALG_WEP;\n\t\t}\n\t} else {\n\t\t/* Important note : if the user do \"iwconfig eth0 enc off\",\n\t\t * we will arrive there with an index of -1. This is valid\n\t\t * but need to be taken care off... Jean II */\n\t\tif ((index < 0) || (index >= ORINOCO_MAX_KEYS)) {\n\t\t\tif ((index != -1) || (erq->flags == 0)) {\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t} else {\n\t\t\t/* Set the index : Check that the key is valid */\n\t\t\tif (priv->keys[index].key_len == 0) {\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tsetindex = index;\n\t\t}\n\t}", "\tif (erq->flags & IW_ENCODE_DISABLED)\n\t\tencode_alg = ORINOCO_ALG_NONE;\n\tif (erq->flags & IW_ENCODE_OPEN)\n\t\trestricted = 0;\n\tif (erq->flags & IW_ENCODE_RESTRICTED)\n\t\trestricted = 1;", "\tif (erq->pointer && erq->length > 0) {\n\t\terr = orinoco_set_key(priv, index, ORINOCO_ALG_WEP, keybuf,\n\t\t\t\t erq->length, NULL, 0);\n\t}\n\tpriv->tx_key = setindex;", "\t/* Try fast key change if connected and only keys are changed */\n\tif ((priv->encode_alg == encode_alg) &&\n\t (priv->wep_restrict == restricted) &&\n\t netif_carrier_ok(dev)) {\n\t\terr = __orinoco_hw_setup_wepkeys(priv);\n\t\t/* No need to commit if successful */\n\t\tgoto out;\n\t}", "\tpriv->encode_alg = encode_alg;\n\tpriv->wep_restrict = restricted;", " out:\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_getiwencode(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_point *erq,\n\t\t\t\t char *keybuf)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint index = (erq->flags & IW_ENCODE_INDEX) - 1;\n\tunsigned long flags;", "\tif (!priv->has_wep)\n\t\treturn -EOPNOTSUPP;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tif ((index < 0) || (index >= ORINOCO_MAX_KEYS))\n\t\tindex = priv->tx_key;", "\terq->flags = 0;\n\tif (!priv->encode_alg)\n\t\terq->flags |= IW_ENCODE_DISABLED;\n\terq->flags |= index + 1;", "\tif (priv->wep_restrict)\n\t\terq->flags |= IW_ENCODE_RESTRICTED;\n\telse\n\t\terq->flags |= IW_ENCODE_OPEN;", "\terq->length = priv->keys[index].key_len;", "\tmemcpy(keybuf, priv->keys[index].key, erq->length);", "\torinoco_unlock(priv, &flags);\n\treturn 0;\n}", "static int orinoco_ioctl_setessid(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_point *erq,\n\t\t\t\t char *essidbuf)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tunsigned long flags;", "\t/* Note : ESSID is ignored in Ad-Hoc demo mode, but we can set it\n\t * anyway... - Jean II */", "\t/* Hum... Should not use Wireless Extension constant (may change),\n\t * should use our own... - Jean II */\n\tif (erq->length > IW_ESSID_MAX_SIZE)\n\t\treturn -E2BIG;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\t/* NULL the string (for NULL termination & ESSID = ANY) - Jean II */\n\tmemset(priv->desired_essid, 0, sizeof(priv->desired_essid));", "\t/* If not ANY, get the new ESSID */\n\tif (erq->flags)\n\t\tmemcpy(priv->desired_essid, essidbuf, erq->length);", "\torinoco_unlock(priv, &flags);", "\treturn -EINPROGRESS;\t\t/* Call commit handler */\n}", "static int orinoco_ioctl_getessid(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_point *erq,\n\t\t\t\t char *essidbuf)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint active;\n\tint err = 0;\n\tunsigned long flags;", "\tif (netif_running(dev)) {\n\t\terr = orinoco_hw_get_essid(priv, &active, essidbuf);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t\terq->length = err;\n\t} else {\n\t\tif (orinoco_lock(priv, &flags) != 0)\n\t\t\treturn -EBUSY;\n\t\tmemcpy(essidbuf, priv->desired_essid, IW_ESSID_MAX_SIZE);\n\t\terq->length = strlen(priv->desired_essid);\n\t\torinoco_unlock(priv, &flags);\n\t}", "\terq->flags = 1;", "\treturn 0;\n}", "static int orinoco_ioctl_setfreq(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_freq *frq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint chan = -1;\n\tunsigned long flags;\n\tint err = -EINPROGRESS;\t\t/* Call commit handler */", "\t/* In infrastructure mode the AP sets the channel */\n\tif (priv->iw_mode == NL80211_IFTYPE_STATION)\n\t\treturn -EBUSY;", "\tif ((frq->e == 0) && (frq->m <= 1000)) {\n\t\t/* Setting by channel number */\n\t\tchan = frq->m;\n\t} else {\n\t\t/* Setting by frequency */\n\t\tint denom = 1;\n\t\tint i;", "\t\t/* Calculate denominator to rescale to MHz */\n\t\tfor (i = 0; i < (6 - frq->e); i++)\n\t\t\tdenom *= 10;", "\t\tchan = ieee80211_freq_to_dsss_chan(frq->m / denom);\n\t}", "\tif ((chan < 1) || (chan > NUM_CHANNELS) ||\n\t !(priv->channel_mask & (1 << (chan-1))))\n\t\treturn -EINVAL;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tpriv->channel = chan;\n\tif (priv->iw_mode == NL80211_IFTYPE_MONITOR) {\n\t\t/* Fast channel change - no commit if successful */\n\t\thermes_t *hw = &priv->hw;\n\t\terr = hw->ops->cmd_wait(hw, HERMES_CMD_TEST |\n\t\t\t\t\t HERMES_TEST_SET_CHANNEL,\n\t\t\t\t\tchan, NULL);\n\t}\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_getfreq(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_freq *frq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint tmp;", "\t/* Locking done in there */\n\ttmp = orinoco_hw_get_freq(priv);\n\tif (tmp < 0)\n\t\treturn tmp;", "\tfrq->m = tmp * 100000;\n\tfrq->e = 1;", "\treturn 0;\n}", "static int orinoco_ioctl_getsens(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *srq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\thermes_t *hw = &priv->hw;\n\tu16 val;\n\tint err;\n\tunsigned long flags;", "\tif (!priv->has_sensitivity)\n\t\treturn -EOPNOTSUPP;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;\n\terr = hermes_read_wordrec(hw, USER_BAP,\n\t\t\t\t HERMES_RID_CNFSYSTEMSCALE, &val);\n\torinoco_unlock(priv, &flags);", "\tif (err)\n\t\treturn err;", "\tsrq->value = val;\n\tsrq->fixed = 0; /* auto */", "\treturn 0;\n}", "static int orinoco_ioctl_setsens(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *srq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint val = srq->value;\n\tunsigned long flags;", "\tif (!priv->has_sensitivity)\n\t\treturn -EOPNOTSUPP;", "\tif ((val < 1) || (val > 3))\n\t\treturn -EINVAL;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;\n\tpriv->ap_density = val;\n\torinoco_unlock(priv, &flags);", "\treturn -EINPROGRESS;\t\t/* Call commit handler */\n}", "static int orinoco_ioctl_setrate(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *rrq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint ratemode;\n\tint bitrate; /* 100s of kilobits */\n\tunsigned long flags;", "\t/* As the user space doesn't know our highest rate, it uses -1\n\t * to ask us to set the highest rate. Test it using \"iwconfig\n\t * ethX rate auto\" - Jean II */\n\tif (rrq->value == -1)\n\t\tbitrate = 110;\n\telse {\n\t\tif (rrq->value % 100000)\n\t\t\treturn -EINVAL;\n\t\tbitrate = rrq->value / 100000;\n\t}", "\tratemode = orinoco_get_bitratemode(bitrate, !rrq->fixed);", "\tif (ratemode == -1)\n\t\treturn -EINVAL;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;\n\tpriv->bitratemode = ratemode;\n\torinoco_unlock(priv, &flags);", "\treturn -EINPROGRESS;\n}", "static int orinoco_ioctl_getrate(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *rrq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint err = 0;\n\tint bitrate, automatic;\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\torinoco_get_ratemode_cfg(priv->bitratemode, &bitrate, &automatic);", "\t/* If the interface is running we try to find more about the\n\t current mode */\n\tif (netif_running(dev)) {\n\t\tint act_bitrate;\n\t\tint lerr;", "\t\t/* Ignore errors if we can't get the actual bitrate */\n\t\tlerr = orinoco_hw_get_act_bitrate(priv, &act_bitrate);\n\t\tif (!lerr)\n\t\t\tbitrate = act_bitrate;\n\t}", "\torinoco_unlock(priv, &flags);", "\trrq->value = bitrate;\n\trrq->fixed = !automatic;\n\trrq->disabled = 0;", "\treturn err;\n}", "static int orinoco_ioctl_setpower(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *prq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint err = -EINPROGRESS;\t\t/* Call commit handler */\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tif (prq->disabled) {\n\t\tpriv->pm_on = 0;\n\t} else {\n\t\tswitch (prq->flags & IW_POWER_MODE) {\n\t\tcase IW_POWER_UNICAST_R:\n\t\t\tpriv->pm_mcast = 0;\n\t\t\tpriv->pm_on = 1;\n\t\t\tbreak;\n\t\tcase IW_POWER_ALL_R:\n\t\t\tpriv->pm_mcast = 1;\n\t\t\tpriv->pm_on = 1;\n\t\t\tbreak;\n\t\tcase IW_POWER_ON:\n\t\t\t/* No flags : but we may have a value - Jean II */\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terr = -EINVAL;\n\t\t\tgoto out;\n\t\t}", "\t\tif (prq->flags & IW_POWER_TIMEOUT) {\n\t\t\tpriv->pm_on = 1;\n\t\t\tpriv->pm_timeout = prq->value / 1000;\n\t\t}\n\t\tif (prq->flags & IW_POWER_PERIOD) {\n\t\t\tpriv->pm_on = 1;\n\t\t\tpriv->pm_period = prq->value / 1000;\n\t\t}\n\t\t/* It's valid to not have a value if we are just toggling\n\t\t * the flags... Jean II */\n\t\tif (!priv->pm_on) {\n\t\t\terr = -EINVAL;\n\t\t\tgoto out;\n\t\t}\n\t}", " out:\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_getpower(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *prq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\thermes_t *hw = &priv->hw;\n\tint err = 0;\n\tu16 enable, period, timeout, mcast;\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\terr = hermes_read_wordrec(hw, USER_BAP,\n\t\t\t\t HERMES_RID_CNFPMENABLED, &enable);\n\tif (err)\n\t\tgoto out;", "\terr = hermes_read_wordrec(hw, USER_BAP,\n\t\t\t\t HERMES_RID_CNFMAXSLEEPDURATION, &period);\n\tif (err)\n\t\tgoto out;", "\terr = hermes_read_wordrec(hw, USER_BAP,\n\t\t\t\t HERMES_RID_CNFPMHOLDOVERDURATION, &timeout);\n\tif (err)\n\t\tgoto out;", "\terr = hermes_read_wordrec(hw, USER_BAP,\n\t\t\t\t HERMES_RID_CNFMULTICASTRECEIVE, &mcast);\n\tif (err)\n\t\tgoto out;", "\tprq->disabled = !enable;\n\t/* Note : by default, display the period */\n\tif ((prq->flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {\n\t\tprq->flags = IW_POWER_TIMEOUT;\n\t\tprq->value = timeout * 1000;\n\t} else {\n\t\tprq->flags = IW_POWER_PERIOD;\n\t\tprq->value = period * 1000;\n\t}\n\tif (mcast)\n\t\tprq->flags |= IW_POWER_ALL_R;\n\telse\n\t\tprq->flags |= IW_POWER_UNICAST_R;", " out:\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_set_encodeext(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tstruct iw_point *encoding = &wrqu->encoding;\n\tstruct iw_encode_ext *ext = (struct iw_encode_ext *)extra;\n\tint idx, alg = ext->alg, set_key = 1;\n\tunsigned long flags;\n\tint err = -EINVAL;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\t/* Determine and validate the key index */\n\tidx = encoding->flags & IW_ENCODE_INDEX;\n\tif (idx) {\n\t\tif ((idx < 1) || (idx > 4))\n\t\t\tgoto out;\n\t\tidx--;\n\t} else\n\t\tidx = priv->tx_key;", "\tif (encoding->flags & IW_ENCODE_DISABLED)\n\t\talg = IW_ENCODE_ALG_NONE;", "\tif (priv->has_wpa && (alg != IW_ENCODE_ALG_TKIP)) {\n\t\t/* Clear any TKIP TX key we had */\n\t\t(void) orinoco_clear_tkip_key(priv, priv->tx_key);\n\t}", "\tif (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY) {\n\t\tpriv->tx_key = idx;\n\t\tset_key = ((alg == IW_ENCODE_ALG_TKIP) ||\n\t\t\t (ext->key_len > 0)) ? 1 : 0;\n\t}", "\tif (set_key) {\n\t\t/* Set the requested key first */\n\t\tswitch (alg) {\n\t\tcase IW_ENCODE_ALG_NONE:\n\t\t\tpriv->encode_alg = ORINOCO_ALG_NONE;\n\t\t\terr = orinoco_set_key(priv, idx, ORINOCO_ALG_NONE,\n\t\t\t\t\t NULL, 0, NULL, 0);\n\t\t\tbreak;", "\t\tcase IW_ENCODE_ALG_WEP:\n\t\t\tif (ext->key_len <= 0)\n\t\t\t\tgoto out;", "\t\t\tpriv->encode_alg = ORINOCO_ALG_WEP;\n\t\t\terr = orinoco_set_key(priv, idx, ORINOCO_ALG_WEP,\n\t\t\t\t\t ext->key, ext->key_len, NULL, 0);\n\t\t\tbreak;", "\t\tcase IW_ENCODE_ALG_TKIP:\n\t\t{\n\t\t\tu8 *tkip_iv = NULL;", "\t\t\tif (!priv->has_wpa ||\n\t\t\t (ext->key_len > sizeof(struct orinoco_tkip_key)))\n\t\t\t\tgoto out;", "\t\t\tpriv->encode_alg = ORINOCO_ALG_TKIP;", "\t\t\tif (ext->ext_flags & IW_ENCODE_EXT_RX_SEQ_VALID)\n\t\t\t\ttkip_iv = &ext->rx_seq[0];", "\t\t\terr = orinoco_set_key(priv, idx, ORINOCO_ALG_TKIP,\n\t\t\t\t\t ext->key, ext->key_len, tkip_iv,\n\t\t\t\t\t ORINOCO_SEQ_LEN);", "\t\t\terr = __orinoco_hw_set_tkip_key(priv, idx,\n\t\t\t\t ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY,\n\t\t\t\t priv->keys[idx].key,\n\t\t\t\t tkip_iv, ORINOCO_SEQ_LEN, NULL, 0);\n\t\t\tif (err)\n\t\t\t\tprintk(KERN_ERR \"%s: Error %d setting TKIP key\"\n\t\t\t\t \"\\n\", dev->name, err);", "\t\t\tgoto out;\n\t\t}\n\t\tdefault:\n\t\t\tgoto out;\n\t\t}\n\t}\n\terr = -EINPROGRESS;\n out:\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_get_encodeext(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tstruct iw_point *encoding = &wrqu->encoding;\n\tstruct iw_encode_ext *ext = (struct iw_encode_ext *)extra;\n\tint idx, max_key_len;\n\tunsigned long flags;\n\tint err;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\terr = -EINVAL;\n\tmax_key_len = encoding->length - sizeof(*ext);\n\tif (max_key_len < 0)\n\t\tgoto out;", "\tidx = encoding->flags & IW_ENCODE_INDEX;\n\tif (idx) {\n\t\tif ((idx < 1) || (idx > 4))\n\t\t\tgoto out;\n\t\tidx--;\n\t} else\n\t\tidx = priv->tx_key;", "\tencoding->flags = idx + 1;\n\tmemset(ext, 0, sizeof(*ext));", "\tswitch (priv->encode_alg) {\n\tcase ORINOCO_ALG_NONE:\n\t\text->alg = IW_ENCODE_ALG_NONE;\n\t\text->key_len = 0;\n\t\tencoding->flags |= IW_ENCODE_DISABLED;\n\t\tbreak;\n\tcase ORINOCO_ALG_WEP:\n\t\text->alg = IW_ENCODE_ALG_WEP;\n\t\text->key_len = min(priv->keys[idx].key_len, max_key_len);\n\t\tmemcpy(ext->key, priv->keys[idx].key, ext->key_len);\n\t\tencoding->flags |= IW_ENCODE_ENABLED;\n\t\tbreak;\n\tcase ORINOCO_ALG_TKIP:\n\t\text->alg = IW_ENCODE_ALG_TKIP;\n\t\text->key_len = min(priv->keys[idx].key_len, max_key_len);\n\t\tmemcpy(ext->key, priv->keys[idx].key, ext->key_len);\n\t\tencoding->flags |= IW_ENCODE_ENABLED;\n\t\tbreak;\n\t}", "\terr = 0;\n out:\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_set_auth(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu, char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\thermes_t *hw = &priv->hw;\n\tstruct iw_param *param = &wrqu->param;\n\tunsigned long flags;\n\tint ret = -EINPROGRESS;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tswitch (param->flags & IW_AUTH_INDEX) {\n\tcase IW_AUTH_WPA_VERSION:\n\tcase IW_AUTH_CIPHER_PAIRWISE:\n\tcase IW_AUTH_CIPHER_GROUP:\n\tcase IW_AUTH_RX_UNENCRYPTED_EAPOL:\n\tcase IW_AUTH_PRIVACY_INVOKED:\n\tcase IW_AUTH_DROP_UNENCRYPTED:\n\t\t/*\n\t\t * orinoco does not use these parameters\n\t\t */\n\t\tbreak;", "\tcase IW_AUTH_KEY_MGMT:\n\t\t/* wl_lkm implies value 2 == PSK for Hermes I\n\t\t * which ties in with WEXT\n\t\t * no other hints tho :(\n\t\t */\n\t\tpriv->key_mgmt = param->value;\n\t\tbreak;", "\tcase IW_AUTH_TKIP_COUNTERMEASURES:\n\t\t/* When countermeasures are enabled, shut down the\n\t\t * card; when disabled, re-enable the card. This must\n\t\t * take effect immediately.\n\t\t *\n\t\t * TODO: Make sure that the EAPOL message is getting\n\t\t * out before card disabled\n\t\t */\n\t\tif (param->value) {\n\t\t\tpriv->tkip_cm_active = 1;", "\t\t\tret = hermes_enable_port(hw, 0);", "\t\t} else {\n\t\t\tpriv->tkip_cm_active = 0;", "\t\t\tret = hermes_disable_port(hw, 0);", "\t\t}\n\t\tbreak;", "\tcase IW_AUTH_80211_AUTH_ALG:\n\t\tif (param->value & IW_AUTH_ALG_SHARED_KEY)\n\t\t\tpriv->wep_restrict = 1;\n\t\telse if (param->value & IW_AUTH_ALG_OPEN_SYSTEM)\n\t\t\tpriv->wep_restrict = 0;\n\t\telse\n\t\t\tret = -EINVAL;\n\t\tbreak;", "\tcase IW_AUTH_WPA_ENABLED:\n\t\tif (priv->has_wpa) {\n\t\t\tpriv->wpa_enabled = param->value ? 1 : 0;\n\t\t} else {\n\t\t\tif (param->value)\n\t\t\t\tret = -EOPNOTSUPP;\n\t\t\t/* else silently accept disable of WPA */\n\t\t\tpriv->wpa_enabled = 0;\n\t\t}\n\t\tbreak;", "\tdefault:\n\t\tret = -EOPNOTSUPP;\n\t}", "\torinoco_unlock(priv, &flags);\n\treturn ret;\n}", "static int orinoco_ioctl_get_auth(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu, char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tstruct iw_param *param = &wrqu->param;\n\tunsigned long flags;\n\tint ret = 0;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tswitch (param->flags & IW_AUTH_INDEX) {\n\tcase IW_AUTH_KEY_MGMT:\n\t\tparam->value = priv->key_mgmt;\n\t\tbreak;", "\tcase IW_AUTH_TKIP_COUNTERMEASURES:\n\t\tparam->value = priv->tkip_cm_active;\n\t\tbreak;", "\tcase IW_AUTH_80211_AUTH_ALG:\n\t\tif (priv->wep_restrict)\n\t\t\tparam->value = IW_AUTH_ALG_SHARED_KEY;\n\t\telse\n\t\t\tparam->value = IW_AUTH_ALG_OPEN_SYSTEM;\n\t\tbreak;", "\tcase IW_AUTH_WPA_ENABLED:\n\t\tparam->value = priv->wpa_enabled;\n\t\tbreak;", "\tdefault:\n\t\tret = -EOPNOTSUPP;\n\t}", "\torinoco_unlock(priv, &flags);\n\treturn ret;\n}", "static int orinoco_ioctl_set_genie(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu, char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tu8 *buf;\n\tunsigned long flags;", "\t/* cut off at IEEE80211_MAX_DATA_LEN */\n\tif ((wrqu->data.length > IEEE80211_MAX_DATA_LEN) ||\n\t (wrqu->data.length && (extra == NULL)))\n\t\treturn -EINVAL;", "\tif (wrqu->data.length) {\n\t\tbuf = kmemdup(extra, wrqu->data.length, GFP_KERNEL);\n\t\tif (buf == NULL)\n\t\t\treturn -ENOMEM;\n\t} else\n\t\tbuf = NULL;", "\tif (orinoco_lock(priv, &flags) != 0) {\n\t\tkfree(buf);\n\t\treturn -EBUSY;\n\t}", "\tkfree(priv->wpa_ie);\n\tpriv->wpa_ie = buf;\n\tpriv->wpa_ie_len = wrqu->data.length;", "\tif (priv->wpa_ie) {\n\t\t/* Looks like wl_lkm wants to check the auth alg, and\n\t\t * somehow pass it to the firmware.\n\t\t * Instead it just calls the key mgmt rid\n\t\t * - we do this in set auth.\n\t\t */\n\t}", "\torinoco_unlock(priv, &flags);\n\treturn 0;\n}", "static int orinoco_ioctl_get_genie(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu, char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tunsigned long flags;\n\tint err = 0;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tif ((priv->wpa_ie_len == 0) || (priv->wpa_ie == NULL)) {\n\t\twrqu->data.length = 0;\n\t\tgoto out;\n\t}", "\tif (wrqu->data.length < priv->wpa_ie_len) {\n\t\terr = -E2BIG;\n\t\tgoto out;\n\t}", "\twrqu->data.length = priv->wpa_ie_len;\n\tmemcpy(extra, priv->wpa_ie, priv->wpa_ie_len);", "out:\n\torinoco_unlock(priv, &flags);\n\treturn err;\n}", "static int orinoco_ioctl_set_mlme(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu, char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tstruct iw_mlme *mlme = (struct iw_mlme *)extra;\n\tunsigned long flags;\n\tint ret = 0;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tswitch (mlme->cmd) {\n\tcase IW_MLME_DEAUTH:\n\t\t/* silently ignore */\n\t\tbreak;", "\tcase IW_MLME_DISASSOC:", "\t\tret = orinoco_hw_disassociate(priv, mlme->addr.sa_data,\n\t\t\t\t\t mlme->reason_code);\n\t\tbreak;", "\tdefault:\n\t\tret = -EOPNOTSUPP;\n\t}", "\torinoco_unlock(priv, &flags);\n\treturn ret;\n}", "static int orinoco_ioctl_reset(struct net_device *dev,\n\t\t\t struct iw_request_info *info,\n\t\t\t void *wrqu,\n\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);", "\tif (!capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;", "\tif (info->cmd == (SIOCIWFIRSTPRIV + 0x1)) {\n\t\tprintk(KERN_DEBUG \"%s: Forcing reset!\\n\", dev->name);", "\t\t/* Firmware reset */\n\t\torinoco_reset(&priv->reset_work);\n\t} else {\n\t\tprintk(KERN_DEBUG \"%s: Force scheduling reset!\\n\", dev->name);", "\t\tschedule_work(&priv->reset_work);\n\t}", "\treturn 0;\n}", "static int orinoco_ioctl_setibssport(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)", "{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint val = *((int *) extra);\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tpriv->ibss_port = val;", "\t/* Actually update the mode we are using */\n\tset_port_type(priv);", "\torinoco_unlock(priv, &flags);\n\treturn -EINPROGRESS;\t\t/* Call commit handler */\n}", "static int orinoco_ioctl_getibssport(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint *val = (int *) extra;", "\t*val = priv->ibss_port;\n\treturn 0;\n}", "static int orinoco_ioctl_setport3(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint val = *((int *) extra);\n\tint err = 0;\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tswitch (val) {\n\tcase 0: /* Try to do IEEE ad-hoc mode */\n\t\tif (!priv->has_ibss) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t\tpriv->prefer_port3 = 0;", "\t\tbreak;", "\tcase 1: /* Try to do Lucent proprietary ad-hoc mode */\n\t\tif (!priv->has_port3) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t\tpriv->prefer_port3 = 1;\n\t\tbreak;", "\tdefault:\n\t\terr = -EINVAL;\n\t}", "\tif (!err) {\n\t\t/* Actually update the mode we are using */\n\t\tset_port_type(priv);\n\t\terr = -EINPROGRESS;\n\t}", "\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_getport3(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint *val = (int *) extra;", "\t*val = priv->prefer_port3;\n\treturn 0;\n}", "static int orinoco_ioctl_setpreamble(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tunsigned long flags;\n\tint val;", "\tif (!priv->has_preamble)\n\t\treturn -EOPNOTSUPP;", "\t/* 802.11b has recently defined some short preamble.\n\t * Basically, the Phy header has been reduced in size.\n\t * This increase performance, especially at high rates\n\t * (the preamble is transmitted at 1Mb/s), unfortunately\n\t * this give compatibility troubles... - Jean II */\n\tval = *((int *) extra);", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tif (val)\n\t\tpriv->preamble = 1;\n\telse\n\t\tpriv->preamble = 0;", "\torinoco_unlock(priv, &flags);", "\treturn -EINPROGRESS;\t\t/* Call commit handler */\n}", "static int orinoco_ioctl_getpreamble(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint *val = (int *) extra;", "\tif (!priv->has_preamble)\n\t\treturn -EOPNOTSUPP;", "\t*val = priv->preamble;\n\treturn 0;\n}", "/* ioctl interface to hermes_read_ltv()\n * To use with iwpriv, pass the RID as the token argument, e.g.\n * iwpriv get_rid [0xfc00]\n * At least Wireless Tools 25 is required to use iwpriv.\n * For Wireless Tools 25 and 26 append \"dummy\" are the end. */\nstatic int orinoco_ioctl_getrid(struct net_device *dev,\n\t\t\t\tstruct iw_request_info *info,\n\t\t\t\tstruct iw_point *data,\n\t\t\t\tchar *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\thermes_t *hw = &priv->hw;\n\tint rid = data->flags;\n\tu16 length;\n\tint err;\n\tunsigned long flags;", "\t/* It's a \"get\" function, but we don't want users to access the\n\t * WEP key and other raw firmware data */\n\tif (!capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;", "\tif (rid < 0xfc00 || rid > 0xffff)\n\t\treturn -EINVAL;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\terr = hw->ops->read_ltv(hw, USER_BAP, rid, MAX_RID_LEN, &length,\n\t\t\t\textra);\n\tif (err)\n\t\tgoto out;", "\tdata->length = min_t(u16, HERMES_RECLEN_TO_BYTES(length),\n\t\t\t MAX_RID_LEN);", " out:\n\torinoco_unlock(priv, &flags);\n\treturn err;\n}", "\n/* Commit handler, called after set operations */\nstatic int orinoco_ioctl_commit(struct net_device *dev,\n\t\t\t\tstruct iw_request_info *info,\n\t\t\t\tvoid *wrqu,\n\t\t\t\tchar *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tunsigned long flags;\n\tint err = 0;", "\tif (!priv->open)\n\t\treturn 0;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn err;", "\terr = orinoco_commit(priv);", "\torinoco_unlock(priv, &flags);\n\treturn err;\n}", "static const struct iw_priv_args orinoco_privtab[] = {\n\t{ SIOCIWFIRSTPRIV + 0x0, 0, 0, \"force_reset\" },\n\t{ SIOCIWFIRSTPRIV + 0x1, 0, 0, \"card_reset\" },\n\t{ SIOCIWFIRSTPRIV + 0x2, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t 0, \"set_port3\" },\n\t{ SIOCIWFIRSTPRIV + 0x3, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t \"get_port3\" },\n\t{ SIOCIWFIRSTPRIV + 0x4, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t 0, \"set_preamble\" },\n\t{ SIOCIWFIRSTPRIV + 0x5, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t \"get_preamble\" },\n\t{ SIOCIWFIRSTPRIV + 0x6, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t 0, \"set_ibssport\" },\n\t{ SIOCIWFIRSTPRIV + 0x7, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t \"get_ibssport\" },\n\t{ SIOCIWFIRSTPRIV + 0x9, 0, IW_PRIV_TYPE_BYTE | MAX_RID_LEN,\n\t \"get_rid\" },\n};", "\n/*\n * Structures to export the Wireless Handlers\n */", "static const iw_handler\torinoco_handler[] = {\n\tIW_HANDLER(SIOCSIWCOMMIT,\t(iw_handler)orinoco_ioctl_commit),\n\tIW_HANDLER(SIOCGIWNAME,\t\t(iw_handler)cfg80211_wext_giwname),\n\tIW_HANDLER(SIOCSIWFREQ,\t\t(iw_handler)orinoco_ioctl_setfreq),\n\tIW_HANDLER(SIOCGIWFREQ,\t\t(iw_handler)orinoco_ioctl_getfreq),\n\tIW_HANDLER(SIOCSIWMODE,\t\t(iw_handler)cfg80211_wext_siwmode),\n\tIW_HANDLER(SIOCGIWMODE,\t\t(iw_handler)cfg80211_wext_giwmode),\n\tIW_HANDLER(SIOCSIWSENS,\t\t(iw_handler)orinoco_ioctl_setsens),\n\tIW_HANDLER(SIOCGIWSENS,\t\t(iw_handler)orinoco_ioctl_getsens),\n\tIW_HANDLER(SIOCGIWRANGE,\t(iw_handler)cfg80211_wext_giwrange),\n\tIW_HANDLER(SIOCSIWSPY,\t\tiw_handler_set_spy),\n\tIW_HANDLER(SIOCGIWSPY,\t\tiw_handler_get_spy),\n\tIW_HANDLER(SIOCSIWTHRSPY,\tiw_handler_set_thrspy),\n\tIW_HANDLER(SIOCGIWTHRSPY,\tiw_handler_get_thrspy),\n\tIW_HANDLER(SIOCSIWAP,\t\t(iw_handler)orinoco_ioctl_setwap),\n\tIW_HANDLER(SIOCGIWAP,\t\t(iw_handler)orinoco_ioctl_getwap),\n\tIW_HANDLER(SIOCSIWSCAN,\t\t(iw_handler)cfg80211_wext_siwscan),\n\tIW_HANDLER(SIOCGIWSCAN,\t\t(iw_handler)cfg80211_wext_giwscan),\n\tIW_HANDLER(SIOCSIWESSID,\t(iw_handler)orinoco_ioctl_setessid),\n\tIW_HANDLER(SIOCGIWESSID,\t(iw_handler)orinoco_ioctl_getessid),\n\tIW_HANDLER(SIOCSIWRATE,\t\t(iw_handler)orinoco_ioctl_setrate),\n\tIW_HANDLER(SIOCGIWRATE,\t\t(iw_handler)orinoco_ioctl_getrate),\n\tIW_HANDLER(SIOCSIWRTS,\t\t(iw_handler)cfg80211_wext_siwrts),\n\tIW_HANDLER(SIOCGIWRTS,\t\t(iw_handler)cfg80211_wext_giwrts),\n\tIW_HANDLER(SIOCSIWFRAG,\t\t(iw_handler)cfg80211_wext_siwfrag),\n\tIW_HANDLER(SIOCGIWFRAG,\t\t(iw_handler)cfg80211_wext_giwfrag),\n\tIW_HANDLER(SIOCGIWRETRY,\t(iw_handler)cfg80211_wext_giwretry),\n\tIW_HANDLER(SIOCSIWENCODE,\t(iw_handler)orinoco_ioctl_setiwencode),\n\tIW_HANDLER(SIOCGIWENCODE,\t(iw_handler)orinoco_ioctl_getiwencode),\n\tIW_HANDLER(SIOCSIWPOWER,\t(iw_handler)orinoco_ioctl_setpower),\n\tIW_HANDLER(SIOCGIWPOWER,\t(iw_handler)orinoco_ioctl_getpower),\n\tIW_HANDLER(SIOCSIWGENIE,\torinoco_ioctl_set_genie),\n\tIW_HANDLER(SIOCGIWGENIE,\torinoco_ioctl_get_genie),\n\tIW_HANDLER(SIOCSIWMLME,\t\torinoco_ioctl_set_mlme),\n\tIW_HANDLER(SIOCSIWAUTH,\t\torinoco_ioctl_set_auth),\n\tIW_HANDLER(SIOCGIWAUTH,\t\torinoco_ioctl_get_auth),\n\tIW_HANDLER(SIOCSIWENCODEEXT,\torinoco_ioctl_set_encodeext),\n\tIW_HANDLER(SIOCGIWENCODEEXT,\torinoco_ioctl_get_encodeext),\n};", "\n/*\n Added typecasting since we no longer use iwreq_data -- Moustafa\n */\nstatic const iw_handler\torinoco_private_handler[] = {\n\t[0] = (iw_handler)orinoco_ioctl_reset,\n\t[1] = (iw_handler)orinoco_ioctl_reset,\n\t[2] = (iw_handler)orinoco_ioctl_setport3,\n\t[3] = (iw_handler)orinoco_ioctl_getport3,\n\t[4] = (iw_handler)orinoco_ioctl_setpreamble,\n\t[5] = (iw_handler)orinoco_ioctl_getpreamble,\n\t[6] = (iw_handler)orinoco_ioctl_setibssport,\n\t[7] = (iw_handler)orinoco_ioctl_getibssport,\n\t[9] = (iw_handler)orinoco_ioctl_getrid,\n};", "const struct iw_handler_def orinoco_handler_def = {\n\t.num_standard = ARRAY_SIZE(orinoco_handler),\n\t.num_private = ARRAY_SIZE(orinoco_private_handler),\n\t.num_private_args = ARRAY_SIZE(orinoco_privtab),\n\t.standard = orinoco_handler,\n\t.private = orinoco_private_handler,\n\t.private_args = orinoco_privtab,\n\t.get_wireless_stats = orinoco_get_wireless_stats,\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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [918], "buggy_code_start_loc": [914], "filenames": ["drivers/net/wireless/orinoco/wext.c"], "fixing_code_end_loc": [918], "fixing_code_start_loc": [914], "message": "The orinoco_ioctl_set_auth function in drivers/net/wireless/orinoco/wext.c in the Linux kernel before 2.6.37 does not properly implement a TKIP protection mechanism, which makes it easier for remote attackers to obtain access to a Wi-Fi network by reading Wi-Fi frames.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "C03086A2-8EEE-40E3-9A7F-A5303FBF0472", "versionEndExcluding": null, "versionEndIncluding": "2.6.36.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:2.6.36.1:*:*:*:*:*:*:*", "matchCriteriaId": "907A3F7F-B11D-4CF1-A1B2-A28BBEBF03C3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:2.6.36.2:*:*:*:*:*:*:*", "matchCriteriaId": "EE4657B8-B691-4833-8546-220AD2BA8A7D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:2.6.36.3:*:*:*:*:*:*:*", "matchCriteriaId": "A2455F37-66D8-4BE1-8739-1A20A2E5375D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The orinoco_ioctl_set_auth function in drivers/net/wireless/orinoco/wext.c in the Linux kernel before 2.6.37 does not properly implement a TKIP protection mechanism, which makes it easier for remote attackers to obtain access to a Wi-Fi network by reading Wi-Fi frames."}, {"lang": "es", "value": "La funci\u00f3n de orinoco_ioctl_set_auth en drivers/net/wireless/orinoco/wext.c en el kernel de Linux en vesiones anteriores a la v2.6.37 no implementa un mecanismo de protecci\u00f3n TKIP, lo que facilita a los atacantes remotos a la hora de obtener acceso a una red Wi-Fi mediante la lectura de frames Wi-Fi."}], "evaluatorComment": null, "id": "CVE-2010-4648", "lastModified": "2023-02-13T03:20:33.853", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 3.3, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:A/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.5, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2012-06-21T23:55:01.693", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://ftp.osuosl.org/pub/linux/kernel/v2.6/ChangeLog-2.6.37"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git%3Ba=commit%3Bh=0a54917c3fc295cb61f3fb52373c173fd3b69f48"}, {"source": "secalert@redhat.com", "tags": ["Patch"], "url": "http://www.openwall.com/lists/oss-security/2011/01/06/18"}, {"source": "secalert@redhat.com", "tags": ["Patch"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=667907"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch"], "url": "https://github.com/torvalds/linux/commit/0a54917c3fc295cb61f3fb52373c173fd3b69f48"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/0a54917c3fc295cb61f3fb52373c173fd3b69f48"}, "type": "NVD-CWE-noinfo"}
235
Determine whether the {function_name} code is vulnerable or not.
[ "/* Wireless extensions support.\n *\n * See copyright notice in main.c\n */\n#include <linux/slab.h>\n#include <linux/kernel.h>\n#include <linux/if_arp.h>\n#include <linux/wireless.h>\n#include <linux/ieee80211.h>\n#include <net/iw_handler.h>\n#include <net/cfg80211.h>", "#include \"hermes.h\"\n#include \"hermes_rid.h\"\n#include \"orinoco.h\"", "#include \"hw.h\"\n#include \"mic.h\"\n#include \"scan.h\"\n#include \"main.h\"", "#include \"wext.h\"", "#define MAX_RID_LEN 1024", "/* Helper routine to record keys\n * It is called under orinoco_lock so it may not sleep */\nstatic int orinoco_set_key(struct orinoco_private *priv, int index,\n\t\t\t enum orinoco_alg alg, const u8 *key, int key_len,\n\t\t\t const u8 *seq, int seq_len)\n{\n\tkzfree(priv->keys[index].key);\n\tkzfree(priv->keys[index].seq);", "\tif (key_len) {\n\t\tpriv->keys[index].key = kzalloc(key_len, GFP_ATOMIC);\n\t\tif (!priv->keys[index].key)\n\t\t\tgoto nomem;\n\t} else\n\t\tpriv->keys[index].key = NULL;", "\tif (seq_len) {\n\t\tpriv->keys[index].seq = kzalloc(seq_len, GFP_ATOMIC);\n\t\tif (!priv->keys[index].seq)\n\t\t\tgoto free_key;\n\t} else\n\t\tpriv->keys[index].seq = NULL;", "\tpriv->keys[index].key_len = key_len;\n\tpriv->keys[index].seq_len = seq_len;", "\tif (key_len)\n\t\tmemcpy(priv->keys[index].key, key, key_len);\n\tif (seq_len)\n\t\tmemcpy(priv->keys[index].seq, seq, seq_len);", "\tswitch (alg) {\n\tcase ORINOCO_ALG_TKIP:\n\t\tpriv->keys[index].cipher = WLAN_CIPHER_SUITE_TKIP;\n\t\tbreak;", "\tcase ORINOCO_ALG_WEP:\n\t\tpriv->keys[index].cipher = (key_len > SMALL_KEY_SIZE) ?\n\t\t\tWLAN_CIPHER_SUITE_WEP104 : WLAN_CIPHER_SUITE_WEP40;\n\t\tbreak;", "\tcase ORINOCO_ALG_NONE:\n\tdefault:\n\t\tpriv->keys[index].cipher = 0;\n\t\tbreak;\n\t}", "\treturn 0;", "free_key:\n\tkfree(priv->keys[index].key);\n\tpriv->keys[index].key = NULL;", "nomem:\n\tpriv->keys[index].key_len = 0;\n\tpriv->keys[index].seq_len = 0;\n\tpriv->keys[index].cipher = 0;", "\treturn -ENOMEM;\n}", "static struct iw_statistics *orinoco_get_wireless_stats(struct net_device *dev)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\thermes_t *hw = &priv->hw;\n\tstruct iw_statistics *wstats = &priv->wstats;\n\tint err;\n\tunsigned long flags;", "\tif (!netif_device_present(dev)) {\n\t\tprintk(KERN_WARNING \"%s: get_wireless_stats() called while device not present\\n\",\n\t\t dev->name);\n\t\treturn NULL; /* FIXME: Can we do better than this? */\n\t}", "\t/* If busy, return the old stats. Returning NULL may cause\n\t * the interface to disappear from /proc/net/wireless */\n\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn wstats;", "\t/* We can't really wait for the tallies inquiry command to\n\t * complete, so we just use the previous results and trigger\n\t * a new tallies inquiry command for next time - Jean II */\n\t/* FIXME: Really we should wait for the inquiry to come back -\n\t * as it is the stats we give don't make a whole lot of sense.\n\t * Unfortunately, it's not clear how to do that within the\n\t * wireless extensions framework: I think we're in user\n\t * context, but a lock seems to be held by the time we get in\n\t * here so we're not safe to sleep here. */\n\thermes_inquire(hw, HERMES_INQ_TALLIES);", "\tif (priv->iw_mode == NL80211_IFTYPE_ADHOC) {\n\t\tmemset(&wstats->qual, 0, sizeof(wstats->qual));\n\t\t/* If a spy address is defined, we report stats of the\n\t\t * first spy address - Jean II */\n\t\tif (SPY_NUMBER(priv)) {\n\t\t\twstats->qual.qual = priv->spy_data.spy_stat[0].qual;\n\t\t\twstats->qual.level = priv->spy_data.spy_stat[0].level;\n\t\t\twstats->qual.noise = priv->spy_data.spy_stat[0].noise;\n\t\t\twstats->qual.updated =\n\t\t\t\tpriv->spy_data.spy_stat[0].updated;\n\t\t}\n\t} else {\n\t\tstruct {\n\t\t\t__le16 qual, signal, noise, unused;\n\t\t} __packed cq;", "\t\terr = HERMES_READ_RECORD(hw, USER_BAP,\n\t\t\t\t\t HERMES_RID_COMMSQUALITY, &cq);", "\t\tif (!err) {\n\t\t\twstats->qual.qual = (int)le16_to_cpu(cq.qual);\n\t\t\twstats->qual.level = (int)le16_to_cpu(cq.signal) - 0x95;\n\t\t\twstats->qual.noise = (int)le16_to_cpu(cq.noise) - 0x95;\n\t\t\twstats->qual.updated =\n\t\t\t\tIW_QUAL_ALL_UPDATED | IW_QUAL_DBM;\n\t\t}\n\t}", "\torinoco_unlock(priv, &flags);\n\treturn wstats;\n}", "/********************************************************************/\n/* Wireless extensions */\n/********************************************************************/", "static int orinoco_ioctl_setwap(struct net_device *dev,\n\t\t\t\tstruct iw_request_info *info,\n\t\t\t\tstruct sockaddr *ap_addr,\n\t\t\t\tchar *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint err = -EINPROGRESS;\t\t/* Call commit handler */\n\tunsigned long flags;\n\tstatic const u8 off_addr[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\tstatic const u8 any_addr[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\t/* Enable automatic roaming - no sanity checks are needed */\n\tif (memcmp(&ap_addr->sa_data, off_addr, ETH_ALEN) == 0 ||\n\t memcmp(&ap_addr->sa_data, any_addr, ETH_ALEN) == 0) {\n\t\tpriv->bssid_fixed = 0;\n\t\tmemset(priv->desired_bssid, 0, ETH_ALEN);", "\t\t/* \"off\" means keep existing connection */\n\t\tif (ap_addr->sa_data[0] == 0) {\n\t\t\t__orinoco_hw_set_wap(priv);\n\t\t\terr = 0;\n\t\t}\n\t\tgoto out;\n\t}", "\tif (priv->firmware_type == FIRMWARE_TYPE_AGERE) {\n\t\tprintk(KERN_WARNING \"%s: Lucent/Agere firmware doesn't \"\n\t\t \"support manual roaming\\n\",\n\t\t dev->name);\n\t\terr = -EOPNOTSUPP;\n\t\tgoto out;\n\t}", "\tif (priv->iw_mode != NL80211_IFTYPE_STATION) {\n\t\tprintk(KERN_WARNING \"%s: Manual roaming supported only in \"\n\t\t \"managed mode\\n\", dev->name);\n\t\terr = -EOPNOTSUPP;\n\t\tgoto out;\n\t}", "\t/* Intersil firmware hangs without Desired ESSID */\n\tif (priv->firmware_type == FIRMWARE_TYPE_INTERSIL &&\n\t strlen(priv->desired_essid) == 0) {\n\t\tprintk(KERN_WARNING \"%s: Desired ESSID must be set for \"\n\t\t \"manual roaming\\n\", dev->name);\n\t\terr = -EOPNOTSUPP;\n\t\tgoto out;\n\t}", "\t/* Finally, enable manual roaming */\n\tpriv->bssid_fixed = 1;\n\tmemcpy(priv->desired_bssid, &ap_addr->sa_data, ETH_ALEN);", " out:\n\torinoco_unlock(priv, &flags);\n\treturn err;\n}", "static int orinoco_ioctl_getwap(struct net_device *dev,\n\t\t\t\tstruct iw_request_info *info,\n\t\t\t\tstruct sockaddr *ap_addr,\n\t\t\t\tchar *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);", "\tint err = 0;\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tap_addr->sa_family = ARPHRD_ETHER;\n\terr = orinoco_hw_get_current_bssid(priv, ap_addr->sa_data);", "\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_setiwencode(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_point *erq,\n\t\t\t\t char *keybuf)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint index = (erq->flags & IW_ENCODE_INDEX) - 1;\n\tint setindex = priv->tx_key;\n\tenum orinoco_alg encode_alg = priv->encode_alg;\n\tint restricted = priv->wep_restrict;\n\tint err = -EINPROGRESS;\t\t/* Call commit handler */\n\tunsigned long flags;", "\tif (!priv->has_wep)\n\t\treturn -EOPNOTSUPP;", "\tif (erq->pointer) {\n\t\t/* We actually have a key to set - check its length */\n\t\tif (erq->length > LARGE_KEY_SIZE)\n\t\t\treturn -E2BIG;", "\t\tif ((erq->length > SMALL_KEY_SIZE) && !priv->has_big_wep)\n\t\t\treturn -E2BIG;\n\t}", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\t/* Clear any TKIP key we have */\n\tif ((priv->has_wpa) && (priv->encode_alg == ORINOCO_ALG_TKIP))\n\t\t(void) orinoco_clear_tkip_key(priv, setindex);", "\tif (erq->length > 0) {\n\t\tif ((index < 0) || (index >= ORINOCO_MAX_KEYS))\n\t\t\tindex = priv->tx_key;", "\t\t/* Switch on WEP if off */\n\t\tif (encode_alg != ORINOCO_ALG_WEP) {\n\t\t\tsetindex = index;\n\t\t\tencode_alg = ORINOCO_ALG_WEP;\n\t\t}\n\t} else {\n\t\t/* Important note : if the user do \"iwconfig eth0 enc off\",\n\t\t * we will arrive there with an index of -1. This is valid\n\t\t * but need to be taken care off... Jean II */\n\t\tif ((index < 0) || (index >= ORINOCO_MAX_KEYS)) {\n\t\t\tif ((index != -1) || (erq->flags == 0)) {\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t} else {\n\t\t\t/* Set the index : Check that the key is valid */\n\t\t\tif (priv->keys[index].key_len == 0) {\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tsetindex = index;\n\t\t}\n\t}", "\tif (erq->flags & IW_ENCODE_DISABLED)\n\t\tencode_alg = ORINOCO_ALG_NONE;\n\tif (erq->flags & IW_ENCODE_OPEN)\n\t\trestricted = 0;\n\tif (erq->flags & IW_ENCODE_RESTRICTED)\n\t\trestricted = 1;", "\tif (erq->pointer && erq->length > 0) {\n\t\terr = orinoco_set_key(priv, index, ORINOCO_ALG_WEP, keybuf,\n\t\t\t\t erq->length, NULL, 0);\n\t}\n\tpriv->tx_key = setindex;", "\t/* Try fast key change if connected and only keys are changed */\n\tif ((priv->encode_alg == encode_alg) &&\n\t (priv->wep_restrict == restricted) &&\n\t netif_carrier_ok(dev)) {\n\t\terr = __orinoco_hw_setup_wepkeys(priv);\n\t\t/* No need to commit if successful */\n\t\tgoto out;\n\t}", "\tpriv->encode_alg = encode_alg;\n\tpriv->wep_restrict = restricted;", " out:\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_getiwencode(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_point *erq,\n\t\t\t\t char *keybuf)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint index = (erq->flags & IW_ENCODE_INDEX) - 1;\n\tunsigned long flags;", "\tif (!priv->has_wep)\n\t\treturn -EOPNOTSUPP;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tif ((index < 0) || (index >= ORINOCO_MAX_KEYS))\n\t\tindex = priv->tx_key;", "\terq->flags = 0;\n\tif (!priv->encode_alg)\n\t\terq->flags |= IW_ENCODE_DISABLED;\n\terq->flags |= index + 1;", "\tif (priv->wep_restrict)\n\t\terq->flags |= IW_ENCODE_RESTRICTED;\n\telse\n\t\terq->flags |= IW_ENCODE_OPEN;", "\terq->length = priv->keys[index].key_len;", "\tmemcpy(keybuf, priv->keys[index].key, erq->length);", "\torinoco_unlock(priv, &flags);\n\treturn 0;\n}", "static int orinoco_ioctl_setessid(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_point *erq,\n\t\t\t\t char *essidbuf)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tunsigned long flags;", "\t/* Note : ESSID is ignored in Ad-Hoc demo mode, but we can set it\n\t * anyway... - Jean II */", "\t/* Hum... Should not use Wireless Extension constant (may change),\n\t * should use our own... - Jean II */\n\tif (erq->length > IW_ESSID_MAX_SIZE)\n\t\treturn -E2BIG;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\t/* NULL the string (for NULL termination & ESSID = ANY) - Jean II */\n\tmemset(priv->desired_essid, 0, sizeof(priv->desired_essid));", "\t/* If not ANY, get the new ESSID */\n\tif (erq->flags)\n\t\tmemcpy(priv->desired_essid, essidbuf, erq->length);", "\torinoco_unlock(priv, &flags);", "\treturn -EINPROGRESS;\t\t/* Call commit handler */\n}", "static int orinoco_ioctl_getessid(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_point *erq,\n\t\t\t\t char *essidbuf)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint active;\n\tint err = 0;\n\tunsigned long flags;", "\tif (netif_running(dev)) {\n\t\terr = orinoco_hw_get_essid(priv, &active, essidbuf);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t\terq->length = err;\n\t} else {\n\t\tif (orinoco_lock(priv, &flags) != 0)\n\t\t\treturn -EBUSY;\n\t\tmemcpy(essidbuf, priv->desired_essid, IW_ESSID_MAX_SIZE);\n\t\terq->length = strlen(priv->desired_essid);\n\t\torinoco_unlock(priv, &flags);\n\t}", "\terq->flags = 1;", "\treturn 0;\n}", "static int orinoco_ioctl_setfreq(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_freq *frq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint chan = -1;\n\tunsigned long flags;\n\tint err = -EINPROGRESS;\t\t/* Call commit handler */", "\t/* In infrastructure mode the AP sets the channel */\n\tif (priv->iw_mode == NL80211_IFTYPE_STATION)\n\t\treturn -EBUSY;", "\tif ((frq->e == 0) && (frq->m <= 1000)) {\n\t\t/* Setting by channel number */\n\t\tchan = frq->m;\n\t} else {\n\t\t/* Setting by frequency */\n\t\tint denom = 1;\n\t\tint i;", "\t\t/* Calculate denominator to rescale to MHz */\n\t\tfor (i = 0; i < (6 - frq->e); i++)\n\t\t\tdenom *= 10;", "\t\tchan = ieee80211_freq_to_dsss_chan(frq->m / denom);\n\t}", "\tif ((chan < 1) || (chan > NUM_CHANNELS) ||\n\t !(priv->channel_mask & (1 << (chan-1))))\n\t\treturn -EINVAL;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tpriv->channel = chan;\n\tif (priv->iw_mode == NL80211_IFTYPE_MONITOR) {\n\t\t/* Fast channel change - no commit if successful */\n\t\thermes_t *hw = &priv->hw;\n\t\terr = hw->ops->cmd_wait(hw, HERMES_CMD_TEST |\n\t\t\t\t\t HERMES_TEST_SET_CHANNEL,\n\t\t\t\t\tchan, NULL);\n\t}\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_getfreq(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_freq *frq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint tmp;", "\t/* Locking done in there */\n\ttmp = orinoco_hw_get_freq(priv);\n\tif (tmp < 0)\n\t\treturn tmp;", "\tfrq->m = tmp * 100000;\n\tfrq->e = 1;", "\treturn 0;\n}", "static int orinoco_ioctl_getsens(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *srq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\thermes_t *hw = &priv->hw;\n\tu16 val;\n\tint err;\n\tunsigned long flags;", "\tif (!priv->has_sensitivity)\n\t\treturn -EOPNOTSUPP;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;\n\terr = hermes_read_wordrec(hw, USER_BAP,\n\t\t\t\t HERMES_RID_CNFSYSTEMSCALE, &val);\n\torinoco_unlock(priv, &flags);", "\tif (err)\n\t\treturn err;", "\tsrq->value = val;\n\tsrq->fixed = 0; /* auto */", "\treturn 0;\n}", "static int orinoco_ioctl_setsens(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *srq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint val = srq->value;\n\tunsigned long flags;", "\tif (!priv->has_sensitivity)\n\t\treturn -EOPNOTSUPP;", "\tif ((val < 1) || (val > 3))\n\t\treturn -EINVAL;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;\n\tpriv->ap_density = val;\n\torinoco_unlock(priv, &flags);", "\treturn -EINPROGRESS;\t\t/* Call commit handler */\n}", "static int orinoco_ioctl_setrate(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *rrq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint ratemode;\n\tint bitrate; /* 100s of kilobits */\n\tunsigned long flags;", "\t/* As the user space doesn't know our highest rate, it uses -1\n\t * to ask us to set the highest rate. Test it using \"iwconfig\n\t * ethX rate auto\" - Jean II */\n\tif (rrq->value == -1)\n\t\tbitrate = 110;\n\telse {\n\t\tif (rrq->value % 100000)\n\t\t\treturn -EINVAL;\n\t\tbitrate = rrq->value / 100000;\n\t}", "\tratemode = orinoco_get_bitratemode(bitrate, !rrq->fixed);", "\tif (ratemode == -1)\n\t\treturn -EINVAL;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;\n\tpriv->bitratemode = ratemode;\n\torinoco_unlock(priv, &flags);", "\treturn -EINPROGRESS;\n}", "static int orinoco_ioctl_getrate(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *rrq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint err = 0;\n\tint bitrate, automatic;\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\torinoco_get_ratemode_cfg(priv->bitratemode, &bitrate, &automatic);", "\t/* If the interface is running we try to find more about the\n\t current mode */\n\tif (netif_running(dev)) {\n\t\tint act_bitrate;\n\t\tint lerr;", "\t\t/* Ignore errors if we can't get the actual bitrate */\n\t\tlerr = orinoco_hw_get_act_bitrate(priv, &act_bitrate);\n\t\tif (!lerr)\n\t\t\tbitrate = act_bitrate;\n\t}", "\torinoco_unlock(priv, &flags);", "\trrq->value = bitrate;\n\trrq->fixed = !automatic;\n\trrq->disabled = 0;", "\treturn err;\n}", "static int orinoco_ioctl_setpower(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *prq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint err = -EINPROGRESS;\t\t/* Call commit handler */\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tif (prq->disabled) {\n\t\tpriv->pm_on = 0;\n\t} else {\n\t\tswitch (prq->flags & IW_POWER_MODE) {\n\t\tcase IW_POWER_UNICAST_R:\n\t\t\tpriv->pm_mcast = 0;\n\t\t\tpriv->pm_on = 1;\n\t\t\tbreak;\n\t\tcase IW_POWER_ALL_R:\n\t\t\tpriv->pm_mcast = 1;\n\t\t\tpriv->pm_on = 1;\n\t\t\tbreak;\n\t\tcase IW_POWER_ON:\n\t\t\t/* No flags : but we may have a value - Jean II */\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terr = -EINVAL;\n\t\t\tgoto out;\n\t\t}", "\t\tif (prq->flags & IW_POWER_TIMEOUT) {\n\t\t\tpriv->pm_on = 1;\n\t\t\tpriv->pm_timeout = prq->value / 1000;\n\t\t}\n\t\tif (prq->flags & IW_POWER_PERIOD) {\n\t\t\tpriv->pm_on = 1;\n\t\t\tpriv->pm_period = prq->value / 1000;\n\t\t}\n\t\t/* It's valid to not have a value if we are just toggling\n\t\t * the flags... Jean II */\n\t\tif (!priv->pm_on) {\n\t\t\terr = -EINVAL;\n\t\t\tgoto out;\n\t\t}\n\t}", " out:\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_getpower(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t struct iw_param *prq,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\thermes_t *hw = &priv->hw;\n\tint err = 0;\n\tu16 enable, period, timeout, mcast;\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\terr = hermes_read_wordrec(hw, USER_BAP,\n\t\t\t\t HERMES_RID_CNFPMENABLED, &enable);\n\tif (err)\n\t\tgoto out;", "\terr = hermes_read_wordrec(hw, USER_BAP,\n\t\t\t\t HERMES_RID_CNFMAXSLEEPDURATION, &period);\n\tif (err)\n\t\tgoto out;", "\terr = hermes_read_wordrec(hw, USER_BAP,\n\t\t\t\t HERMES_RID_CNFPMHOLDOVERDURATION, &timeout);\n\tif (err)\n\t\tgoto out;", "\terr = hermes_read_wordrec(hw, USER_BAP,\n\t\t\t\t HERMES_RID_CNFMULTICASTRECEIVE, &mcast);\n\tif (err)\n\t\tgoto out;", "\tprq->disabled = !enable;\n\t/* Note : by default, display the period */\n\tif ((prq->flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {\n\t\tprq->flags = IW_POWER_TIMEOUT;\n\t\tprq->value = timeout * 1000;\n\t} else {\n\t\tprq->flags = IW_POWER_PERIOD;\n\t\tprq->value = period * 1000;\n\t}\n\tif (mcast)\n\t\tprq->flags |= IW_POWER_ALL_R;\n\telse\n\t\tprq->flags |= IW_POWER_UNICAST_R;", " out:\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_set_encodeext(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tstruct iw_point *encoding = &wrqu->encoding;\n\tstruct iw_encode_ext *ext = (struct iw_encode_ext *)extra;\n\tint idx, alg = ext->alg, set_key = 1;\n\tunsigned long flags;\n\tint err = -EINVAL;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\t/* Determine and validate the key index */\n\tidx = encoding->flags & IW_ENCODE_INDEX;\n\tif (idx) {\n\t\tif ((idx < 1) || (idx > 4))\n\t\t\tgoto out;\n\t\tidx--;\n\t} else\n\t\tidx = priv->tx_key;", "\tif (encoding->flags & IW_ENCODE_DISABLED)\n\t\talg = IW_ENCODE_ALG_NONE;", "\tif (priv->has_wpa && (alg != IW_ENCODE_ALG_TKIP)) {\n\t\t/* Clear any TKIP TX key we had */\n\t\t(void) orinoco_clear_tkip_key(priv, priv->tx_key);\n\t}", "\tif (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY) {\n\t\tpriv->tx_key = idx;\n\t\tset_key = ((alg == IW_ENCODE_ALG_TKIP) ||\n\t\t\t (ext->key_len > 0)) ? 1 : 0;\n\t}", "\tif (set_key) {\n\t\t/* Set the requested key first */\n\t\tswitch (alg) {\n\t\tcase IW_ENCODE_ALG_NONE:\n\t\t\tpriv->encode_alg = ORINOCO_ALG_NONE;\n\t\t\terr = orinoco_set_key(priv, idx, ORINOCO_ALG_NONE,\n\t\t\t\t\t NULL, 0, NULL, 0);\n\t\t\tbreak;", "\t\tcase IW_ENCODE_ALG_WEP:\n\t\t\tif (ext->key_len <= 0)\n\t\t\t\tgoto out;", "\t\t\tpriv->encode_alg = ORINOCO_ALG_WEP;\n\t\t\terr = orinoco_set_key(priv, idx, ORINOCO_ALG_WEP,\n\t\t\t\t\t ext->key, ext->key_len, NULL, 0);\n\t\t\tbreak;", "\t\tcase IW_ENCODE_ALG_TKIP:\n\t\t{\n\t\t\tu8 *tkip_iv = NULL;", "\t\t\tif (!priv->has_wpa ||\n\t\t\t (ext->key_len > sizeof(struct orinoco_tkip_key)))\n\t\t\t\tgoto out;", "\t\t\tpriv->encode_alg = ORINOCO_ALG_TKIP;", "\t\t\tif (ext->ext_flags & IW_ENCODE_EXT_RX_SEQ_VALID)\n\t\t\t\ttkip_iv = &ext->rx_seq[0];", "\t\t\terr = orinoco_set_key(priv, idx, ORINOCO_ALG_TKIP,\n\t\t\t\t\t ext->key, ext->key_len, tkip_iv,\n\t\t\t\t\t ORINOCO_SEQ_LEN);", "\t\t\terr = __orinoco_hw_set_tkip_key(priv, idx,\n\t\t\t\t ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY,\n\t\t\t\t priv->keys[idx].key,\n\t\t\t\t tkip_iv, ORINOCO_SEQ_LEN, NULL, 0);\n\t\t\tif (err)\n\t\t\t\tprintk(KERN_ERR \"%s: Error %d setting TKIP key\"\n\t\t\t\t \"\\n\", dev->name, err);", "\t\t\tgoto out;\n\t\t}\n\t\tdefault:\n\t\t\tgoto out;\n\t\t}\n\t}\n\terr = -EINPROGRESS;\n out:\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_get_encodeext(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tstruct iw_point *encoding = &wrqu->encoding;\n\tstruct iw_encode_ext *ext = (struct iw_encode_ext *)extra;\n\tint idx, max_key_len;\n\tunsigned long flags;\n\tint err;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\terr = -EINVAL;\n\tmax_key_len = encoding->length - sizeof(*ext);\n\tif (max_key_len < 0)\n\t\tgoto out;", "\tidx = encoding->flags & IW_ENCODE_INDEX;\n\tif (idx) {\n\t\tif ((idx < 1) || (idx > 4))\n\t\t\tgoto out;\n\t\tidx--;\n\t} else\n\t\tidx = priv->tx_key;", "\tencoding->flags = idx + 1;\n\tmemset(ext, 0, sizeof(*ext));", "\tswitch (priv->encode_alg) {\n\tcase ORINOCO_ALG_NONE:\n\t\text->alg = IW_ENCODE_ALG_NONE;\n\t\text->key_len = 0;\n\t\tencoding->flags |= IW_ENCODE_DISABLED;\n\t\tbreak;\n\tcase ORINOCO_ALG_WEP:\n\t\text->alg = IW_ENCODE_ALG_WEP;\n\t\text->key_len = min(priv->keys[idx].key_len, max_key_len);\n\t\tmemcpy(ext->key, priv->keys[idx].key, ext->key_len);\n\t\tencoding->flags |= IW_ENCODE_ENABLED;\n\t\tbreak;\n\tcase ORINOCO_ALG_TKIP:\n\t\text->alg = IW_ENCODE_ALG_TKIP;\n\t\text->key_len = min(priv->keys[idx].key_len, max_key_len);\n\t\tmemcpy(ext->key, priv->keys[idx].key, ext->key_len);\n\t\tencoding->flags |= IW_ENCODE_ENABLED;\n\t\tbreak;\n\t}", "\terr = 0;\n out:\n\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_set_auth(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu, char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\thermes_t *hw = &priv->hw;\n\tstruct iw_param *param = &wrqu->param;\n\tunsigned long flags;\n\tint ret = -EINPROGRESS;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tswitch (param->flags & IW_AUTH_INDEX) {\n\tcase IW_AUTH_WPA_VERSION:\n\tcase IW_AUTH_CIPHER_PAIRWISE:\n\tcase IW_AUTH_CIPHER_GROUP:\n\tcase IW_AUTH_RX_UNENCRYPTED_EAPOL:\n\tcase IW_AUTH_PRIVACY_INVOKED:\n\tcase IW_AUTH_DROP_UNENCRYPTED:\n\t\t/*\n\t\t * orinoco does not use these parameters\n\t\t */\n\t\tbreak;", "\tcase IW_AUTH_KEY_MGMT:\n\t\t/* wl_lkm implies value 2 == PSK for Hermes I\n\t\t * which ties in with WEXT\n\t\t * no other hints tho :(\n\t\t */\n\t\tpriv->key_mgmt = param->value;\n\t\tbreak;", "\tcase IW_AUTH_TKIP_COUNTERMEASURES:\n\t\t/* When countermeasures are enabled, shut down the\n\t\t * card; when disabled, re-enable the card. This must\n\t\t * take effect immediately.\n\t\t *\n\t\t * TODO: Make sure that the EAPOL message is getting\n\t\t * out before card disabled\n\t\t */\n\t\tif (param->value) {\n\t\t\tpriv->tkip_cm_active = 1;", "\t\t\tret = hermes_disable_port(hw, 0);", "\t\t} else {\n\t\t\tpriv->tkip_cm_active = 0;", "\t\t\tret = hermes_enable_port(hw, 0);", "\t\t}\n\t\tbreak;", "\tcase IW_AUTH_80211_AUTH_ALG:\n\t\tif (param->value & IW_AUTH_ALG_SHARED_KEY)\n\t\t\tpriv->wep_restrict = 1;\n\t\telse if (param->value & IW_AUTH_ALG_OPEN_SYSTEM)\n\t\t\tpriv->wep_restrict = 0;\n\t\telse\n\t\t\tret = -EINVAL;\n\t\tbreak;", "\tcase IW_AUTH_WPA_ENABLED:\n\t\tif (priv->has_wpa) {\n\t\t\tpriv->wpa_enabled = param->value ? 1 : 0;\n\t\t} else {\n\t\t\tif (param->value)\n\t\t\t\tret = -EOPNOTSUPP;\n\t\t\t/* else silently accept disable of WPA */\n\t\t\tpriv->wpa_enabled = 0;\n\t\t}\n\t\tbreak;", "\tdefault:\n\t\tret = -EOPNOTSUPP;\n\t}", "\torinoco_unlock(priv, &flags);\n\treturn ret;\n}", "static int orinoco_ioctl_get_auth(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu, char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tstruct iw_param *param = &wrqu->param;\n\tunsigned long flags;\n\tint ret = 0;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tswitch (param->flags & IW_AUTH_INDEX) {\n\tcase IW_AUTH_KEY_MGMT:\n\t\tparam->value = priv->key_mgmt;\n\t\tbreak;", "\tcase IW_AUTH_TKIP_COUNTERMEASURES:\n\t\tparam->value = priv->tkip_cm_active;\n\t\tbreak;", "\tcase IW_AUTH_80211_AUTH_ALG:\n\t\tif (priv->wep_restrict)\n\t\t\tparam->value = IW_AUTH_ALG_SHARED_KEY;\n\t\telse\n\t\t\tparam->value = IW_AUTH_ALG_OPEN_SYSTEM;\n\t\tbreak;", "\tcase IW_AUTH_WPA_ENABLED:\n\t\tparam->value = priv->wpa_enabled;\n\t\tbreak;", "\tdefault:\n\t\tret = -EOPNOTSUPP;\n\t}", "\torinoco_unlock(priv, &flags);\n\treturn ret;\n}", "static int orinoco_ioctl_set_genie(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu, char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tu8 *buf;\n\tunsigned long flags;", "\t/* cut off at IEEE80211_MAX_DATA_LEN */\n\tif ((wrqu->data.length > IEEE80211_MAX_DATA_LEN) ||\n\t (wrqu->data.length && (extra == NULL)))\n\t\treturn -EINVAL;", "\tif (wrqu->data.length) {\n\t\tbuf = kmemdup(extra, wrqu->data.length, GFP_KERNEL);\n\t\tif (buf == NULL)\n\t\t\treturn -ENOMEM;\n\t} else\n\t\tbuf = NULL;", "\tif (orinoco_lock(priv, &flags) != 0) {\n\t\tkfree(buf);\n\t\treturn -EBUSY;\n\t}", "\tkfree(priv->wpa_ie);\n\tpriv->wpa_ie = buf;\n\tpriv->wpa_ie_len = wrqu->data.length;", "\tif (priv->wpa_ie) {\n\t\t/* Looks like wl_lkm wants to check the auth alg, and\n\t\t * somehow pass it to the firmware.\n\t\t * Instead it just calls the key mgmt rid\n\t\t * - we do this in set auth.\n\t\t */\n\t}", "\torinoco_unlock(priv, &flags);\n\treturn 0;\n}", "static int orinoco_ioctl_get_genie(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu, char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tunsigned long flags;\n\tint err = 0;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tif ((priv->wpa_ie_len == 0) || (priv->wpa_ie == NULL)) {\n\t\twrqu->data.length = 0;\n\t\tgoto out;\n\t}", "\tif (wrqu->data.length < priv->wpa_ie_len) {\n\t\terr = -E2BIG;\n\t\tgoto out;\n\t}", "\twrqu->data.length = priv->wpa_ie_len;\n\tmemcpy(extra, priv->wpa_ie, priv->wpa_ie_len);", "out:\n\torinoco_unlock(priv, &flags);\n\treturn err;\n}", "static int orinoco_ioctl_set_mlme(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t union iwreq_data *wrqu, char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tstruct iw_mlme *mlme = (struct iw_mlme *)extra;\n\tunsigned long flags;\n\tint ret = 0;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tswitch (mlme->cmd) {\n\tcase IW_MLME_DEAUTH:\n\t\t/* silently ignore */\n\t\tbreak;", "\tcase IW_MLME_DISASSOC:", "\t\tret = orinoco_hw_disassociate(priv, mlme->addr.sa_data,\n\t\t\t\t\t mlme->reason_code);\n\t\tbreak;", "\tdefault:\n\t\tret = -EOPNOTSUPP;\n\t}", "\torinoco_unlock(priv, &flags);\n\treturn ret;\n}", "static int orinoco_ioctl_reset(struct net_device *dev,\n\t\t\t struct iw_request_info *info,\n\t\t\t void *wrqu,\n\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);", "\tif (!capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;", "\tif (info->cmd == (SIOCIWFIRSTPRIV + 0x1)) {\n\t\tprintk(KERN_DEBUG \"%s: Forcing reset!\\n\", dev->name);", "\t\t/* Firmware reset */\n\t\torinoco_reset(&priv->reset_work);\n\t} else {\n\t\tprintk(KERN_DEBUG \"%s: Force scheduling reset!\\n\", dev->name);", "\t\tschedule_work(&priv->reset_work);\n\t}", "\treturn 0;\n}", "static int orinoco_ioctl_setibssport(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)", "{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint val = *((int *) extra);\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tpriv->ibss_port = val;", "\t/* Actually update the mode we are using */\n\tset_port_type(priv);", "\torinoco_unlock(priv, &flags);\n\treturn -EINPROGRESS;\t\t/* Call commit handler */\n}", "static int orinoco_ioctl_getibssport(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint *val = (int *) extra;", "\t*val = priv->ibss_port;\n\treturn 0;\n}", "static int orinoco_ioctl_setport3(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint val = *((int *) extra);\n\tint err = 0;\n\tunsigned long flags;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tswitch (val) {\n\tcase 0: /* Try to do IEEE ad-hoc mode */\n\t\tif (!priv->has_ibss) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t\tpriv->prefer_port3 = 0;", "\t\tbreak;", "\tcase 1: /* Try to do Lucent proprietary ad-hoc mode */\n\t\tif (!priv->has_port3) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t\tpriv->prefer_port3 = 1;\n\t\tbreak;", "\tdefault:\n\t\terr = -EINVAL;\n\t}", "\tif (!err) {\n\t\t/* Actually update the mode we are using */\n\t\tset_port_type(priv);\n\t\terr = -EINPROGRESS;\n\t}", "\torinoco_unlock(priv, &flags);", "\treturn err;\n}", "static int orinoco_ioctl_getport3(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint *val = (int *) extra;", "\t*val = priv->prefer_port3;\n\treturn 0;\n}", "static int orinoco_ioctl_setpreamble(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tunsigned long flags;\n\tint val;", "\tif (!priv->has_preamble)\n\t\treturn -EOPNOTSUPP;", "\t/* 802.11b has recently defined some short preamble.\n\t * Basically, the Phy header has been reduced in size.\n\t * This increase performance, especially at high rates\n\t * (the preamble is transmitted at 1Mb/s), unfortunately\n\t * this give compatibility troubles... - Jean II */\n\tval = *((int *) extra);", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\tif (val)\n\t\tpriv->preamble = 1;\n\telse\n\t\tpriv->preamble = 0;", "\torinoco_unlock(priv, &flags);", "\treturn -EINPROGRESS;\t\t/* Call commit handler */\n}", "static int orinoco_ioctl_getpreamble(struct net_device *dev,\n\t\t\t\t struct iw_request_info *info,\n\t\t\t\t void *wrqu,\n\t\t\t\t char *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tint *val = (int *) extra;", "\tif (!priv->has_preamble)\n\t\treturn -EOPNOTSUPP;", "\t*val = priv->preamble;\n\treturn 0;\n}", "/* ioctl interface to hermes_read_ltv()\n * To use with iwpriv, pass the RID as the token argument, e.g.\n * iwpriv get_rid [0xfc00]\n * At least Wireless Tools 25 is required to use iwpriv.\n * For Wireless Tools 25 and 26 append \"dummy\" are the end. */\nstatic int orinoco_ioctl_getrid(struct net_device *dev,\n\t\t\t\tstruct iw_request_info *info,\n\t\t\t\tstruct iw_point *data,\n\t\t\t\tchar *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\thermes_t *hw = &priv->hw;\n\tint rid = data->flags;\n\tu16 length;\n\tint err;\n\tunsigned long flags;", "\t/* It's a \"get\" function, but we don't want users to access the\n\t * WEP key and other raw firmware data */\n\tif (!capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;", "\tif (rid < 0xfc00 || rid > 0xffff)\n\t\treturn -EINVAL;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn -EBUSY;", "\terr = hw->ops->read_ltv(hw, USER_BAP, rid, MAX_RID_LEN, &length,\n\t\t\t\textra);\n\tif (err)\n\t\tgoto out;", "\tdata->length = min_t(u16, HERMES_RECLEN_TO_BYTES(length),\n\t\t\t MAX_RID_LEN);", " out:\n\torinoco_unlock(priv, &flags);\n\treturn err;\n}", "\n/* Commit handler, called after set operations */\nstatic int orinoco_ioctl_commit(struct net_device *dev,\n\t\t\t\tstruct iw_request_info *info,\n\t\t\t\tvoid *wrqu,\n\t\t\t\tchar *extra)\n{\n\tstruct orinoco_private *priv = ndev_priv(dev);\n\tunsigned long flags;\n\tint err = 0;", "\tif (!priv->open)\n\t\treturn 0;", "\tif (orinoco_lock(priv, &flags) != 0)\n\t\treturn err;", "\terr = orinoco_commit(priv);", "\torinoco_unlock(priv, &flags);\n\treturn err;\n}", "static const struct iw_priv_args orinoco_privtab[] = {\n\t{ SIOCIWFIRSTPRIV + 0x0, 0, 0, \"force_reset\" },\n\t{ SIOCIWFIRSTPRIV + 0x1, 0, 0, \"card_reset\" },\n\t{ SIOCIWFIRSTPRIV + 0x2, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t 0, \"set_port3\" },\n\t{ SIOCIWFIRSTPRIV + 0x3, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t \"get_port3\" },\n\t{ SIOCIWFIRSTPRIV + 0x4, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t 0, \"set_preamble\" },\n\t{ SIOCIWFIRSTPRIV + 0x5, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t \"get_preamble\" },\n\t{ SIOCIWFIRSTPRIV + 0x6, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t 0, \"set_ibssport\" },\n\t{ SIOCIWFIRSTPRIV + 0x7, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,\n\t \"get_ibssport\" },\n\t{ SIOCIWFIRSTPRIV + 0x9, 0, IW_PRIV_TYPE_BYTE | MAX_RID_LEN,\n\t \"get_rid\" },\n};", "\n/*\n * Structures to export the Wireless Handlers\n */", "static const iw_handler\torinoco_handler[] = {\n\tIW_HANDLER(SIOCSIWCOMMIT,\t(iw_handler)orinoco_ioctl_commit),\n\tIW_HANDLER(SIOCGIWNAME,\t\t(iw_handler)cfg80211_wext_giwname),\n\tIW_HANDLER(SIOCSIWFREQ,\t\t(iw_handler)orinoco_ioctl_setfreq),\n\tIW_HANDLER(SIOCGIWFREQ,\t\t(iw_handler)orinoco_ioctl_getfreq),\n\tIW_HANDLER(SIOCSIWMODE,\t\t(iw_handler)cfg80211_wext_siwmode),\n\tIW_HANDLER(SIOCGIWMODE,\t\t(iw_handler)cfg80211_wext_giwmode),\n\tIW_HANDLER(SIOCSIWSENS,\t\t(iw_handler)orinoco_ioctl_setsens),\n\tIW_HANDLER(SIOCGIWSENS,\t\t(iw_handler)orinoco_ioctl_getsens),\n\tIW_HANDLER(SIOCGIWRANGE,\t(iw_handler)cfg80211_wext_giwrange),\n\tIW_HANDLER(SIOCSIWSPY,\t\tiw_handler_set_spy),\n\tIW_HANDLER(SIOCGIWSPY,\t\tiw_handler_get_spy),\n\tIW_HANDLER(SIOCSIWTHRSPY,\tiw_handler_set_thrspy),\n\tIW_HANDLER(SIOCGIWTHRSPY,\tiw_handler_get_thrspy),\n\tIW_HANDLER(SIOCSIWAP,\t\t(iw_handler)orinoco_ioctl_setwap),\n\tIW_HANDLER(SIOCGIWAP,\t\t(iw_handler)orinoco_ioctl_getwap),\n\tIW_HANDLER(SIOCSIWSCAN,\t\t(iw_handler)cfg80211_wext_siwscan),\n\tIW_HANDLER(SIOCGIWSCAN,\t\t(iw_handler)cfg80211_wext_giwscan),\n\tIW_HANDLER(SIOCSIWESSID,\t(iw_handler)orinoco_ioctl_setessid),\n\tIW_HANDLER(SIOCGIWESSID,\t(iw_handler)orinoco_ioctl_getessid),\n\tIW_HANDLER(SIOCSIWRATE,\t\t(iw_handler)orinoco_ioctl_setrate),\n\tIW_HANDLER(SIOCGIWRATE,\t\t(iw_handler)orinoco_ioctl_getrate),\n\tIW_HANDLER(SIOCSIWRTS,\t\t(iw_handler)cfg80211_wext_siwrts),\n\tIW_HANDLER(SIOCGIWRTS,\t\t(iw_handler)cfg80211_wext_giwrts),\n\tIW_HANDLER(SIOCSIWFRAG,\t\t(iw_handler)cfg80211_wext_siwfrag),\n\tIW_HANDLER(SIOCGIWFRAG,\t\t(iw_handler)cfg80211_wext_giwfrag),\n\tIW_HANDLER(SIOCGIWRETRY,\t(iw_handler)cfg80211_wext_giwretry),\n\tIW_HANDLER(SIOCSIWENCODE,\t(iw_handler)orinoco_ioctl_setiwencode),\n\tIW_HANDLER(SIOCGIWENCODE,\t(iw_handler)orinoco_ioctl_getiwencode),\n\tIW_HANDLER(SIOCSIWPOWER,\t(iw_handler)orinoco_ioctl_setpower),\n\tIW_HANDLER(SIOCGIWPOWER,\t(iw_handler)orinoco_ioctl_getpower),\n\tIW_HANDLER(SIOCSIWGENIE,\torinoco_ioctl_set_genie),\n\tIW_HANDLER(SIOCGIWGENIE,\torinoco_ioctl_get_genie),\n\tIW_HANDLER(SIOCSIWMLME,\t\torinoco_ioctl_set_mlme),\n\tIW_HANDLER(SIOCSIWAUTH,\t\torinoco_ioctl_set_auth),\n\tIW_HANDLER(SIOCGIWAUTH,\t\torinoco_ioctl_get_auth),\n\tIW_HANDLER(SIOCSIWENCODEEXT,\torinoco_ioctl_set_encodeext),\n\tIW_HANDLER(SIOCGIWENCODEEXT,\torinoco_ioctl_get_encodeext),\n};", "\n/*\n Added typecasting since we no longer use iwreq_data -- Moustafa\n */\nstatic const iw_handler\torinoco_private_handler[] = {\n\t[0] = (iw_handler)orinoco_ioctl_reset,\n\t[1] = (iw_handler)orinoco_ioctl_reset,\n\t[2] = (iw_handler)orinoco_ioctl_setport3,\n\t[3] = (iw_handler)orinoco_ioctl_getport3,\n\t[4] = (iw_handler)orinoco_ioctl_setpreamble,\n\t[5] = (iw_handler)orinoco_ioctl_getpreamble,\n\t[6] = (iw_handler)orinoco_ioctl_setibssport,\n\t[7] = (iw_handler)orinoco_ioctl_getibssport,\n\t[9] = (iw_handler)orinoco_ioctl_getrid,\n};", "const struct iw_handler_def orinoco_handler_def = {\n\t.num_standard = ARRAY_SIZE(orinoco_handler),\n\t.num_private = ARRAY_SIZE(orinoco_private_handler),\n\t.num_private_args = ARRAY_SIZE(orinoco_privtab),\n\t.standard = orinoco_handler,\n\t.private = orinoco_private_handler,\n\t.private_args = orinoco_privtab,\n\t.get_wireless_stats = orinoco_get_wireless_stats,\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 ]
PreciseBugs
{"buggy_code_end_loc": [918], "buggy_code_start_loc": [914], "filenames": ["drivers/net/wireless/orinoco/wext.c"], "fixing_code_end_loc": [918], "fixing_code_start_loc": [914], "message": "The orinoco_ioctl_set_auth function in drivers/net/wireless/orinoco/wext.c in the Linux kernel before 2.6.37 does not properly implement a TKIP protection mechanism, which makes it easier for remote attackers to obtain access to a Wi-Fi network by reading Wi-Fi frames.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "C03086A2-8EEE-40E3-9A7F-A5303FBF0472", "versionEndExcluding": null, "versionEndIncluding": "2.6.36.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:2.6.36.1:*:*:*:*:*:*:*", "matchCriteriaId": "907A3F7F-B11D-4CF1-A1B2-A28BBEBF03C3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:2.6.36.2:*:*:*:*:*:*:*", "matchCriteriaId": "EE4657B8-B691-4833-8546-220AD2BA8A7D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:2.6.36.3:*:*:*:*:*:*:*", "matchCriteriaId": "A2455F37-66D8-4BE1-8739-1A20A2E5375D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The orinoco_ioctl_set_auth function in drivers/net/wireless/orinoco/wext.c in the Linux kernel before 2.6.37 does not properly implement a TKIP protection mechanism, which makes it easier for remote attackers to obtain access to a Wi-Fi network by reading Wi-Fi frames."}, {"lang": "es", "value": "La funci\u00f3n de orinoco_ioctl_set_auth en drivers/net/wireless/orinoco/wext.c en el kernel de Linux en vesiones anteriores a la v2.6.37 no implementa un mecanismo de protecci\u00f3n TKIP, lo que facilita a los atacantes remotos a la hora de obtener acceso a una red Wi-Fi mediante la lectura de frames Wi-Fi."}], "evaluatorComment": null, "id": "CVE-2010-4648", "lastModified": "2023-02-13T03:20:33.853", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 3.3, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:A/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.5, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2012-06-21T23:55:01.693", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://ftp.osuosl.org/pub/linux/kernel/v2.6/ChangeLog-2.6.37"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git%3Ba=commit%3Bh=0a54917c3fc295cb61f3fb52373c173fd3b69f48"}, {"source": "secalert@redhat.com", "tags": ["Patch"], "url": "http://www.openwall.com/lists/oss-security/2011/01/06/18"}, {"source": "secalert@redhat.com", "tags": ["Patch"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=667907"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch"], "url": "https://github.com/torvalds/linux/commit/0a54917c3fc295cb61f3fb52373c173fd3b69f48"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/0a54917c3fc295cb61f3fb52373c173fd3b69f48"}, "type": "NVD-CWE-noinfo"}
235
Determine whether the {function_name} code is vulnerable or not.
[ "/*! @file GPMF_parser.c\n * \n * @brief GPMF Parser library\n *", " * @version 1.2.1", " * \n * (C) Copyright 2017 GoPro Inc (http://gopro.com/).\n *\t\n * Licensed under either:\n * - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 \n * - MIT license, http://opensource.org/licenses/MIT\n * at your option.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * \n */", "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdint.h>", "#include \"GPMF_parser.h\"", "\n#ifdef DBG\n#if _WINDOWS\n#define DBG_MSG printf\n#else\n#define DBG_MSG(...)\n#endif\n#else\n#define DBG_MSG(...)\n#endif", "\nGPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes.\n{\n\tif (ms)\n\t{", "\t\tint32_t nestsize = (int32_t)ms->nest_size[ms->nest_level];", "\t\tif (nestsize == 0 && ms->nest_level == 0)\n\t\t\tnestsize = ms->buffer_size_longs;", "\t\tif (size + 2 <= nestsize) return GPMF_OK;\n\t}\n\treturn GPMF_ERROR_BAD_STRUCTURE;\n}", "\nGPMF_ERR GPMF_Validate(GPMF_stream *ms, GPMF_LEVELS recurse)\n{\n\tif (ms)\n\t{\n\t\tuint32_t currpos = ms->pos;\n\t\tint32_t nestsize = (int32_t)ms->nest_size[ms->nest_level];\n\t\tif (nestsize == 0 && ms->nest_level == 0)\n\t\t\tnestsize = ms->buffer_size_longs;\n\t\t\n\t\twhile (ms->pos+1 < ms->buffer_size_longs && nestsize > 0)\n\t\t{\n\t\t\tuint32_t key = ms->buffer[ms->pos];", "\t\t\tif (ms->nest_level == 0 && key != GPMF_KEY_DEVICE && ms->device_count == 0 && ms->pos == 0)\n\t\t\t{\n\t\t\t\tDBG_MSG(\"ERROR: uninitized -- GPMF_ERROR_BAD_STRUCTURE\\n\");\n\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t}", "\t\t\tif (GPMF_VALID_FOURCC(key))\n\t\t\t{\n\t\t\t\tuint32_t type_size_repeat = ms->buffer[ms->pos + 1];\n\t\t\t\tint32_t size = GPMF_DATA_SIZE(type_size_repeat) >> 2;\n\t\t\t\tuint8_t type = GPMF_SAMPLE_TYPE(type_size_repeat);\n\t\t\t\tif (size + 2 > nestsize)\n\t\t\t\t{\n\t\t\t\t\tDBG_MSG(\"ERROR: nest size too small within %c%c%c%c-- GPMF_ERROR_BAD_STRUCTURE\\n\", PRINTF_4CC(key));\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t}", "\t\t\t\tif (!GPMF_VALID_FOURCC(key))\n\t\t\t\t{\n\t\t\t\t\tDBG_MSG(\"ERROR: invalid 4CC -- GPMF_ERROR_BAD_STRUCTURE\\n\");\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t}", "\t\t\t\tif (type == GPMF_TYPE_NEST && recurse == GPMF_RECURSE_LEVELS)\n\t\t\t\t{\n\t\t\t\t\tuint32_t validnest;\n\t\t\t\t\tms->pos += 2;\n\t\t\t\t\tms->nest_level++;\n\t\t\t\t\tif (ms->nest_level > GPMF_NEST_LIMIT)\n\t\t\t\t\t{\n\t\t\t\t\t\tDBG_MSG(\"ERROR: nest level within %c%c%c%c too deep -- GPMF_ERROR_BAD_STRUCTURE\\n\", PRINTF_4CC(key));\n\t\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t\t}\n\t\t\t\t\tms->nest_size[ms->nest_level] = size;\n\t\t\t\t\tvalidnest = GPMF_Validate(ms, recurse);\n\t\t\t\t\tms->nest_level--;\n\t\t\t\t\tif (GPMF_OK != validnest)\n\t\t\t\t\t{\n\t\t\t\t\t\tDBG_MSG(\"ERROR: invalid nest within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\\n\", PRINTF_4CC(key));\n\t\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (ms->nest_level == 0)\n\t\t\t\t\t\t\tms->device_count++;\n\t\t\t\t\t}", "\t\t\t\t\tms->pos += size;\n\t\t\t\t\tnestsize -= 2 + size;", "\t\t\t\t\twhile (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == GPMF_KEY_END)\n\t\t\t\t\t{\n\t\t\t\t\t\tms->pos++;\n\t\t\t\t\t\tnestsize--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tms->pos += 2 + size;\n\t\t\t\t\tnestsize -= 2 + size;\n\t\t\t\t}", "\t\t\t\tif (ms->pos == ms->buffer_size_longs)\n\t\t\t\t{\n\t\t\t\t\tms->pos = currpos;\n\t\t\t\t\treturn GPMF_OK;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (key == GPMF_KEY_END)\n\t\t\t\t{\n\t\t\t\t\tdo\n\t\t\t\t\t{\n\t\t\t\t\t\tms->pos++;\n\t\t\t\t\t\tnestsize--;\n\t\t\t\t\t} while (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == 0);\n\t\t\t\t}\n\t\t\t\telse if (ms->nest_level == 0 && ms->device_count > 0)\n\t\t\t\t{\n\t\t\t\t\tms->pos = currpos;\n\t\t\t\t\treturn GPMF_OK;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tDBG_MSG(\"ERROR: bad struct within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\\n\", PRINTF_4CC(key));\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\tms->pos = currpos;\n\t\treturn GPMF_OK;\n\t}\n\telse\n\t{\n\t\tDBG_MSG(\"ERROR: Invalid handle -- GPMF_ERROR_MEMORY\\n\");\n\t\treturn GPMF_ERROR_MEMORY;\n\t}\n}", "\nGPMF_ERR GPMF_ResetState(GPMF_stream *ms)\n{\n\tif (ms)\n\t{\n\t\tms->pos = 0;\n\t\tms->nest_level = 0;\n\t\tms->device_count = 0;\n\t\tms->nest_size[ms->nest_level] = 0;\n\t\tms->last_level_pos[ms->nest_level] = 0;\n\t\tms->last_seek[ms->nest_level] = 0;\n\t\tms->device_id = 0;\n\t\tms->device_name[0] = 0;", "\t\treturn GPMF_OK;\n\t}\n\t\n\treturn GPMF_ERROR_MEMORY;\n}", "\nGPMF_ERR GPMF_Init(GPMF_stream *ms, uint32_t *buffer, int datasize)\n{\n\tif(ms)\n\t{\n\t\tms->buffer = buffer;\n\t\tms->buffer_size_longs = datasize >>2;", "\t\tGPMF_ResetState(ms);", "\t\treturn GPMF_OK;\n\t}\n\t\n\treturn GPMF_ERROR_MEMORY;\n}", "\nGPMF_ERR GPMF_CopyState(GPMF_stream *msrc, GPMF_stream *mdst)\n{\n\tif (msrc && mdst)\n\t{\n\t\tmemcpy(mdst, msrc, sizeof(GPMF_stream));\n\t\treturn GPMF_OK;\n\t}\n\treturn GPMF_ERROR_MEMORY;\n}", "\nGPMF_ERR GPMF_Next(GPMF_stream *ms, GPMF_LEVELS recurse)\n{\n\tif (ms)\n\t{\n\t\tif (ms->pos+1 < ms->buffer_size_longs)\n\t\t{", "\t\t\tuint32_t key, type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);\n\t\t\tuint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2);", "\t\t\tif (GPMF_OK != IsValidSize(ms, size)) return GPMF_ERROR_BAD_STRUCTURE;", "\t\t\tif (GPMF_TYPE_NEST == type && GPMF_KEY_DEVICE == ms->buffer[ms->pos] && ms->nest_level == 0)\n\t\t\t{\n\t\t\t\tms->last_level_pos[ms->nest_level] = ms->pos;\n\t\t\t\tms->nest_size[ms->nest_level] = size;\n\t\t\t\tif (recurse)\n\t\t\t\t\tms->pos += 2;\n\t\t\t\telse\n\t\t\t\t\tms->pos += 2 + size;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (size + 2 > ms->nest_size[ms->nest_level])\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;", "\t\t\t\tif (recurse && type == GPMF_TYPE_NEST)\n\t\t\t\t{\n\t\t\t\t\tms->last_level_pos[ms->nest_level] = ms->pos;\n\t\t\t\t\tms->pos += 2;\n\t\t\t\t\tms->nest_size[ms->nest_level] -= size + 2;", "\t\t\t\t\tms->nest_level++;\n\t\t\t\t\tif (ms->nest_level > GPMF_NEST_LIMIT)\n\t\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;", "\t\t\t\t\tms->nest_size[ms->nest_level] = size;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (recurse)\n\t\t\t\t\t{\n\t\t\t\t\t\tms->pos += size + 2;\n\t\t\t\t\t\tms->nest_size[ms->nest_level] -= size + 2;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (ms->nest_size[ms->nest_level] - (size + 2) > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tms->pos += size + 2;\n\t\t\t\t\t\t\tms->nest_size[ms->nest_level] -= size + 2;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn GPMF_ERROR_LAST; \n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} ", "\t\t\twhile (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END)\n\t\t\t{\n\t\t\t\tms->pos++;\n\t\t\t\tms->nest_size[ms->nest_level]--;\n\t\t\t}", "\t\t\twhile (ms->nest_level > 0 && ms->nest_size[ms->nest_level] == 0)\n\t\t\t{\n\t\t\t\tms->nest_level--;\n\t\t\t\t//if (ms->nest_level == 0)\n\t\t\t\t//{\n\t\t\t\t//\tms->device_count++;\n\t\t\t\t//}\n\t\t\t}", "\t\t\tif (ms->pos < ms->buffer_size_longs)\n\t\t\t{\n\t\t\t\twhile (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END)\n\t\t\t\t{\n\t\t\t\t\tms->pos++;\n\t\t\t\t\tms->nest_size[ms->nest_level]--;\n\t\t\t\t}", "\t\t\t\tkey = ms->buffer[ms->pos];\n\t\t\t\tif (!GPMF_VALID_FOURCC(key))\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;", "\t\t\t\tif (key == GPMF_KEY_DEVICE_ID)\n\t\t\t\t\tms->device_id = BYTESWAP32(ms->buffer[ms->pos + 2]);\n\t\t\t\tif (key == GPMF_KEY_DEVICE_NAME)\n\t\t\t\t{\n\t\t\t\t\tsize = GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]); // in bytes\n\t\t\t\t\tif (size > sizeof(ms->device_name) - 1)\n\t\t\t\t\t\tsize = sizeof(ms->device_name) - 1;\n\t\t\t\t\tmemcpy(ms->device_name, &ms->buffer[ms->pos + 2], size);\n\t\t\t\t\tms->device_name[size] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// end of buffer\n\t\t\t\treturn GPMF_ERROR_BUFFER_END;\n\t\t\t}", "\t\t\treturn GPMF_OK;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// end of buffer\n\t\t\treturn GPMF_ERROR_BUFFER_END;\n\t\t}\n\t}\n\treturn GPMF_ERROR_MEMORY;\n}", "", "GPMF_ERR GPMF_FindNext(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse)\n{\n\tGPMF_stream prevstate;", "\tif (ms)\n\t{\n\t\tmemcpy(&prevstate, ms, sizeof(GPMF_stream));", "\t\tif (ms->pos < ms->buffer_size_longs)\n\t\t{\n\t\t\twhile (0 == GPMF_Next(ms, recurse))\n\t\t\t{\n\t\t\t\tif (ms->buffer[ms->pos] == fourcc)\n\t\t\t\t{\n\t\t\t\t\treturn GPMF_OK; //found match\n\t\t\t\t}\n\t\t\t}", "\t\t\t// restore read position\n\t\t\tmemcpy(ms, &prevstate, sizeof(GPMF_stream));\n\t\t\treturn GPMF_ERROR_FIND;\n\t\t}\n\t}\n\treturn GPMF_ERROR_FIND;\n}", "GPMF_ERR GPMF_Reserved(uint32_t key)\n{\n\tif(key == GPMF_KEY_DEVICE)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_DEVICE_ID)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_DEVICE_NAME)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_STREAM)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_STREAM_NAME)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_SI_UNITS)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_UNITS)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_SCALE)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_TYPE)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_TOTAL_SAMPLES)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_TICK)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_TOCK)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_EMPTY_PAYLOADS)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_REMARK)\n\t\treturn GPMF_ERROR_RESERVED;", "\treturn GPMF_OK;\n}", "uint32_t GPMF_PayloadSampleCount(GPMF_stream *ms)\n{\n\tuint32_t count = 0;\n\tif (ms)\n\t{\n\t\tuint32_t fourcc = GPMF_Key(ms);", "\t\tGPMF_stream find_stream;\n\t\tGPMF_CopyState(ms, &find_stream);", "\t\tif (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats\n\t\t{\n\t\t\tcount=2;\n\t\t\twhile (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL))\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t} \n\t\t}\n\t\telse\n\t\t{\n\t\t\tcount = GPMF_Repeat(ms);\n\t\t}\n\t}\n\treturn count;\n}", "\nGPMF_ERR GPMF_SeekToSamples(GPMF_stream *ms)\n{\n\tGPMF_stream prevstate;", "\tif (ms)\n\t{", "\t\tif (ms->pos+1 < ms->buffer_size_longs)\n\t\t{\n\t\t\tuint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);", "\t\t\tmemcpy(&prevstate, ms, sizeof(GPMF_stream));", "\t\t\tif (type == GPMF_TYPE_NEST)\n\t\t\t\tGPMF_Next(ms, GPMF_RECURSE_LEVELS); // open STRM and recurse in", "\t\t\twhile (0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL))\n\t\t\t{\n\t\t\t\tuint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2);\n\t\t\t\tif (GPMF_OK != IsValidSize(ms, size))\n\t\t\t\t{\n\t\t\t\t\tmemcpy(ms, &prevstate, sizeof(GPMF_stream));\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t}", "\t\t\t\ttype = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);", "\n\t\t\t\tif (type == GPMF_TYPE_NEST) // Nest with-in nest\n\t\t\t\t{\n\t\t\t\t\treturn GPMF_OK; //found match\n\t\t\t\t}", "\t\t\t\tif (size + 2 == ms->nest_size[ms->nest_level])\n\t\t\t\t{\n\t\t\t\t\tuint32_t key = GPMF_Key(ms);", "\t\t\t\t\tif (GPMF_ERROR_RESERVED == GPMF_Reserved(key))\n\t\t\t\t\t\treturn GPMF_ERROR_FIND;\n\t\t\t\t\t\n\t\t\t\t\treturn GPMF_OK; //found match\n\t\t\t\t}", "\t\t\t\tif (ms->buffer[ms->pos] == ms->buffer[ms->pos + size + 2]) // Matching tags\n\t\t\t\t{\n\t\t\t\t\treturn GPMF_OK; //found match\n\t\t\t\t}\n\t\t\t}", "\t\t\t// restore read position\n\t\t\tmemcpy(ms, &prevstate, sizeof(GPMF_stream));\n\t\t\treturn GPMF_ERROR_FIND;\n\t\t}\n\t}\n\treturn GPMF_ERROR_FIND;\n}", "\nGPMF_ERR GPMF_FindPrev(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse)\n{\n\tGPMF_stream prevstate;", "\tif (ms)\n\t{\n\t\tuint32_t curr_level = ms->nest_level;", "\t\tmemcpy(&prevstate, ms, sizeof(GPMF_stream));", "\t\tif (ms->pos < ms->buffer_size_longs && curr_level > 0)\n\t\t{", "\t\t\tdo\n\t\t\t{\n\t\t\t\tms->last_seek[curr_level] = ms->pos;\n\t\t\t\tms->pos = ms->last_level_pos[curr_level - 1] + 2;\n\t\t\t\tms->nest_size[curr_level] += ms->last_seek[curr_level] - ms->pos;\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\tif (ms->last_seek[curr_level] > ms->pos && ms->buffer[ms->pos] == fourcc)\n\t\t\t\t\t{", "\t\t\t\t\t\treturn GPMF_OK; //found match\n\t\t\t\t\t}\n\t\t\t\t} while (ms->last_seek[curr_level] > ms->pos && 0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL));", "\t\t\t\tcurr_level--;\n\t\t\t} while (recurse == GPMF_RECURSE_LEVELS && curr_level > 0);", "\t\t\t// restore read position\n\t\t\tmemcpy(ms, &prevstate, sizeof(GPMF_stream));", "\t\t\treturn GPMF_ERROR_FIND;\n\t\t}\n\t}", "\treturn GPMF_ERROR_FIND;\n}", "", "", "uint32_t GPMF_Key(GPMF_stream *ms)\n{\n\tif (ms)\n\t{\n\t\tuint32_t key = ms->buffer[ms->pos];\n\t\treturn key;\n\t}\n\treturn 0;\n}", "\nuint32_t GPMF_Type(GPMF_stream *ms)\n{\n\tif (ms && ms->pos+1 < ms->buffer_size_longs)\n\t{\n\t\tuint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos+1]);\n\t\treturn type;\n\t}\n\treturn 0;\n}", "\nuint32_t GPMF_StructSize(GPMF_stream *ms)\n{\n\tif (ms && ms->pos+1 < ms->buffer_size_longs)\n\t{\n\t\tuint32_t ssize = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]);\n\t\tuint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2);", "\t\tif (GPMF_OK != IsValidSize(ms, size)) return 0; // as the structure is corrupted. i.e. GPMF_ERROR_BAD_STRUCTURE;", "\t\treturn ssize;\n\t}\n\treturn 0;\n}", "\nuint32_t GPMF_ElementsInStruct(GPMF_stream *ms)\n{\n\tif (ms && ms->pos+1 < ms->buffer_size_longs)\n\t{\n\t\tuint32_t ssize = GPMF_StructSize(ms);\n\t\tGPMF_SampleType type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);", "\t\tif (type != GPMF_TYPE_NEST && type != GPMF_TYPE_COMPLEX)\n\t\t{\n\t\t\tint32_t tsize = GPMF_SizeofType(type);\n\t\t\tif (tsize > 0)\n\t\t\t\treturn ssize / tsize;\n\t\t\telse\n\t\t\t\treturn 0;\n\t\t}", "\t\tif (type == GPMF_TYPE_COMPLEX)\n\t\t{\n\t\t\tGPMF_stream find_stream;\n\t\t\tGPMF_CopyState(ms, &find_stream);", "\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL))\n\t\t\t{\n\t\t\t\tchar tmp[64] = \"\";\n\t\t\t\tuint32_t tmpsize = sizeof(tmp);\n\t\t\t\tchar *data = (char *)GPMF_RawData(&find_stream);\n\t\t\t\tint size = GPMF_RawDataSize(&find_stream);\n\t\t\t\t\n\t\t\t\tif (GPMF_OK == GPMF_ExpandComplexTYPE(data, size, tmp, &tmpsize))\n\t\t\t\t\treturn tmpsize;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}", "\nuint32_t GPMF_Repeat(GPMF_stream *ms)\n{\n\tif (ms && ms->pos+1 < ms->buffer_size_longs)\n\t{\n\t\tuint32_t repeat = GPMF_SAMPLES(ms->buffer[ms->pos + 1]);\n\t\treturn repeat;\n\t}\n\treturn 0;\n}", "uint32_t GPMF_RawDataSize(GPMF_stream *ms)\n{\n\tif (ms && ms->pos+1 < ms->buffer_size_longs)\n\t{\n\t\tuint32_t size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]);\n\t\tif (GPMF_OK != IsValidSize(ms, size >> 2)) return 0;", "\t\treturn size;\n\t}\n\treturn 0;\n}", "\nuint32_t GPMF_NestLevel(GPMF_stream *ms)\n{\n\tif (ms)\n\t{\n\t\treturn ms->nest_level;\n\t}\n\treturn 0;\n}", "uint32_t GPMF_DeviceID(GPMF_stream *ms)\n{\n\tif (ms)\n\t{\n\t\treturn ms->device_id;\n\t}\n\treturn 0;\n}", "GPMF_ERR GPMF_DeviceName(GPMF_stream *ms, char *devicenamebuf, uint32_t devicename_buf_size)\n{\n\tif (ms && devicenamebuf)\n\t{\n\t\tuint32_t len = (uint32_t)strlen(ms->device_name);\n\t\tif (len >= devicename_buf_size)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\t\tmemcpy(devicenamebuf, ms->device_name, len);\n\t\tdevicenamebuf[len] = 0;\n\t\treturn GPMF_OK;\n\t}\n\treturn GPMF_ERROR_MEMORY;\n}", "\nvoid *GPMF_RawData(GPMF_stream *ms)\n{\n\tif (ms)\n\t{\n\t\treturn (void *)&ms->buffer[ms->pos + 2];\n\t}\n\treturn NULL;\n}", "", "\nuint32_t GPMF_SizeofType(GPMF_SampleType type)\n{\n\tuint32_t ssize = 0;", "\tswitch ((int)type)\n\t{\n\tcase GPMF_TYPE_STRING_ASCII:\t\tssize = 1; break;\n\tcase GPMF_TYPE_SIGNED_BYTE:\t\t\tssize = 1; break;\n\tcase GPMF_TYPE_UNSIGNED_BYTE:\t\tssize = 1; break;", "\t// These datatypes are always be stored in Big-Endian\n\tcase GPMF_TYPE_SIGNED_SHORT:\t\tssize = 2; break;\n\tcase GPMF_TYPE_UNSIGNED_SHORT:\t\tssize = 2; break;\n\tcase GPMF_TYPE_FLOAT:\t\t\t\tssize = 4; break;\n\tcase GPMF_TYPE_FOURCC:\t\t\t\tssize = 4; break;\n\tcase GPMF_TYPE_SIGNED_LONG:\t\t\tssize = 4; break;\n\tcase GPMF_TYPE_UNSIGNED_LONG:\t\tssize = 4; break;\n\tcase GPMF_TYPE_Q15_16_FIXED_POINT: ssize = 4; break;\n\tcase GPMF_TYPE_Q31_32_FIXED_POINT: ssize = 8; break;\n\tcase GPMF_TYPE_DOUBLE:\t\t\t\tssize = 8; break;\n\tcase GPMF_TYPE_SIGNED_64BIT_INT:\tssize = 8; break;\n\tcase GPMF_TYPE_UNSIGNED_64BIT_INT: ssize = 8; break;", "\t//All unknown or larger than 8-bytes stored as is:\n\tcase GPMF_TYPE_GUID:\t\t\t\tssize = 16; break;\n\tcase GPMF_TYPE_UTC_DATE_TIME:\t\tssize = 16; break;\n\t}", "\treturn ssize;\n}", "uint32_t GPMF_ExpandComplexTYPE(char *src, uint32_t srcsize, char *dst, uint32_t *dstsize)\n{\n\tuint32_t i = 0, k = 0, count = 0;", "\twhile (i<srcsize && k<*dstsize)\n\t{\n\t\tif (src[i] == '[' && i>0)\n\t\t{\n\t\t\tint j = 1;\n\t\t\tcount = 0;\n\t\t\twhile (src[i + j] >= '0' && src[i + j] <= '9')\n\t\t\t{\n\t\t\t\tcount *= 10;\n\t\t\t\tcount += src[i + j] - '0';\n\t\t\t\tj++;\n\t\t\t}", "\t\t\tif (count > 1)\n\t\t\t{\n\t\t\t\tuint32_t l;\n\t\t\t\tfor (l = 1; l<count; l++)\n\t\t\t\t{\n\t\t\t\t\tdst[k] = src[i - 1];\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti += j;\n\t\t\tif (src[i] == ']') i++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdst[k] = src[i];\n\t\t\tif (dst[k] == 0) break;\n\t\t\ti++, k++;\n\t\t}\n\t}", "\tif (k >= *dstsize)\n\t\treturn GPMF_ERROR_MEMORY; // bad structure formed", "\tdst[k] = 0;\n\t*dstsize = k;", "\treturn GPMF_OK;\n}", "", "uint32_t GPMF_SizeOfComplexTYPE(char *type, uint32_t typestringlength)\n{\n\tchar *typearray = type;\n\tuint32_t size = 0, expand = 0;\n\tuint32_t i, len = typestringlength;", "\n\tfor (i = 0; i < len; i++)\n\t\tif (typearray[i] == '[')\n\t\t\texpand = 1;\n\t\t\t\n\tif (expand)\n\t{\n\t\tchar exptypearray[64];\n\t\tuint32_t dstsize = sizeof(exptypearray);", "\t\tif (GPMF_OK == GPMF_ExpandComplexTYPE(typearray, len, exptypearray, &dstsize))\n\t\t{\n\t\t\ttypearray = exptypearray;\n\t\t\tlen = dstsize;\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}", "\n\tfor (i = 0; i < len; i++)\n\t{\n\t\tuint32_t typesize = GPMF_SizeofType((GPMF_SampleType)typearray[i]);", "\t\tif (typesize < 1) return 0;\n\t\tsize += typesize;\n\t}", "\treturn size;\n}", "\nGPMF_ERR GPMF_FormattedData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples)\n{\n\tif (ms && buffer)\n\t{\n\t\tuint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2];\n\t\tuint8_t *output = (uint8_t *)buffer;\n\t\tuint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]);\n\t\tuint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]);\n\t\tuint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);\n\t\tuint32_t typesize = 1;\n\t\tuint32_t elements = 0;\n\t\tuint32_t typestringlength = 1;\n\t\tchar complextype[64] = \"L\";", "\t\tif (type == GPMF_TYPE_NEST)\n\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\n\t\tif (GPMF_OK != IsValidSize(ms, remaining_sample_size>>2))\n\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;", "\t\tif (sample_size * read_samples > buffersize)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\t\tremaining_sample_size -= sample_offset * sample_size; // skip samples\n\t\tdata += sample_offset * sample_size;", "\t\tif (remaining_sample_size < sample_size * read_samples)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\t\tif (type == GPMF_TYPE_COMPLEX)\n\t\t{\n\t\t\tGPMF_stream find_stream;\n\t\t\tGPMF_CopyState(ms, &find_stream);", "\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS))\n\t\t\t{\n\t\t\t\tchar *data1 = (char *)GPMF_RawData(&find_stream);\n\t\t\t\tint size = GPMF_RawDataSize(&find_stream);", "\t\t\t\ttypestringlength = sizeof(complextype);\n\t\t\t\tif (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength))\n\t\t\t\t{\n\t\t\t\t\telements = (uint32_t)strlen(complextype);", "\t\t\t\t\tif (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength))\n\t\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttypesize = GPMF_SizeofType((GPMF_SampleType)type);", "\t\t\tif (type == GPMF_TYPE_FOURCC)\n\t\t\t\ttypesize = 1; // Do not ByteSWAP", "\t\t\tif (typesize == 0)\n\t\t\t\treturn GPMF_ERROR_MEMORY;", "\t\t\telements = sample_size / typesize;\n\t\t}", "\t\twhile (read_samples--)\n\t\t{\n\t\t\tuint32_t i,j;", "\t\t\tfor (i = 0; i < elements; i++)\n\t\t\t{\n\t\t\t\tif (type == GPMF_TYPE_COMPLEX)\n\t\t\t\t{\n\t\t\t\t\tif (complextype[i] == GPMF_TYPE_FOURCC)\n\t\t\t\t\t{\n\t\t\t\t\t\t*output++ = *data++;\n\t\t\t\t\t\t*output++ = *data++;\n\t\t\t\t\t\t*output++ = *data++;\n\t\t\t\t\t\t*output++ = *data++;\n\t\t\t\t\t\ttypesize = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\ttypesize = GPMF_SizeofType(complextype[i]);\n\t\t\t\t}", "\t\t\t\tswitch (typesize)\n\t\t\t\t{\n\t\t\t\tcase 2:\n\t\t\t\t{\n\t\t\t\t\tuint16_t *data16 = (uint16_t *)data;\n\t\t\t\t\tuint16_t *output16 = (uint16_t *)output;\n\t\t\t\t\t*output16 = BYTESWAP16(*data16);\n\t\t\t\t\toutput16++;\n\t\t\t\t\tdata16++;", "\t\t\t\t\tdata = (uint8_t *)data16;\n\t\t\t\t\toutput = (uint8_t *)output16;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t{\n\t\t\t\t\tuint32_t *data32 = (uint32_t *)data;\n\t\t\t\t\tuint32_t *output32 = (uint32_t *)output;\n\t\t\t\t\t*output32 = BYTESWAP32(*data32);\n\t\t\t\t\toutput32++;\n\t\t\t\t\tdata32++;", "\t\t\t\t\tdata = (uint8_t *)data32;\n\t\t\t\t\toutput = (uint8_t *)output32;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t{\n\t\t\t\t\tuint32_t *data32 = (uint32_t *)data;\n\t\t\t\t\tuint32_t *output32 = (uint32_t *)output;\n\t\t\t\t\t*(output32+1) = BYTESWAP32(*data32);\n\t\t\t\t\t*(output32) = BYTESWAP32(*(data32+1));\n\t\t\t\t\tdata32 += 2;\n\t\t\t\t\toutput32 += 2;", "\t\t\t\t\tdata = (uint8_t *)data32;\n\t\t\t\t\toutput = (uint8_t *)output32;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tdefault: //1, 16 or more not byteswapped\n\t\t\t\t\tfor (j = 0; j < typesize; j++)\n\t\t\t\t\t\t*output++ = *data++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\treturn GPMF_OK;\n\t}", "\treturn GPMF_ERROR_MEMORY;\n}", "\n#define MACRO_CAST_SCALE_UNSIGNED_TYPE(casttype)\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tcasttype *tmp = (casttype *)output;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tswitch (scaletype)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tcase GPMF_TYPE_SIGNED_BYTE:\t\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int8_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_BYTE:\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint8_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_SIGNED_SHORT:\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int16_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_SHORT:\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint16_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_SIGNED_LONG:\t\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int32_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_LONG:\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint32_t *)scaledata8);\tbreak; \\\n\tcase GPMF_TYPE_FLOAT:\t\t\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((float *)scaledata8);\tbreak;\t\\\n\tdefault: break;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\toutput = (uint8_t *)tmp;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n}", "#define MACRO_CAST_SCALE_SIGNED_TYPE(casttype)\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tcasttype *tmp = (casttype *)output;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tswitch (scaletype)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tcase GPMF_TYPE_SIGNED_BYTE:\t\t*tmp++ = (casttype)*val / (casttype)*((int8_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_BYTE:\t*tmp++ = (casttype)*val / (casttype)*((uint8_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_SIGNED_SHORT:\t*tmp++ = (casttype)*val / (casttype)*((int16_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_SHORT:\t*tmp++ = (casttype)*val / (casttype)*((uint16_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_SIGNED_LONG:\t\t*tmp++ = (casttype)*val / (casttype)*((int32_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_LONG:\t*tmp++ = (casttype)*val / (casttype)*((uint32_t *)scaledata8);\tbreak; \\\n\tcase GPMF_TYPE_FLOAT:\t\t\t*tmp++ = (casttype)*val / (casttype)*((float *)scaledata8);\t\tbreak;\t\\\n\tdefault: break;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\toutput = (uint8_t *)tmp;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n}", "#define MACRO_CAST_SCALE\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tswitch (outputType)\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tcase GPMF_TYPE_SIGNED_BYTE: \tMACRO_CAST_SCALE_SIGNED_TYPE(int8_t)\tbreak;\t\t\\\n\t\tcase GPMF_TYPE_UNSIGNED_BYTE:\tMACRO_CAST_SCALE_UNSIGNED_TYPE(uint8_t)\tbreak;\t\t\\\n\t\tcase GPMF_TYPE_SIGNED_SHORT: \tMACRO_CAST_SCALE_SIGNED_TYPE(int16_t)\tbreak;\t\t\\\n\t\tcase GPMF_TYPE_UNSIGNED_SHORT:\tMACRO_CAST_SCALE_UNSIGNED_TYPE(uint16_t)\tbreak;\t\\\n\t\tcase GPMF_TYPE_FLOAT:\t\t\tMACRO_CAST_SCALE_SIGNED_TYPE(float)\tbreak;\t\t\t\\\n\t\tcase GPMF_TYPE_SIGNED_LONG:\t\tMACRO_CAST_SCALE_SIGNED_TYPE(int32_t)\tbreak;\t\t\\\n\t\tcase GPMF_TYPE_UNSIGNED_LONG:\tMACRO_CAST_SCALE_UNSIGNED_TYPE(uint32_t)\tbreak;\t\\\n\t\tcase GPMF_TYPE_DOUBLE:\t\t\tMACRO_CAST_SCALE_SIGNED_TYPE(double)\tbreak;\t\t\\\n\t\tdefault: break;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "#define MACRO_BSWAP_CAST_SCALE(swap, inputcast, tempcast)\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tinputcast *val;\t\t\t\t\t\t\t\t\t\t\\\n\ttempcast temp, *datatemp = (tempcast *)data;\t\t\\\n\ttemp = swap(*datatemp);\t\t\t\t\t\t\t\t\\\n\tval = (inputcast *)&temp;\t\t\t\t\t\t\t\\\n\tMACRO_CAST_SCALE\t\t\t\t\t\t\t\t\t\\\n\tdatatemp++;\t\t\t\t\t\t\t\t\t\t\t\\\n\tdata = (uint8_t *)datatemp;\t\t\t\t\t\t\t\\\n}", "GPMF_ERR GPMF_ScaledData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples, GPMF_SampleType outputType)\n{\n\tif (ms && buffer)\n\t{\n\t\tuint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2];\n\t\tuint8_t *output = (uint8_t *)buffer;\n\t\tuint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]);\n\t\tuint32_t output_sample_size = GPMF_SizeofType(outputType);\n\t\tuint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]);\n\t\tuint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);\n\t\tchar complextype[64] = \"L\";\n\t\tuint32_t inputtypesize = 0;\n\t\tuint32_t inputtypeelements = 0;\n\t\tuint8_t scaletype = 0;\n\t\tuint8_t scalecount = 0;\n\t\tuint32_t scaletypesize = 0;\n\t\tuint32_t *scaledata = NULL;\n\t\tuint32_t tmpbuffer[64];\n\t\tuint32_t tmpbuffersize = sizeof(tmpbuffer);\n\t\tuint32_t elements = 1;", "\t\ttype = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);", "\t\tif (type == GPMF_TYPE_NEST)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\t\tif (GPMF_OK != IsValidSize(ms, remaining_sample_size >> 2))\n\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;", "\t\tremaining_sample_size -= sample_offset * sample_size; // skip samples\n\t\tdata += sample_offset * sample_size;", "\t\tif (remaining_sample_size < sample_size * read_samples)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\t\tif (type == GPMF_TYPE_COMPLEX)\n\t\t{", "\t\t\tGPMF_stream find_stream;\n\t\t\tGPMF_CopyState(ms, &find_stream);", "\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS))\n\t\t\t{\n\t\t\t\tchar *data1 = (char *)GPMF_RawData(&find_stream);\n\t\t\t\tint size = GPMF_RawDataSize(&find_stream);\n\t\t\t\tuint32_t typestringlength = sizeof(complextype);\n\t\t\t\tif (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength))\n\t\t\t\t{\n\t\t\t\t\tinputtypeelements = elements = typestringlength;", "\t\t\t\t\tif (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength))\n\t\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcomplextype[0] = type;\n\t\t\tinputtypesize = GPMF_SizeofType(type);\n\t\t\tif (inputtypesize == 0)\n\t\t\t\treturn GPMF_ERROR_MEMORY;\n\t\t\tinputtypeelements = 1;\n\t\t\telements = sample_size / inputtypesize;\n\t\t}", "\t\tif (output_sample_size * elements * read_samples > buffersize)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\n\t\tswitch (outputType)\t{\n\t\tcase GPMF_TYPE_SIGNED_BYTE:\n\t\tcase GPMF_TYPE_UNSIGNED_BYTE:\n\t\tcase GPMF_TYPE_SIGNED_SHORT:\n\t\tcase GPMF_TYPE_UNSIGNED_SHORT:\n\t\tcase GPMF_TYPE_FLOAT:\n\t\tcase GPMF_TYPE_SIGNED_LONG:\n\t\tcase GPMF_TYPE_UNSIGNED_LONG:\n\t\tcase GPMF_TYPE_DOUBLE:\n\t\t\t// All supported formats.\n\t\t{\n\t\t\tGPMF_stream fs;\n\t\t\tGPMF_CopyState(ms, &fs);", "\t\t\tif (GPMF_OK == GPMF_FindPrev(&fs, GPMF_KEY_SCALE, GPMF_CURRENT_LEVEL))\n\t\t\t{\n\t\t\t\tscaledata = (uint32_t *)GPMF_RawData(&fs);\n\t\t\t\tscaletype = GPMF_SAMPLE_TYPE(fs.buffer[fs.pos + 1]);", "\t\t\t\tswitch (scaletype)\n\t\t\t\t{\n\t\t\t\tcase GPMF_TYPE_SIGNED_BYTE:\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_BYTE:\n\t\t\t\tcase GPMF_TYPE_SIGNED_SHORT:\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_SHORT:\n\t\t\t\tcase GPMF_TYPE_SIGNED_LONG:\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_LONG:\n\t\t\t\tcase GPMF_TYPE_FLOAT:\n\t\t\t\t\tscalecount = GPMF_SAMPLES(fs.buffer[fs.pos + 1]);\n\t\t\t\t\tscaletypesize = GPMF_SizeofType(scaletype);", "\t\t\t\t\tif (scalecount > 1)\n\t\t\t\t\t\tif (scalecount != elements)\n\t\t\t\t\t\t\treturn GPMF_ERROR_SCALE_COUNT;", "\t\t\t\t\tGPMF_FormattedData(&fs, tmpbuffer, tmpbuffersize, 0, scalecount);", "\t\t\t\t\tscaledata = (uint32_t *)tmpbuffer;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tscaletype = 'L';\n\t\t\t\tscalecount = 1;\n\t\t\t\ttmpbuffer[0] = 1; // set the scale to 1 is no scale was provided\n\t\t\t\tscaledata = (uint32_t *)tmpbuffer;\n\t\t\t}\n\t\t}", "\t\twhile (read_samples--)\n\t\t{\n\t\t\tuint32_t i;\n\t\t\tuint8_t *scaledata8 = (uint8_t *)scaledata;", "\t\t\tfor (i = 0; i < elements; i++)\n\t\t\t{\n\t\t\t\tswitch (complextype[i % inputtypeelements])\n\t\t\t\t{\n\t\t\t\tcase GPMF_TYPE_FLOAT: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, float, uint32_t) break;\n\t\t\t\tcase GPMF_TYPE_SIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, int8_t, uint8_t) break;\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, uint8_t, uint8_t) break;\n\t\t\t\tcase GPMF_TYPE_SIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, int16_t, uint16_t) break;\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, uint16_t, uint16_t) break;\n\t\t\t\tcase GPMF_TYPE_SIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, int32_t, uint32_t) break;\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, uint32_t, uint32_t) break;\n\t\t\t\tcase GPMF_TYPE_SIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break;\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break;\n\t\t\t\tdefault:\n\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (scalecount > 1)\n\t\t\t\t\tscaledata8 += scaletypesize;\n\t\t\t}\n\t\t}\n\t\tbreak;", "\t\tdefault:\n\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\tbreak;\n\t\t}", "\t\treturn GPMF_OK;\n\t}", "\treturn GPMF_ERROR_MEMORY;\n}" ]
[ 1, 0, 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 ]
PreciseBugs
{"buggy_code_end_loc": [46, 130, 244, 971, 114], "buggy_code_start_loc": [5, 5, 48, 5, 66], "filenames": ["GPMF_parser.c", "GPMF_parser.h", "demo/GPMF_demo.c", "demo/GPMF_mp4reader.c", "demo/GPMF_mp4reader.h"], "fixing_code_end_loc": [46, 134, 251, 1131, 115], "fixing_code_start_loc": [5, 5, 49, 5, 67], "message": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gopro:gpmf-parser:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "BA83C3BC-F72D-453A-B3E4-DB1065FC99A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c."}, {"lang": "es", "value": "GoPro GPMF-parser versi\u00f3n 1.2.2, presenta una lectura fuera de l\u00edmites y una SEGV en la funci\u00f3n GPMF_Next en el archivo GPMF_parser.c."}], "evaluatorComment": null, "id": "CVE-2019-15147", "lastModified": "2019-08-22T17:00:00.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-08-18T19:15:10.543", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/issues/60"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, "type": "CWE-125"}
236
Determine whether the {function_name} code is vulnerable or not.
[ "/*! @file GPMF_parser.c\n * \n * @brief GPMF Parser library\n *", " * @version 1.2.2", " * \n * (C) Copyright 2017 GoPro Inc (http://gopro.com/).\n *\t\n * Licensed under either:\n * - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 \n * - MIT license, http://opensource.org/licenses/MIT\n * at your option.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * \n */", "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdint.h>", "#include \"GPMF_parser.h\"", "\n#ifdef DBG\n#if _WINDOWS\n#define DBG_MSG printf\n#else\n#define DBG_MSG(...)\n#endif\n#else\n#define DBG_MSG(...)\n#endif", "\nGPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes.\n{\n\tif (ms)\n\t{", "\t\tuint32_t nestsize = (uint32_t)ms->nest_size[ms->nest_level];", "\t\tif (nestsize == 0 && ms->nest_level == 0)\n\t\t\tnestsize = ms->buffer_size_longs;", "\t\tif (size + 2 <= nestsize) return GPMF_OK;\n\t}\n\treturn GPMF_ERROR_BAD_STRUCTURE;\n}", "\nGPMF_ERR GPMF_Validate(GPMF_stream *ms, GPMF_LEVELS recurse)\n{\n\tif (ms)\n\t{\n\t\tuint32_t currpos = ms->pos;\n\t\tint32_t nestsize = (int32_t)ms->nest_size[ms->nest_level];\n\t\tif (nestsize == 0 && ms->nest_level == 0)\n\t\t\tnestsize = ms->buffer_size_longs;\n\t\t\n\t\twhile (ms->pos+1 < ms->buffer_size_longs && nestsize > 0)\n\t\t{\n\t\t\tuint32_t key = ms->buffer[ms->pos];", "\t\t\tif (ms->nest_level == 0 && key != GPMF_KEY_DEVICE && ms->device_count == 0 && ms->pos == 0)\n\t\t\t{\n\t\t\t\tDBG_MSG(\"ERROR: uninitized -- GPMF_ERROR_BAD_STRUCTURE\\n\");\n\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t}", "\t\t\tif (GPMF_VALID_FOURCC(key))\n\t\t\t{\n\t\t\t\tuint32_t type_size_repeat = ms->buffer[ms->pos + 1];\n\t\t\t\tint32_t size = GPMF_DATA_SIZE(type_size_repeat) >> 2;\n\t\t\t\tuint8_t type = GPMF_SAMPLE_TYPE(type_size_repeat);\n\t\t\t\tif (size + 2 > nestsize)\n\t\t\t\t{\n\t\t\t\t\tDBG_MSG(\"ERROR: nest size too small within %c%c%c%c-- GPMF_ERROR_BAD_STRUCTURE\\n\", PRINTF_4CC(key));\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t}", "\t\t\t\tif (!GPMF_VALID_FOURCC(key))\n\t\t\t\t{\n\t\t\t\t\tDBG_MSG(\"ERROR: invalid 4CC -- GPMF_ERROR_BAD_STRUCTURE\\n\");\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t}", "\t\t\t\tif (type == GPMF_TYPE_NEST && recurse == GPMF_RECURSE_LEVELS)\n\t\t\t\t{\n\t\t\t\t\tuint32_t validnest;\n\t\t\t\t\tms->pos += 2;\n\t\t\t\t\tms->nest_level++;\n\t\t\t\t\tif (ms->nest_level > GPMF_NEST_LIMIT)\n\t\t\t\t\t{\n\t\t\t\t\t\tDBG_MSG(\"ERROR: nest level within %c%c%c%c too deep -- GPMF_ERROR_BAD_STRUCTURE\\n\", PRINTF_4CC(key));\n\t\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t\t}\n\t\t\t\t\tms->nest_size[ms->nest_level] = size;\n\t\t\t\t\tvalidnest = GPMF_Validate(ms, recurse);\n\t\t\t\t\tms->nest_level--;\n\t\t\t\t\tif (GPMF_OK != validnest)\n\t\t\t\t\t{\n\t\t\t\t\t\tDBG_MSG(\"ERROR: invalid nest within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\\n\", PRINTF_4CC(key));\n\t\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (ms->nest_level == 0)\n\t\t\t\t\t\t\tms->device_count++;\n\t\t\t\t\t}", "\t\t\t\t\tms->pos += size;\n\t\t\t\t\tnestsize -= 2 + size;", "\t\t\t\t\twhile (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == GPMF_KEY_END)\n\t\t\t\t\t{\n\t\t\t\t\t\tms->pos++;\n\t\t\t\t\t\tnestsize--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tms->pos += 2 + size;\n\t\t\t\t\tnestsize -= 2 + size;\n\t\t\t\t}", "\t\t\t\tif (ms->pos == ms->buffer_size_longs)\n\t\t\t\t{\n\t\t\t\t\tms->pos = currpos;\n\t\t\t\t\treturn GPMF_OK;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (key == GPMF_KEY_END)\n\t\t\t\t{\n\t\t\t\t\tdo\n\t\t\t\t\t{\n\t\t\t\t\t\tms->pos++;\n\t\t\t\t\t\tnestsize--;\n\t\t\t\t\t} while (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == 0);\n\t\t\t\t}\n\t\t\t\telse if (ms->nest_level == 0 && ms->device_count > 0)\n\t\t\t\t{\n\t\t\t\t\tms->pos = currpos;\n\t\t\t\t\treturn GPMF_OK;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tDBG_MSG(\"ERROR: bad struct within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\\n\", PRINTF_4CC(key));\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\tms->pos = currpos;\n\t\treturn GPMF_OK;\n\t}\n\telse\n\t{\n\t\tDBG_MSG(\"ERROR: Invalid handle -- GPMF_ERROR_MEMORY\\n\");\n\t\treturn GPMF_ERROR_MEMORY;\n\t}\n}", "\nGPMF_ERR GPMF_ResetState(GPMF_stream *ms)\n{\n\tif (ms)\n\t{\n\t\tms->pos = 0;\n\t\tms->nest_level = 0;\n\t\tms->device_count = 0;\n\t\tms->nest_size[ms->nest_level] = 0;\n\t\tms->last_level_pos[ms->nest_level] = 0;\n\t\tms->last_seek[ms->nest_level] = 0;\n\t\tms->device_id = 0;\n\t\tms->device_name[0] = 0;", "\t\treturn GPMF_OK;\n\t}\n\t\n\treturn GPMF_ERROR_MEMORY;\n}", "\nGPMF_ERR GPMF_Init(GPMF_stream *ms, uint32_t *buffer, int datasize)\n{\n\tif(ms)\n\t{\n\t\tms->buffer = buffer;\n\t\tms->buffer_size_longs = datasize >>2;", "\t\tGPMF_ResetState(ms);", "\t\treturn GPMF_OK;\n\t}\n\t\n\treturn GPMF_ERROR_MEMORY;\n}", "\nGPMF_ERR GPMF_CopyState(GPMF_stream *msrc, GPMF_stream *mdst)\n{\n\tif (msrc && mdst)\n\t{\n\t\tmemcpy(mdst, msrc, sizeof(GPMF_stream));\n\t\treturn GPMF_OK;\n\t}\n\treturn GPMF_ERROR_MEMORY;\n}", "\nGPMF_ERR GPMF_Next(GPMF_stream *ms, GPMF_LEVELS recurse)\n{\n\tif (ms)\n\t{\n\t\tif (ms->pos+1 < ms->buffer_size_longs)\n\t\t{", "\t\t\tuint32_t key, type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);\n\t\t\tuint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2);", "\t\t\tif (GPMF_OK != IsValidSize(ms, size)) return GPMF_ERROR_BAD_STRUCTURE;", "\t\t\tif (GPMF_TYPE_NEST == type && GPMF_KEY_DEVICE == ms->buffer[ms->pos] && ms->nest_level == 0)\n\t\t\t{\n\t\t\t\tms->last_level_pos[ms->nest_level] = ms->pos;\n\t\t\t\tms->nest_size[ms->nest_level] = size;\n\t\t\t\tif (recurse)\n\t\t\t\t\tms->pos += 2;\n\t\t\t\telse\n\t\t\t\t\tms->pos += 2 + size;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (size + 2 > ms->nest_size[ms->nest_level])\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;", "\t\t\t\tif (recurse && type == GPMF_TYPE_NEST)\n\t\t\t\t{\n\t\t\t\t\tms->last_level_pos[ms->nest_level] = ms->pos;\n\t\t\t\t\tms->pos += 2;\n\t\t\t\t\tms->nest_size[ms->nest_level] -= size + 2;", "\t\t\t\t\tms->nest_level++;\n\t\t\t\t\tif (ms->nest_level > GPMF_NEST_LIMIT)\n\t\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;", "\t\t\t\t\tms->nest_size[ms->nest_level] = size;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (recurse)\n\t\t\t\t\t{\n\t\t\t\t\t\tms->pos += size + 2;\n\t\t\t\t\t\tms->nest_size[ms->nest_level] -= size + 2;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (ms->nest_size[ms->nest_level] - (size + 2) > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tms->pos += size + 2;\n\t\t\t\t\t\t\tms->nest_size[ms->nest_level] -= size + 2;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn GPMF_ERROR_LAST; \n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} ", "\t\t\twhile (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END)\n\t\t\t{\n\t\t\t\tms->pos++;\n\t\t\t\tms->nest_size[ms->nest_level]--;\n\t\t\t}", "\t\t\twhile (ms->nest_level > 0 && ms->nest_size[ms->nest_level] == 0)\n\t\t\t{\n\t\t\t\tms->nest_level--;\n\t\t\t\t//if (ms->nest_level == 0)\n\t\t\t\t//{\n\t\t\t\t//\tms->device_count++;\n\t\t\t\t//}\n\t\t\t}", "\t\t\tif (ms->pos < ms->buffer_size_longs)\n\t\t\t{\n\t\t\t\twhile (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END)\n\t\t\t\t{\n\t\t\t\t\tms->pos++;\n\t\t\t\t\tms->nest_size[ms->nest_level]--;\n\t\t\t\t}", "\t\t\t\tkey = ms->buffer[ms->pos];\n\t\t\t\tif (!GPMF_VALID_FOURCC(key))\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;", "\t\t\t\tif (key == GPMF_KEY_DEVICE_ID)\n\t\t\t\t\tms->device_id = BYTESWAP32(ms->buffer[ms->pos + 2]);\n\t\t\t\tif (key == GPMF_KEY_DEVICE_NAME)\n\t\t\t\t{\n\t\t\t\t\tsize = GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]); // in bytes\n\t\t\t\t\tif (size > sizeof(ms->device_name) - 1)\n\t\t\t\t\t\tsize = sizeof(ms->device_name) - 1;\n\t\t\t\t\tmemcpy(ms->device_name, &ms->buffer[ms->pos + 2], size);\n\t\t\t\t\tms->device_name[size] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// end of buffer\n\t\t\t\treturn GPMF_ERROR_BUFFER_END;\n\t\t\t}", "\t\t\treturn GPMF_OK;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// end of buffer\n\t\t\treturn GPMF_ERROR_BUFFER_END;\n\t\t}\n\t}\n\treturn GPMF_ERROR_MEMORY;\n}", "", "GPMF_ERR GPMF_FindNext(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse)\n{\n\tGPMF_stream prevstate;", "\tif (ms)\n\t{\n\t\tmemcpy(&prevstate, ms, sizeof(GPMF_stream));", "\t\tif (ms->pos < ms->buffer_size_longs)\n\t\t{\n\t\t\twhile (0 == GPMF_Next(ms, recurse))\n\t\t\t{\n\t\t\t\tif (ms->buffer[ms->pos] == fourcc)\n\t\t\t\t{\n\t\t\t\t\treturn GPMF_OK; //found match\n\t\t\t\t}\n\t\t\t}", "\t\t\t// restore read position\n\t\t\tmemcpy(ms, &prevstate, sizeof(GPMF_stream));\n\t\t\treturn GPMF_ERROR_FIND;\n\t\t}\n\t}\n\treturn GPMF_ERROR_FIND;\n}", "GPMF_ERR GPMF_Reserved(uint32_t key)\n{\n\tif(key == GPMF_KEY_DEVICE)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_DEVICE_ID)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_DEVICE_NAME)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_STREAM)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_STREAM_NAME)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_SI_UNITS)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_UNITS)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_SCALE)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_TYPE)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_TOTAL_SAMPLES)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_TICK)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_TOCK)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_EMPTY_PAYLOADS)\n\t\treturn GPMF_ERROR_RESERVED;", "\tif(key == GPMF_KEY_REMARK)\n\t\treturn GPMF_ERROR_RESERVED;", "\treturn GPMF_OK;\n}", "uint32_t GPMF_PayloadSampleCount(GPMF_stream *ms)\n{\n\tuint32_t count = 0;\n\tif (ms)\n\t{\n\t\tuint32_t fourcc = GPMF_Key(ms);", "\t\tGPMF_stream find_stream;\n\t\tGPMF_CopyState(ms, &find_stream);", "\t\tif (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats\n\t\t{\n\t\t\tcount=2;\n\t\t\twhile (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL))\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t} \n\t\t}\n\t\telse\n\t\t{\n\t\t\tcount = GPMF_Repeat(ms);\n\t\t}\n\t}\n\treturn count;\n}", "\nGPMF_ERR GPMF_SeekToSamples(GPMF_stream *ms)\n{\n\tGPMF_stream prevstate;", "\tif (ms)\n\t{", "\t\tif (ms->pos+1 < ms->buffer_size_longs)\n\t\t{\n\t\t\tuint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);", "\t\t\tmemcpy(&prevstate, ms, sizeof(GPMF_stream));", "\t\t\tif (type == GPMF_TYPE_NEST)\n\t\t\t\tGPMF_Next(ms, GPMF_RECURSE_LEVELS); // open STRM and recurse in", "\t\t\twhile (0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL))\n\t\t\t{\n\t\t\t\tuint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2);\n\t\t\t\tif (GPMF_OK != IsValidSize(ms, size))\n\t\t\t\t{\n\t\t\t\t\tmemcpy(ms, &prevstate, sizeof(GPMF_stream));\n\t\t\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\t\t}", "\t\t\t\ttype = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);", "\n\t\t\t\tif (type == GPMF_TYPE_NEST) // Nest with-in nest\n\t\t\t\t{\n\t\t\t\t\treturn GPMF_OK; //found match\n\t\t\t\t}", "\t\t\t\tif (size + 2 == ms->nest_size[ms->nest_level])\n\t\t\t\t{\n\t\t\t\t\tuint32_t key = GPMF_Key(ms);", "\t\t\t\t\tif (GPMF_ERROR_RESERVED == GPMF_Reserved(key))\n\t\t\t\t\t\treturn GPMF_ERROR_FIND;\n\t\t\t\t\t\n\t\t\t\t\treturn GPMF_OK; //found match\n\t\t\t\t}", "\t\t\t\tif (ms->buffer[ms->pos] == ms->buffer[ms->pos + size + 2]) // Matching tags\n\t\t\t\t{\n\t\t\t\t\treturn GPMF_OK; //found match\n\t\t\t\t}\n\t\t\t}", "\t\t\t// restore read position\n\t\t\tmemcpy(ms, &prevstate, sizeof(GPMF_stream));\n\t\t\treturn GPMF_ERROR_FIND;\n\t\t}\n\t}\n\treturn GPMF_ERROR_FIND;\n}", "\nGPMF_ERR GPMF_FindPrev(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse)\n{\n\tGPMF_stream prevstate;", "\tif (ms)\n\t{\n\t\tuint32_t curr_level = ms->nest_level;", "\t\tmemcpy(&prevstate, ms, sizeof(GPMF_stream));", "\t\tif (ms->pos < ms->buffer_size_longs && curr_level > 0)\n\t\t{", "\t\t\tdo\n\t\t\t{\n\t\t\t\tms->last_seek[curr_level] = ms->pos;\n\t\t\t\tms->pos = ms->last_level_pos[curr_level - 1] + 2;\n\t\t\t\tms->nest_size[curr_level] += ms->last_seek[curr_level] - ms->pos;\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\tif (ms->last_seek[curr_level] > ms->pos && ms->buffer[ms->pos] == fourcc)\n\t\t\t\t\t{", "\t\t\t\t\t\treturn GPMF_OK; //found match\n\t\t\t\t\t}\n\t\t\t\t} while (ms->last_seek[curr_level] > ms->pos && 0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL));", "\t\t\t\tcurr_level--;\n\t\t\t} while (recurse == GPMF_RECURSE_LEVELS && curr_level > 0);", "\t\t\t// restore read position\n\t\t\tmemcpy(ms, &prevstate, sizeof(GPMF_stream));", "\t\t\treturn GPMF_ERROR_FIND;\n\t\t}\n\t}", "\treturn GPMF_ERROR_FIND;\n}", "", "", "uint32_t GPMF_Key(GPMF_stream *ms)\n{\n\tif (ms)\n\t{\n\t\tuint32_t key = ms->buffer[ms->pos];\n\t\treturn key;\n\t}\n\treturn 0;\n}", "\nuint32_t GPMF_Type(GPMF_stream *ms)\n{\n\tif (ms && ms->pos+1 < ms->buffer_size_longs)\n\t{\n\t\tuint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos+1]);\n\t\treturn type;\n\t}\n\treturn 0;\n}", "\nuint32_t GPMF_StructSize(GPMF_stream *ms)\n{\n\tif (ms && ms->pos+1 < ms->buffer_size_longs)\n\t{\n\t\tuint32_t ssize = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]);\n\t\tuint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2);", "\t\tif (GPMF_OK != IsValidSize(ms, size)) return 0; // as the structure is corrupted. i.e. GPMF_ERROR_BAD_STRUCTURE;", "\t\treturn ssize;\n\t}\n\treturn 0;\n}", "\nuint32_t GPMF_ElementsInStruct(GPMF_stream *ms)\n{\n\tif (ms && ms->pos+1 < ms->buffer_size_longs)\n\t{\n\t\tuint32_t ssize = GPMF_StructSize(ms);\n\t\tGPMF_SampleType type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);", "\t\tif (type != GPMF_TYPE_NEST && type != GPMF_TYPE_COMPLEX)\n\t\t{\n\t\t\tint32_t tsize = GPMF_SizeofType(type);\n\t\t\tif (tsize > 0)\n\t\t\t\treturn ssize / tsize;\n\t\t\telse\n\t\t\t\treturn 0;\n\t\t}", "\t\tif (type == GPMF_TYPE_COMPLEX)\n\t\t{\n\t\t\tGPMF_stream find_stream;\n\t\t\tGPMF_CopyState(ms, &find_stream);", "\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL))\n\t\t\t{\n\t\t\t\tchar tmp[64] = \"\";\n\t\t\t\tuint32_t tmpsize = sizeof(tmp);\n\t\t\t\tchar *data = (char *)GPMF_RawData(&find_stream);\n\t\t\t\tint size = GPMF_RawDataSize(&find_stream);\n\t\t\t\t\n\t\t\t\tif (GPMF_OK == GPMF_ExpandComplexTYPE(data, size, tmp, &tmpsize))\n\t\t\t\t\treturn tmpsize;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}", "\nuint32_t GPMF_Repeat(GPMF_stream *ms)\n{\n\tif (ms && ms->pos+1 < ms->buffer_size_longs)\n\t{\n\t\tuint32_t repeat = GPMF_SAMPLES(ms->buffer[ms->pos + 1]);\n\t\treturn repeat;\n\t}\n\treturn 0;\n}", "uint32_t GPMF_RawDataSize(GPMF_stream *ms)\n{\n\tif (ms && ms->pos+1 < ms->buffer_size_longs)\n\t{\n\t\tuint32_t size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]);\n\t\tif (GPMF_OK != IsValidSize(ms, size >> 2)) return 0;", "\t\treturn size;\n\t}\n\treturn 0;\n}", "\nuint32_t GPMF_NestLevel(GPMF_stream *ms)\n{\n\tif (ms)\n\t{\n\t\treturn ms->nest_level;\n\t}\n\treturn 0;\n}", "uint32_t GPMF_DeviceID(GPMF_stream *ms)\n{\n\tif (ms)\n\t{\n\t\treturn ms->device_id;\n\t}\n\treturn 0;\n}", "GPMF_ERR GPMF_DeviceName(GPMF_stream *ms, char *devicenamebuf, uint32_t devicename_buf_size)\n{\n\tif (ms && devicenamebuf)\n\t{\n\t\tuint32_t len = (uint32_t)strlen(ms->device_name);\n\t\tif (len >= devicename_buf_size)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\t\tmemcpy(devicenamebuf, ms->device_name, len);\n\t\tdevicenamebuf[len] = 0;\n\t\treturn GPMF_OK;\n\t}\n\treturn GPMF_ERROR_MEMORY;\n}", "\nvoid *GPMF_RawData(GPMF_stream *ms)\n{\n\tif (ms)\n\t{\n\t\treturn (void *)&ms->buffer[ms->pos + 2];\n\t}\n\treturn NULL;\n}", "", "\nuint32_t GPMF_SizeofType(GPMF_SampleType type)\n{\n\tuint32_t ssize = 0;", "\tswitch ((int)type)\n\t{\n\tcase GPMF_TYPE_STRING_ASCII:\t\tssize = 1; break;\n\tcase GPMF_TYPE_SIGNED_BYTE:\t\t\tssize = 1; break;\n\tcase GPMF_TYPE_UNSIGNED_BYTE:\t\tssize = 1; break;", "\t// These datatypes are always be stored in Big-Endian\n\tcase GPMF_TYPE_SIGNED_SHORT:\t\tssize = 2; break;\n\tcase GPMF_TYPE_UNSIGNED_SHORT:\t\tssize = 2; break;\n\tcase GPMF_TYPE_FLOAT:\t\t\t\tssize = 4; break;\n\tcase GPMF_TYPE_FOURCC:\t\t\t\tssize = 4; break;\n\tcase GPMF_TYPE_SIGNED_LONG:\t\t\tssize = 4; break;\n\tcase GPMF_TYPE_UNSIGNED_LONG:\t\tssize = 4; break;\n\tcase GPMF_TYPE_Q15_16_FIXED_POINT: ssize = 4; break;\n\tcase GPMF_TYPE_Q31_32_FIXED_POINT: ssize = 8; break;\n\tcase GPMF_TYPE_DOUBLE:\t\t\t\tssize = 8; break;\n\tcase GPMF_TYPE_SIGNED_64BIT_INT:\tssize = 8; break;\n\tcase GPMF_TYPE_UNSIGNED_64BIT_INT: ssize = 8; break;", "\t//All unknown or larger than 8-bytes stored as is:\n\tcase GPMF_TYPE_GUID:\t\t\t\tssize = 16; break;\n\tcase GPMF_TYPE_UTC_DATE_TIME:\t\tssize = 16; break;\n\t}", "\treturn ssize;\n}", "uint32_t GPMF_ExpandComplexTYPE(char *src, uint32_t srcsize, char *dst, uint32_t *dstsize)\n{\n\tuint32_t i = 0, k = 0, count = 0;", "\twhile (i<srcsize && k<*dstsize)\n\t{\n\t\tif (src[i] == '[' && i>0)\n\t\t{\n\t\t\tint j = 1;\n\t\t\tcount = 0;\n\t\t\twhile (src[i + j] >= '0' && src[i + j] <= '9')\n\t\t\t{\n\t\t\t\tcount *= 10;\n\t\t\t\tcount += src[i + j] - '0';\n\t\t\t\tj++;\n\t\t\t}", "\t\t\tif (count > 1)\n\t\t\t{\n\t\t\t\tuint32_t l;\n\t\t\t\tfor (l = 1; l<count; l++)\n\t\t\t\t{\n\t\t\t\t\tdst[k] = src[i - 1];\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti += j;\n\t\t\tif (src[i] == ']') i++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdst[k] = src[i];\n\t\t\tif (dst[k] == 0) break;\n\t\t\ti++, k++;\n\t\t}\n\t}", "\tif (k >= *dstsize)\n\t\treturn GPMF_ERROR_MEMORY; // bad structure formed", "\tdst[k] = 0;\n\t*dstsize = k;", "\treturn GPMF_OK;\n}", "", "uint32_t GPMF_SizeOfComplexTYPE(char *type, uint32_t typestringlength)\n{\n\tchar *typearray = type;\n\tuint32_t size = 0, expand = 0;\n\tuint32_t i, len = typestringlength;", "\n\tfor (i = 0; i < len; i++)\n\t\tif (typearray[i] == '[')\n\t\t\texpand = 1;\n\t\t\t\n\tif (expand)\n\t{\n\t\tchar exptypearray[64];\n\t\tuint32_t dstsize = sizeof(exptypearray);", "\t\tif (GPMF_OK == GPMF_ExpandComplexTYPE(typearray, len, exptypearray, &dstsize))\n\t\t{\n\t\t\ttypearray = exptypearray;\n\t\t\tlen = dstsize;\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}", "\n\tfor (i = 0; i < len; i++)\n\t{\n\t\tuint32_t typesize = GPMF_SizeofType((GPMF_SampleType)typearray[i]);", "\t\tif (typesize < 1) return 0;\n\t\tsize += typesize;\n\t}", "\treturn size;\n}", "\nGPMF_ERR GPMF_FormattedData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples)\n{\n\tif (ms && buffer)\n\t{\n\t\tuint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2];\n\t\tuint8_t *output = (uint8_t *)buffer;\n\t\tuint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]);\n\t\tuint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]);\n\t\tuint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);\n\t\tuint32_t typesize = 1;\n\t\tuint32_t elements = 0;\n\t\tuint32_t typestringlength = 1;\n\t\tchar complextype[64] = \"L\";", "\t\tif (type == GPMF_TYPE_NEST)\n\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;\n\t\t\n\t\tif (GPMF_OK != IsValidSize(ms, remaining_sample_size>>2))\n\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;", "\t\tif (sample_size * read_samples > buffersize)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\t\tremaining_sample_size -= sample_offset * sample_size; // skip samples\n\t\tdata += sample_offset * sample_size;", "\t\tif (remaining_sample_size < sample_size * read_samples)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\t\tif (type == GPMF_TYPE_COMPLEX)\n\t\t{\n\t\t\tGPMF_stream find_stream;\n\t\t\tGPMF_CopyState(ms, &find_stream);", "\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS))\n\t\t\t{\n\t\t\t\tchar *data1 = (char *)GPMF_RawData(&find_stream);\n\t\t\t\tint size = GPMF_RawDataSize(&find_stream);", "\t\t\t\ttypestringlength = sizeof(complextype);\n\t\t\t\tif (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength))\n\t\t\t\t{\n\t\t\t\t\telements = (uint32_t)strlen(complextype);", "\t\t\t\t\tif (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength))\n\t\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttypesize = GPMF_SizeofType((GPMF_SampleType)type);", "\t\t\tif (type == GPMF_TYPE_FOURCC)\n\t\t\t\ttypesize = 1; // Do not ByteSWAP", "\t\t\tif (typesize == 0)\n\t\t\t\treturn GPMF_ERROR_MEMORY;", "\t\t\telements = sample_size / typesize;\n\t\t}", "\t\twhile (read_samples--)\n\t\t{\n\t\t\tuint32_t i,j;", "\t\t\tfor (i = 0; i < elements; i++)\n\t\t\t{\n\t\t\t\tif (type == GPMF_TYPE_COMPLEX)\n\t\t\t\t{\n\t\t\t\t\tif (complextype[i] == GPMF_TYPE_FOURCC)\n\t\t\t\t\t{\n\t\t\t\t\t\t*output++ = *data++;\n\t\t\t\t\t\t*output++ = *data++;\n\t\t\t\t\t\t*output++ = *data++;\n\t\t\t\t\t\t*output++ = *data++;\n\t\t\t\t\t\ttypesize = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\ttypesize = GPMF_SizeofType(complextype[i]);\n\t\t\t\t}", "\t\t\t\tswitch (typesize)\n\t\t\t\t{\n\t\t\t\tcase 2:\n\t\t\t\t{\n\t\t\t\t\tuint16_t *data16 = (uint16_t *)data;\n\t\t\t\t\tuint16_t *output16 = (uint16_t *)output;\n\t\t\t\t\t*output16 = BYTESWAP16(*data16);\n\t\t\t\t\toutput16++;\n\t\t\t\t\tdata16++;", "\t\t\t\t\tdata = (uint8_t *)data16;\n\t\t\t\t\toutput = (uint8_t *)output16;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t{\n\t\t\t\t\tuint32_t *data32 = (uint32_t *)data;\n\t\t\t\t\tuint32_t *output32 = (uint32_t *)output;\n\t\t\t\t\t*output32 = BYTESWAP32(*data32);\n\t\t\t\t\toutput32++;\n\t\t\t\t\tdata32++;", "\t\t\t\t\tdata = (uint8_t *)data32;\n\t\t\t\t\toutput = (uint8_t *)output32;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t{\n\t\t\t\t\tuint32_t *data32 = (uint32_t *)data;\n\t\t\t\t\tuint32_t *output32 = (uint32_t *)output;\n\t\t\t\t\t*(output32+1) = BYTESWAP32(*data32);\n\t\t\t\t\t*(output32) = BYTESWAP32(*(data32+1));\n\t\t\t\t\tdata32 += 2;\n\t\t\t\t\toutput32 += 2;", "\t\t\t\t\tdata = (uint8_t *)data32;\n\t\t\t\t\toutput = (uint8_t *)output32;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tdefault: //1, 16 or more not byteswapped\n\t\t\t\t\tfor (j = 0; j < typesize; j++)\n\t\t\t\t\t\t*output++ = *data++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\treturn GPMF_OK;\n\t}", "\treturn GPMF_ERROR_MEMORY;\n}", "\n#define MACRO_CAST_SCALE_UNSIGNED_TYPE(casttype)\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tcasttype *tmp = (casttype *)output;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tswitch (scaletype)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tcase GPMF_TYPE_SIGNED_BYTE:\t\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int8_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_BYTE:\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint8_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_SIGNED_SHORT:\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int16_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_SHORT:\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint16_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_SIGNED_LONG:\t\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int32_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_LONG:\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint32_t *)scaledata8);\tbreak; \\\n\tcase GPMF_TYPE_FLOAT:\t\t\t*tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((float *)scaledata8);\tbreak;\t\\\n\tdefault: break;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\toutput = (uint8_t *)tmp;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n}", "#define MACRO_CAST_SCALE_SIGNED_TYPE(casttype)\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tcasttype *tmp = (casttype *)output;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tswitch (scaletype)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tcase GPMF_TYPE_SIGNED_BYTE:\t\t*tmp++ = (casttype)*val / (casttype)*((int8_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_BYTE:\t*tmp++ = (casttype)*val / (casttype)*((uint8_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_SIGNED_SHORT:\t*tmp++ = (casttype)*val / (casttype)*((int16_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_SHORT:\t*tmp++ = (casttype)*val / (casttype)*((uint16_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_SIGNED_LONG:\t\t*tmp++ = (casttype)*val / (casttype)*((int32_t *)scaledata8);\tbreak;\t\\\n\tcase GPMF_TYPE_UNSIGNED_LONG:\t*tmp++ = (casttype)*val / (casttype)*((uint32_t *)scaledata8);\tbreak; \\\n\tcase GPMF_TYPE_FLOAT:\t\t\t*tmp++ = (casttype)*val / (casttype)*((float *)scaledata8);\t\tbreak;\t\\\n\tdefault: break;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\toutput = (uint8_t *)tmp;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n}", "#define MACRO_CAST_SCALE\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tswitch (outputType)\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tcase GPMF_TYPE_SIGNED_BYTE: \tMACRO_CAST_SCALE_SIGNED_TYPE(int8_t)\tbreak;\t\t\\\n\t\tcase GPMF_TYPE_UNSIGNED_BYTE:\tMACRO_CAST_SCALE_UNSIGNED_TYPE(uint8_t)\tbreak;\t\t\\\n\t\tcase GPMF_TYPE_SIGNED_SHORT: \tMACRO_CAST_SCALE_SIGNED_TYPE(int16_t)\tbreak;\t\t\\\n\t\tcase GPMF_TYPE_UNSIGNED_SHORT:\tMACRO_CAST_SCALE_UNSIGNED_TYPE(uint16_t)\tbreak;\t\\\n\t\tcase GPMF_TYPE_FLOAT:\t\t\tMACRO_CAST_SCALE_SIGNED_TYPE(float)\tbreak;\t\t\t\\\n\t\tcase GPMF_TYPE_SIGNED_LONG:\t\tMACRO_CAST_SCALE_SIGNED_TYPE(int32_t)\tbreak;\t\t\\\n\t\tcase GPMF_TYPE_UNSIGNED_LONG:\tMACRO_CAST_SCALE_UNSIGNED_TYPE(uint32_t)\tbreak;\t\\\n\t\tcase GPMF_TYPE_DOUBLE:\t\t\tMACRO_CAST_SCALE_SIGNED_TYPE(double)\tbreak;\t\t\\\n\t\tdefault: break;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "#define MACRO_BSWAP_CAST_SCALE(swap, inputcast, tempcast)\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tinputcast *val;\t\t\t\t\t\t\t\t\t\t\\\n\ttempcast temp, *datatemp = (tempcast *)data;\t\t\\\n\ttemp = swap(*datatemp);\t\t\t\t\t\t\t\t\\\n\tval = (inputcast *)&temp;\t\t\t\t\t\t\t\\\n\tMACRO_CAST_SCALE\t\t\t\t\t\t\t\t\t\\\n\tdatatemp++;\t\t\t\t\t\t\t\t\t\t\t\\\n\tdata = (uint8_t *)datatemp;\t\t\t\t\t\t\t\\\n}", "GPMF_ERR GPMF_ScaledData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples, GPMF_SampleType outputType)\n{\n\tif (ms && buffer)\n\t{\n\t\tuint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2];\n\t\tuint8_t *output = (uint8_t *)buffer;\n\t\tuint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]);\n\t\tuint32_t output_sample_size = GPMF_SizeofType(outputType);\n\t\tuint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]);\n\t\tuint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);\n\t\tchar complextype[64] = \"L\";\n\t\tuint32_t inputtypesize = 0;\n\t\tuint32_t inputtypeelements = 0;\n\t\tuint8_t scaletype = 0;\n\t\tuint8_t scalecount = 0;\n\t\tuint32_t scaletypesize = 0;\n\t\tuint32_t *scaledata = NULL;\n\t\tuint32_t tmpbuffer[64];\n\t\tuint32_t tmpbuffersize = sizeof(tmpbuffer);\n\t\tuint32_t elements = 1;", "\t\ttype = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);", "\t\tif (type == GPMF_TYPE_NEST)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\t\tif (GPMF_OK != IsValidSize(ms, remaining_sample_size >> 2))\n\t\t\treturn GPMF_ERROR_BAD_STRUCTURE;", "\t\tremaining_sample_size -= sample_offset * sample_size; // skip samples\n\t\tdata += sample_offset * sample_size;", "\t\tif (remaining_sample_size < sample_size * read_samples)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\t\tif (type == GPMF_TYPE_COMPLEX)\n\t\t{", "\t\t\tGPMF_stream find_stream;\n\t\t\tGPMF_CopyState(ms, &find_stream);", "\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS))\n\t\t\t{\n\t\t\t\tchar *data1 = (char *)GPMF_RawData(&find_stream);\n\t\t\t\tint size = GPMF_RawDataSize(&find_stream);\n\t\t\t\tuint32_t typestringlength = sizeof(complextype);\n\t\t\t\tif (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength))\n\t\t\t\t{\n\t\t\t\t\tinputtypeelements = elements = typestringlength;", "\t\t\t\t\tif (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength))\n\t\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcomplextype[0] = type;\n\t\t\tinputtypesize = GPMF_SizeofType(type);\n\t\t\tif (inputtypesize == 0)\n\t\t\t\treturn GPMF_ERROR_MEMORY;\n\t\t\tinputtypeelements = 1;\n\t\t\telements = sample_size / inputtypesize;\n\t\t}", "\t\tif (output_sample_size * elements * read_samples > buffersize)\n\t\t\treturn GPMF_ERROR_MEMORY;", "\n\t\tswitch (outputType)\t{\n\t\tcase GPMF_TYPE_SIGNED_BYTE:\n\t\tcase GPMF_TYPE_UNSIGNED_BYTE:\n\t\tcase GPMF_TYPE_SIGNED_SHORT:\n\t\tcase GPMF_TYPE_UNSIGNED_SHORT:\n\t\tcase GPMF_TYPE_FLOAT:\n\t\tcase GPMF_TYPE_SIGNED_LONG:\n\t\tcase GPMF_TYPE_UNSIGNED_LONG:\n\t\tcase GPMF_TYPE_DOUBLE:\n\t\t\t// All supported formats.\n\t\t{\n\t\t\tGPMF_stream fs;\n\t\t\tGPMF_CopyState(ms, &fs);", "\t\t\tif (GPMF_OK == GPMF_FindPrev(&fs, GPMF_KEY_SCALE, GPMF_CURRENT_LEVEL))\n\t\t\t{\n\t\t\t\tscaledata = (uint32_t *)GPMF_RawData(&fs);\n\t\t\t\tscaletype = GPMF_SAMPLE_TYPE(fs.buffer[fs.pos + 1]);", "\t\t\t\tswitch (scaletype)\n\t\t\t\t{\n\t\t\t\tcase GPMF_TYPE_SIGNED_BYTE:\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_BYTE:\n\t\t\t\tcase GPMF_TYPE_SIGNED_SHORT:\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_SHORT:\n\t\t\t\tcase GPMF_TYPE_SIGNED_LONG:\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_LONG:\n\t\t\t\tcase GPMF_TYPE_FLOAT:\n\t\t\t\t\tscalecount = GPMF_SAMPLES(fs.buffer[fs.pos + 1]);\n\t\t\t\t\tscaletypesize = GPMF_SizeofType(scaletype);", "\t\t\t\t\tif (scalecount > 1)\n\t\t\t\t\t\tif (scalecount != elements)\n\t\t\t\t\t\t\treturn GPMF_ERROR_SCALE_COUNT;", "\t\t\t\t\tGPMF_FormattedData(&fs, tmpbuffer, tmpbuffersize, 0, scalecount);", "\t\t\t\t\tscaledata = (uint32_t *)tmpbuffer;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tscaletype = 'L';\n\t\t\t\tscalecount = 1;\n\t\t\t\ttmpbuffer[0] = 1; // set the scale to 1 is no scale was provided\n\t\t\t\tscaledata = (uint32_t *)tmpbuffer;\n\t\t\t}\n\t\t}", "\t\twhile (read_samples--)\n\t\t{\n\t\t\tuint32_t i;\n\t\t\tuint8_t *scaledata8 = (uint8_t *)scaledata;", "\t\t\tfor (i = 0; i < elements; i++)\n\t\t\t{\n\t\t\t\tswitch (complextype[i % inputtypeelements])\n\t\t\t\t{\n\t\t\t\tcase GPMF_TYPE_FLOAT: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, float, uint32_t) break;\n\t\t\t\tcase GPMF_TYPE_SIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, int8_t, uint8_t) break;\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, uint8_t, uint8_t) break;\n\t\t\t\tcase GPMF_TYPE_SIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, int16_t, uint16_t) break;\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, uint16_t, uint16_t) break;\n\t\t\t\tcase GPMF_TYPE_SIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, int32_t, uint32_t) break;\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, uint32_t, uint32_t) break;\n\t\t\t\tcase GPMF_TYPE_SIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break;\n\t\t\t\tcase GPMF_TYPE_UNSIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break;\n\t\t\t\tdefault:\n\t\t\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (scalecount > 1)\n\t\t\t\t\tscaledata8 += scaletypesize;\n\t\t\t}\n\t\t}\n\t\tbreak;", "\t\tdefault:\n\t\t\treturn GPMF_ERROR_TYPE_NOT_SUPPORTED;\n\t\t\tbreak;\n\t\t}", "\t\treturn GPMF_OK;\n\t}", "\treturn GPMF_ERROR_MEMORY;\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 ]
PreciseBugs
{"buggy_code_end_loc": [46, 130, 244, 971, 114], "buggy_code_start_loc": [5, 5, 48, 5, 66], "filenames": ["GPMF_parser.c", "GPMF_parser.h", "demo/GPMF_demo.c", "demo/GPMF_mp4reader.c", "demo/GPMF_mp4reader.h"], "fixing_code_end_loc": [46, 134, 251, 1131, 115], "fixing_code_start_loc": [5, 5, 49, 5, 67], "message": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gopro:gpmf-parser:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "BA83C3BC-F72D-453A-B3E4-DB1065FC99A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c."}, {"lang": "es", "value": "GoPro GPMF-parser versi\u00f3n 1.2.2, presenta una lectura fuera de l\u00edmites y una SEGV en la funci\u00f3n GPMF_Next en el archivo GPMF_parser.c."}], "evaluatorComment": null, "id": "CVE-2019-15147", "lastModified": "2019-08-22T17:00:00.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-08-18T19:15:10.543", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/issues/60"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, "type": "CWE-125"}
236
Determine whether the {function_name} code is vulnerable or not.
[ "/*! @file GPMF_parser.h\n * \n * @brief GPMF Parser library include\n * ", " * @version 1.1.0", " * \n * (C) Copyright 2017 GoPro Inc (http://gopro.com/).\n *\t\n * Licensed under either:\n * - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 \n * - MIT license, http://opensource.org/licenses/MIT\n * at your option.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * \n */", "#ifndef _GPMF_PARSER_H\n#define _GPMF_PARSER_H", "#ifdef __cplusplus\nextern \"C\" {\n#endif", "#define GPMF_NEST_LIMIT 16", "typedef struct GPMF_stream\n{\n\tuint32_t *buffer;\n\tuint32_t buffer_size_longs;\n\tuint32_t pos;\n\tuint32_t last_level_pos[GPMF_NEST_LIMIT];\n\tuint32_t nest_size[GPMF_NEST_LIMIT];\n\tuint32_t last_seek[GPMF_NEST_LIMIT];\n\tuint32_t nest_level;\n\tuint32_t device_count;\n\tuint32_t device_id;\n\tchar device_name[32];\n} GPMF_stream;", "typedef enum GPMF_ERROR\n{\n\tGPMF_OK = 0,\n\tGPMF_ERROR_MEMORY,\n\tGPMF_ERROR_BAD_STRUCTURE,\n\tGPMF_ERROR_BUFFER_END,\n\tGPMF_ERROR_FIND,\n\tGPMF_ERROR_LAST,\n\tGPMF_ERROR_TYPE_NOT_SUPPORTED,\n\tGPMF_ERROR_SCALE_NOT_SUPPORTED,\n\tGPMF_ERROR_SCALE_COUNT,\n\tGPMF_ERROR_RESERVED\n} GPMF_ERROR;", "typedef enum GPMF_LEVELS\n{\n\tGPMF_CURRENT_LEVEL = 0,\n\tGPMF_RECURSE_LEVELS\n} GPMF_LEVELS;", "#define GPMF_ERR\tuint32_t", "typedef enum\n{\n\tGPMF_TYPE_STRING_ASCII = 'c', //single byte 'c' style character string\n\tGPMF_TYPE_SIGNED_BYTE = 'b',//single byte signed number\n\tGPMF_TYPE_UNSIGNED_BYTE = 'B', //single byte unsigned number\n\tGPMF_TYPE_SIGNED_SHORT = 's',//16-bit integer\n\tGPMF_TYPE_UNSIGNED_SHORT = 'S',//16-bit integer\n\tGPMF_TYPE_FLOAT = 'f', //32-bit single precision float (IEEE 754)\n\tGPMF_TYPE_FOURCC = 'F', //32-bit four character tag \n\tGPMF_TYPE_SIGNED_LONG = 'l',//32-bit integer\n\tGPMF_TYPE_UNSIGNED_LONG = 'L', //32-bit integer\n\tGPMF_TYPE_Q15_16_FIXED_POINT = 'q', // Q number Q15.16 - 16-bit signed integer (A) with 16-bit fixed point (B) for A.B value (range -32768.0 to 32767.99998). \n\tGPMF_TYPE_Q31_32_FIXED_POINT = 'Q', // Q number Q31.32 - 32-bit signed integer (A) with 32-bit fixed point (B) for A.B value. \n\tGPMF_TYPE_SIGNED_64BIT_INT = 'j', //64 bit signed long\n\tGPMF_TYPE_UNSIGNED_64BIT_INT = 'J', //64 bit unsigned long\t\n\tGPMF_TYPE_DOUBLE = 'd', //64 bit double precision float (IEEE 754)\n\tGPMF_TYPE_UTC_DATE_TIME = 'U', //128-bit ASCII Date + UTC Time format yymmddhhmmss.sss - 16 bytes ASCII (years 20xx covered)\n\tGPMF_TYPE_GUID = 'G', //128-bit ID (like UUID)", "\tGPMF_TYPE_COMPLEX = '?', //for sample with complex data structures, base size in bytes. Data is either opaque, or the stream has a TYPE structure field for the sample.", "\tGPMF_TYPE_NEST = 0, // used to nest more GPMF formatted metadata ", "} GPMF_SampleType;", "", "#define MAKEID(a,b,c,d)\t\t\t(((d&0xff)<<24)|((c&0xff)<<16)|((b&0xff)<<8)|(a&0xff))\n#define STR2FOURCC(s)\t\t\t((s[0]<<0)|(s[1]<<8)|(s[2]<<16)|(s[3]<<24))", "#define BYTESWAP64(a)\t\t\t(((a&0xff)<<56)|((a&0xff00)<<40)|((a&0xff0000)<<24)|((a&0xff000000)<<8) | ((a>>56)&0xff)|((a>>40)&0xff00)|((a>>24)&0xff0000)|((a>>8)&0xff000000) )\n#define BYTESWAP32(a)\t\t\t(((a&0xff)<<24)|((a&0xff00)<<8)|((a>>8)&0xff00)|((a>>24)&0xff))\n#define BYTESWAP16(a)\t\t\t((((a)>>8)&0xff)|(((a)<<8)&0xff00))\n#define NOSWAP8(a)\t\t\t\t(a)", "#define GPMF_SAMPLES(a)\t\t\t(((a>>24) & 0xff)|(((a>>16)&0xff)<<8))\n#define GPMF_SAMPLE_SIZE(a)\t\t(((a)>>8)&0xff)\n#define GPMF_SAMPLE_TYPE(a)\t\t(a&0xff)\n#define GPMF_MAKE_TYPE_SIZE_COUNT(t,s,c)\t\t((t)&0xff)|(((s)&0xff)<<8)|(((c)&0xff)<<24)|(((c)&0xff00)<<8)\n#define GPMF_DATA_SIZE(a)\t\t((GPMF_SAMPLE_SIZE(a)*GPMF_SAMPLES(a)+3)&~0x3)\n#define GPMF_DATA_PACKEDSIZE(a)\t((GPMF_SAMPLE_SIZE(a)*GPMF_SAMPLES(a)))\n#define GPMF_VALID_FOURCC(a)\t(((((a>>24)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>24)&0xff)>='A'&&((a>>24)&0xff)<='Z') || (((a>>24)&0xff)>='0'&&((a>>24)&0xff)<='9') || (((a>>24)&0xff)==' ') ) && \\\n\t\t\t\t\t\t\t\t( (((a>>16)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>16)&0xff)>='A'&&((a>>16)&0xff)<='Z') || (((a>>16)&0xff)>='0'&&((a>>16)&0xff)<='9') || (((a>>16)&0xff)==' ') ) && \\\n\t\t\t\t\t\t\t\t( (((a>>8)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>8)&0xff)>='A'&&((a>>8)&0xff)<='Z') || (((a>>8)&0xff)>='0'&&((a>>8)&0xff)<='9') || (((a>>8)&0xff)==' ') ) && \\\n\t\t\t\t\t\t\t\t( (((a>>0)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>0)&0xff)>='A'&&((a>>0)&0xff)<='Z') || (((a>>0)&0xff)>='0'&&((a>>0)&0xff)<='9') || (((a>>0)&0xff)==' ') )) \n#define GPMF_KEY_TYPE(a)\t\t(a&0xff)", "#define PRINTF_4CC(k)\t\t\t((k) >> 0) & 0xff, ((k) >> 8) & 0xff, ((k) >> 16) & 0xff, ((k) >> 24) & 0xff", " \ntypedef enum GPMFKey // TAG in all caps are GoPro preserved (are defined by GoPro, but can be used by others.)\n{\n\t// Internal Metadata structure and formatting tags\n\tGPMF_KEY_DEVICE =\t\t\tMAKEID('D','E','V','C'),//DEVC - nested device data to speed the parsing of multiple devices in post \n\tGPMF_KEY_DEVICE_ID =\t\tMAKEID('D','V','I','D'),//DVID - unique id per stream for a metadata source (in camera or external input) (single 4 byte int)\n\tGPMF_KEY_DEVICE_NAME =\t\tMAKEID('D','V','N','M'),//DVNM - human readable device type/name (char string)\n\tGPMF_KEY_STREAM =\t\t\tMAKEID('S','T','R','M'),//STRM - nested channel/stream of telemetry data\n\tGPMF_KEY_STREAM_NAME =\t\tMAKEID('S','T','N','M'),//STNM - human readable telemetry/metadata stream type/name (char string)\n\tGPMF_KEY_SI_UNITS =\t\t\tMAKEID('S','I','U','N'),//SIUN - Display string for metadata units where inputs are in SI units \"uT\",\"rad/s\",\"km/s\",\"m/s\",\"mm/s\" etc.\n\tGPMF_KEY_UNITS =\t\t\tMAKEID('U','N','I','T'),//UNIT - Freedform display string for metadata units (char sting like \"RPM\", \"MPH\", \"km/h\", etc)\n\tGPMF_KEY_SCALE =\t\t\tMAKEID('S','C','A','L'),//SCAL - divisor for input data to scale to the correct units.\n\tGPMF_KEY_TYPE =\t\t\t\tMAKEID('T','Y','P','E'),//TYPE - Type define for complex data structures", "\tGPMF_KEY_TOTAL_SAMPLES =\tMAKEID('T','S','M','P'),//TOTL - Total Sample Count including the current payload \t", "\tGPMF_KEY_TICK =\t\t\t\tMAKEID('T','I','C','K'),//TICK - Used for slow data. Beginning of data timing in milliseconds. \n\tGPMF_KEY_TOCK =\t\t\t\tMAKEID('T','O','C','K'),//TOCK - Used for slow data. End of data timing in milliseconds. \n\tGPMF_KEY_EMPTY_PAYLOADS =\tMAKEID('E','M','P','T'),//EMPT - Payloads that are empty since the device start (e.g. BLE disconnect.)\n\tGPMF_KEY_REMARK =\t\t\tMAKEID('R','M','R','K'),//RMRK - addcing comments to the bitstream (debugging)", "\tGPMF_KEY_END = 0//(null)\n} GPMFKey;", "", "// Prepare GPMF data \nGPMF_ERR GPMF_Init(GPMF_stream *gs, uint32_t *buffer, int datasize);\t\t\t\t\t\t\t//Initialize a GPMF_stream for parsing a particular buffer.\nGPMF_ERR GPMF_ResetState(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//Read from beginning of the buffer again\nGPMF_ERR GPMF_CopyState(GPMF_stream *src, GPMF_stream *dst);\t\t\t\t\t\t\t\t\t//Copy state, \nGPMF_ERR GPMF_Validate(GPMF_stream *gs, GPMF_LEVELS recurse);\t\t\t\t\t\t\t\t\t//Is the nest structure valid GPMF? ", "// Navigate through GPMF data \nGPMF_ERR GPMF_Next(GPMF_stream *gs, GPMF_LEVELS recurse);\t\t\t\t\t\t\t\t\t\t//Step to the next GPMF KLV entrance, optionally recurse up or down nesting levels.\nGPMF_ERR GPMF_FindPrev(GPMF_stream *gs, uint32_t fourCC, GPMF_LEVELS recurse);\t\t\t\t\t//find a previous FourCC -- at the current level only if recurse is false\nGPMF_ERR GPMF_FindNext(GPMF_stream *gs, uint32_t fourCC, GPMF_LEVELS recurse);\t\t\t\t\t//find a particular FourCC upcoming -- at the current level only if recurse is false\nGPMF_ERR GPMF_SeekToSamples(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t//find the last FourCC in the current level, this is raw data for any STRM", "// Get information about the current GPMF KLV\nuint32_t GPMF_Key(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current Key (FourCC)\nuint32_t GPMF_Type(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current Type (GPMF_Type)\nuint32_t GPMF_StructSize(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current sample structure size\nuint32_t GPMF_Repeat(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current repeat or the number of samples of this structure\nuint32_t GPMF_PayloadSampleCount(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current number of samples of this structure, supporting multisample entries.\nuint32_t GPMF_ElementsInStruct(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t//return the current number elements within the structure (e.g. 3-axis gyro)\nuint32_t GPMF_RawDataSize(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the data size for the current GPMF KLV \nvoid * GPMF_RawData(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return a pointer the KLV data (which is Bigendian if the type is known.)", "// Get information about where the GPMF KLV is nested\nuint32_t GPMF_NestLevel(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current nest level\nuint32_t GPMF_DeviceID(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current device ID (DVID), to seperate match sensor data from difference devices.\nGPMF_ERR GPMF_DeviceName(GPMF_stream *gs, char *devicename_buf, uint32_t devicename_buf_size);\t//return the current device name (DVNM), to seperate match sensor data from difference devices.", "// Utilities for data types\nuint32_t GPMF_SizeofType(GPMF_SampleType type);\t\t\t\t\t\t\t\t\t\t\t\t\t// GPMF equivalent to sizeof(type)\nuint32_t GPMF_ExpandComplexTYPE(char *src, uint32_t srcsize, char *dst, uint32_t *dstsize);\t\t// GPMF using TYPE for cmple structure. { float val[16],uin32_t flags; } has type \"f[8]L\", this tools expands to the simpler format \"ffffffffL\"\nuint32_t GPMF_SizeOfComplexTYPE(char *typearray, uint32_t typestringlength);\t\t\t\t\t// GPMF equivalent to sizeof(typedef) for complex types. \nGPMF_ERR GPMF_Reserved(uint32_t key);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Test for a reverse GPMF Key, returns GPMF_OK is not reversed.", "//Tools for extracting sensor data \nGPMF_ERR GPMF_FormattedData(GPMF_stream *gs, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples); // extract 'n' samples into local endian memory format.\nGPMF_ERR GPMF_ScaledData(GPMF_stream *gs, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples, GPMF_SampleType type); // extract 'n' samples into local endian memory format\t\t\t\t\t\t\t\t\t\t// return a point the KLV data.", "", "", "\n#ifdef __cplusplus\n}\n#endif", "#endif" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [46, 130, 244, 971, 114], "buggy_code_start_loc": [5, 5, 48, 5, 66], "filenames": ["GPMF_parser.c", "GPMF_parser.h", "demo/GPMF_demo.c", "demo/GPMF_mp4reader.c", "demo/GPMF_mp4reader.h"], "fixing_code_end_loc": [46, 134, 251, 1131, 115], "fixing_code_start_loc": [5, 5, 49, 5, 67], "message": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gopro:gpmf-parser:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "BA83C3BC-F72D-453A-B3E4-DB1065FC99A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c."}, {"lang": "es", "value": "GoPro GPMF-parser versi\u00f3n 1.2.2, presenta una lectura fuera de l\u00edmites y una SEGV en la funci\u00f3n GPMF_Next en el archivo GPMF_parser.c."}], "evaluatorComment": null, "id": "CVE-2019-15147", "lastModified": "2019-08-22T17:00:00.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-08-18T19:15:10.543", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/issues/60"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, "type": "CWE-125"}
236
Determine whether the {function_name} code is vulnerable or not.
[ "/*! @file GPMF_parser.h\n * \n * @brief GPMF Parser library include\n * ", " * @version 1.1.1", " * \n * (C) Copyright 2017 GoPro Inc (http://gopro.com/).\n *\t\n * Licensed under either:\n * - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 \n * - MIT license, http://opensource.org/licenses/MIT\n * at your option.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * \n */", "#ifndef _GPMF_PARSER_H\n#define _GPMF_PARSER_H", "#ifdef __cplusplus\nextern \"C\" {\n#endif", "#define GPMF_NEST_LIMIT 16", "typedef struct GPMF_stream\n{\n\tuint32_t *buffer;\n\tuint32_t buffer_size_longs;\n\tuint32_t pos;\n\tuint32_t last_level_pos[GPMF_NEST_LIMIT];\n\tuint32_t nest_size[GPMF_NEST_LIMIT];\n\tuint32_t last_seek[GPMF_NEST_LIMIT];\n\tuint32_t nest_level;\n\tuint32_t device_count;\n\tuint32_t device_id;\n\tchar device_name[32];\n} GPMF_stream;", "typedef enum GPMF_ERROR\n{\n\tGPMF_OK = 0,\n\tGPMF_ERROR_MEMORY,\n\tGPMF_ERROR_BAD_STRUCTURE,\n\tGPMF_ERROR_BUFFER_END,\n\tGPMF_ERROR_FIND,\n\tGPMF_ERROR_LAST,\n\tGPMF_ERROR_TYPE_NOT_SUPPORTED,\n\tGPMF_ERROR_SCALE_NOT_SUPPORTED,\n\tGPMF_ERROR_SCALE_COUNT,\n\tGPMF_ERROR_RESERVED\n} GPMF_ERROR;", "typedef enum GPMF_LEVELS\n{\n\tGPMF_CURRENT_LEVEL = 0,\n\tGPMF_RECURSE_LEVELS\n} GPMF_LEVELS;", "#define GPMF_ERR\tuint32_t", "typedef enum\n{\n\tGPMF_TYPE_STRING_ASCII = 'c', //single byte 'c' style character string\n\tGPMF_TYPE_SIGNED_BYTE = 'b',//single byte signed number\n\tGPMF_TYPE_UNSIGNED_BYTE = 'B', //single byte unsigned number\n\tGPMF_TYPE_SIGNED_SHORT = 's',//16-bit integer\n\tGPMF_TYPE_UNSIGNED_SHORT = 'S',//16-bit integer\n\tGPMF_TYPE_FLOAT = 'f', //32-bit single precision float (IEEE 754)\n\tGPMF_TYPE_FOURCC = 'F', //32-bit four character tag \n\tGPMF_TYPE_SIGNED_LONG = 'l',//32-bit integer\n\tGPMF_TYPE_UNSIGNED_LONG = 'L', //32-bit integer\n\tGPMF_TYPE_Q15_16_FIXED_POINT = 'q', // Q number Q15.16 - 16-bit signed integer (A) with 16-bit fixed point (B) for A.B value (range -32768.0 to 32767.99998). \n\tGPMF_TYPE_Q31_32_FIXED_POINT = 'Q', // Q number Q31.32 - 32-bit signed integer (A) with 32-bit fixed point (B) for A.B value. \n\tGPMF_TYPE_SIGNED_64BIT_INT = 'j', //64 bit signed long\n\tGPMF_TYPE_UNSIGNED_64BIT_INT = 'J', //64 bit unsigned long\t\n\tGPMF_TYPE_DOUBLE = 'd', //64 bit double precision float (IEEE 754)\n\tGPMF_TYPE_UTC_DATE_TIME = 'U', //128-bit ASCII Date + UTC Time format yymmddhhmmss.sss - 16 bytes ASCII (years 20xx covered)\n\tGPMF_TYPE_GUID = 'G', //128-bit ID (like UUID)", "\tGPMF_TYPE_COMPLEX = '?', //for sample with complex data structures, base size in bytes. Data is either opaque, or the stream has a TYPE structure field for the sample.", "\tGPMF_TYPE_NEST = 0, // used to nest more GPMF formatted metadata ", "} GPMF_SampleType;", "", "#define MAKEID(a,b,c,d)\t\t\t(((d&0xff)<<24)|((c&0xff)<<16)|((b&0xff)<<8)|(a&0xff))\n#define STR2FOURCC(s)\t\t\t((s[0]<<0)|(s[1]<<8)|(s[2]<<16)|(s[3]<<24))", "#define BYTESWAP64(a)\t\t\t(((a&0xff)<<56)|((a&0xff00)<<40)|((a&0xff0000)<<24)|((a&0xff000000)<<8) | ((a>>56)&0xff)|((a>>40)&0xff00)|((a>>24)&0xff0000)|((a>>8)&0xff000000) )\n#define BYTESWAP32(a)\t\t\t(((a&0xff)<<24)|((a&0xff00)<<8)|((a>>8)&0xff00)|((a>>24)&0xff))\n#define BYTESWAP16(a)\t\t\t((((a)>>8)&0xff)|(((a)<<8)&0xff00))\n#define NOSWAP8(a)\t\t\t\t(a)", "#define GPMF_SAMPLES(a)\t\t\t(((a>>24) & 0xff)|(((a>>16)&0xff)<<8))\n#define GPMF_SAMPLE_SIZE(a)\t\t(((a)>>8)&0xff)\n#define GPMF_SAMPLE_TYPE(a)\t\t(a&0xff)\n#define GPMF_MAKE_TYPE_SIZE_COUNT(t,s,c)\t\t((t)&0xff)|(((s)&0xff)<<8)|(((c)&0xff)<<24)|(((c)&0xff00)<<8)\n#define GPMF_DATA_SIZE(a)\t\t((GPMF_SAMPLE_SIZE(a)*GPMF_SAMPLES(a)+3)&~0x3)\n#define GPMF_DATA_PACKEDSIZE(a)\t((GPMF_SAMPLE_SIZE(a)*GPMF_SAMPLES(a)))\n#define GPMF_VALID_FOURCC(a)\t(((((a>>24)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>24)&0xff)>='A'&&((a>>24)&0xff)<='Z') || (((a>>24)&0xff)>='0'&&((a>>24)&0xff)<='9') || (((a>>24)&0xff)==' ') ) && \\\n\t\t\t\t\t\t\t\t( (((a>>16)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>16)&0xff)>='A'&&((a>>16)&0xff)<='Z') || (((a>>16)&0xff)>='0'&&((a>>16)&0xff)<='9') || (((a>>16)&0xff)==' ') ) && \\\n\t\t\t\t\t\t\t\t( (((a>>8)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>8)&0xff)>='A'&&((a>>8)&0xff)<='Z') || (((a>>8)&0xff)>='0'&&((a>>8)&0xff)<='9') || (((a>>8)&0xff)==' ') ) && \\\n\t\t\t\t\t\t\t\t( (((a>>0)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>0)&0xff)>='A'&&((a>>0)&0xff)<='Z') || (((a>>0)&0xff)>='0'&&((a>>0)&0xff)<='9') || (((a>>0)&0xff)==' ') )) \n#define GPMF_KEY_TYPE(a)\t\t(a&0xff)", "#define PRINTF_4CC(k)\t\t\t((k) >> 0) & 0xff, ((k) >> 8) & 0xff, ((k) >> 16) & 0xff, ((k) >> 24) & 0xff", " \ntypedef enum GPMFKey // TAG in all caps are GoPro preserved (are defined by GoPro, but can be used by others.)\n{\n\t// Internal Metadata structure and formatting tags\n\tGPMF_KEY_DEVICE =\t\t\tMAKEID('D','E','V','C'),//DEVC - nested device data to speed the parsing of multiple devices in post \n\tGPMF_KEY_DEVICE_ID =\t\tMAKEID('D','V','I','D'),//DVID - unique id per stream for a metadata source (in camera or external input) (single 4 byte int)\n\tGPMF_KEY_DEVICE_NAME =\t\tMAKEID('D','V','N','M'),//DVNM - human readable device type/name (char string)\n\tGPMF_KEY_STREAM =\t\t\tMAKEID('S','T','R','M'),//STRM - nested channel/stream of telemetry data\n\tGPMF_KEY_STREAM_NAME =\t\tMAKEID('S','T','N','M'),//STNM - human readable telemetry/metadata stream type/name (char string)\n\tGPMF_KEY_SI_UNITS =\t\t\tMAKEID('S','I','U','N'),//SIUN - Display string for metadata units where inputs are in SI units \"uT\",\"rad/s\",\"km/s\",\"m/s\",\"mm/s\" etc.\n\tGPMF_KEY_UNITS =\t\t\tMAKEID('U','N','I','T'),//UNIT - Freedform display string for metadata units (char sting like \"RPM\", \"MPH\", \"km/h\", etc)\n\tGPMF_KEY_SCALE =\t\t\tMAKEID('S','C','A','L'),//SCAL - divisor for input data to scale to the correct units.\n\tGPMF_KEY_TYPE =\t\t\t\tMAKEID('T','Y','P','E'),//TYPE - Type define for complex data structures", "\tGPMF_KEY_TOTAL_SAMPLES =\tMAKEID('T','S','M','P'),//TSMP - Total Sample Count including the current payload \t\n\tGPMF_KEY_TIME_OFFSET =\t\tMAKEID('T','I','M','O'),//TIMO - Time offset of the metadata stream that follows (single 4 byte float)\n\tGPMF_KEY_TIMING_OFFSET =\tMAKEID('T','I','M','O'),//TIMO - duplicated, as older code might use the other version of TIMO\n\tGPMF_KEY_TIME_STAMP =\t\tMAKEID('S','T','M','P'),//STMP - Time stamp for the first sample. \n\tGPMF_KEY_TIME_STAMPS =\t\tMAKEID('S','T','P','S'),//STPS - Stream of all the timestamps delivered (Generally don't use this. This would be if your sensor has no peroidic times, yet precision is required, or for debugging.) ", "\tGPMF_KEY_TICK =\t\t\t\tMAKEID('T','I','C','K'),//TICK - Used for slow data. Beginning of data timing in milliseconds. \n\tGPMF_KEY_TOCK =\t\t\t\tMAKEID('T','O','C','K'),//TOCK - Used for slow data. End of data timing in milliseconds. \n\tGPMF_KEY_EMPTY_PAYLOADS =\tMAKEID('E','M','P','T'),//EMPT - Payloads that are empty since the device start (e.g. BLE disconnect.)\n\tGPMF_KEY_REMARK =\t\t\tMAKEID('R','M','R','K'),//RMRK - addcing comments to the bitstream (debugging)", "\tGPMF_KEY_END = 0//(null)\n} GPMFKey;", "", "// Prepare GPMF data \nGPMF_ERR GPMF_Init(GPMF_stream *gs, uint32_t *buffer, int datasize);\t\t\t\t\t\t\t//Initialize a GPMF_stream for parsing a particular buffer.\nGPMF_ERR GPMF_ResetState(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//Read from beginning of the buffer again\nGPMF_ERR GPMF_CopyState(GPMF_stream *src, GPMF_stream *dst);\t\t\t\t\t\t\t\t\t//Copy state, \nGPMF_ERR GPMF_Validate(GPMF_stream *gs, GPMF_LEVELS recurse);\t\t\t\t\t\t\t\t\t//Is the nest structure valid GPMF? ", "// Navigate through GPMF data \nGPMF_ERR GPMF_Next(GPMF_stream *gs, GPMF_LEVELS recurse);\t\t\t\t\t\t\t\t\t\t//Step to the next GPMF KLV entrance, optionally recurse up or down nesting levels.\nGPMF_ERR GPMF_FindPrev(GPMF_stream *gs, uint32_t fourCC, GPMF_LEVELS recurse);\t\t\t\t\t//find a previous FourCC -- at the current level only if recurse is false\nGPMF_ERR GPMF_FindNext(GPMF_stream *gs, uint32_t fourCC, GPMF_LEVELS recurse);\t\t\t\t\t//find a particular FourCC upcoming -- at the current level only if recurse is false\nGPMF_ERR GPMF_SeekToSamples(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t//find the last FourCC in the current level, this is raw data for any STRM", "// Get information about the current GPMF KLV\nuint32_t GPMF_Key(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current Key (FourCC)\nuint32_t GPMF_Type(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current Type (GPMF_Type)\nuint32_t GPMF_StructSize(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current sample structure size\nuint32_t GPMF_Repeat(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current repeat or the number of samples of this structure\nuint32_t GPMF_PayloadSampleCount(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current number of samples of this structure, supporting multisample entries.\nuint32_t GPMF_ElementsInStruct(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t//return the current number elements within the structure (e.g. 3-axis gyro)\nuint32_t GPMF_RawDataSize(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the data size for the current GPMF KLV \nvoid * GPMF_RawData(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return a pointer the KLV data (which is Bigendian if the type is known.)", "// Get information about where the GPMF KLV is nested\nuint32_t GPMF_NestLevel(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current nest level\nuint32_t GPMF_DeviceID(GPMF_stream *gs);\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the current device ID (DVID), to seperate match sensor data from difference devices.\nGPMF_ERR GPMF_DeviceName(GPMF_stream *gs, char *devicename_buf, uint32_t devicename_buf_size);\t//return the current device name (DVNM), to seperate match sensor data from difference devices.", "// Utilities for data types\nuint32_t GPMF_SizeofType(GPMF_SampleType type);\t\t\t\t\t\t\t\t\t\t\t\t\t// GPMF equivalent to sizeof(type)\nuint32_t GPMF_ExpandComplexTYPE(char *src, uint32_t srcsize, char *dst, uint32_t *dstsize);\t\t// GPMF using TYPE for cmple structure. { float val[16],uin32_t flags; } has type \"f[8]L\", this tools expands to the simpler format \"ffffffffL\"\nuint32_t GPMF_SizeOfComplexTYPE(char *typearray, uint32_t typestringlength);\t\t\t\t\t// GPMF equivalent to sizeof(typedef) for complex types. \nGPMF_ERR GPMF_Reserved(uint32_t key);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Test for a reverse GPMF Key, returns GPMF_OK is not reversed.", "//Tools for extracting sensor data \nGPMF_ERR GPMF_FormattedData(GPMF_stream *gs, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples); // extract 'n' samples into local endian memory format.\nGPMF_ERR GPMF_ScaledData(GPMF_stream *gs, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples, GPMF_SampleType type); // extract 'n' samples into local endian memory format\t\t\t\t\t\t\t\t\t\t// return a point the KLV data.", "", "", "\n#ifdef __cplusplus\n}\n#endif", "#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [46, 130, 244, 971, 114], "buggy_code_start_loc": [5, 5, 48, 5, 66], "filenames": ["GPMF_parser.c", "GPMF_parser.h", "demo/GPMF_demo.c", "demo/GPMF_mp4reader.c", "demo/GPMF_mp4reader.h"], "fixing_code_end_loc": [46, 134, 251, 1131, 115], "fixing_code_start_loc": [5, 5, 49, 5, 67], "message": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gopro:gpmf-parser:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "BA83C3BC-F72D-453A-B3E4-DB1065FC99A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c."}, {"lang": "es", "value": "GoPro GPMF-parser versi\u00f3n 1.2.2, presenta una lectura fuera de l\u00edmites y una SEGV en la funci\u00f3n GPMF_Next en el archivo GPMF_parser.c."}], "evaluatorComment": null, "id": "CVE-2019-15147", "lastModified": "2019-08-22T17:00:00.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-08-18T19:15:10.543", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/issues/60"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, "type": "CWE-125"}
236
Determine whether the {function_name} code is vulnerable or not.
[ "/*! @file GPMF_demo.c\n *\n * @brief Demo to extract GPMF from an MP4\n *\n * @version 1.0.1\n *\n * (C) Copyright 2017 GoPro Inc (http://gopro.com/).\n *\t\n * Licensed under either:\n * - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 \n * - MIT license, http://opensource.org/licenses/MIT\n * at your option.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */", "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdint.h>", "#include \"../GPMF_parser.h\"\n#include \"GPMF_mp4reader.h\"", "\nextern void PrintGPMF(GPMF_stream *ms);", "int main(int argc, char *argv[])\n{\n\tint32_t ret = GPMF_OK;\n\tGPMF_stream metadata_stream, *ms = &metadata_stream;\n\tdouble metadatalength;\n\tuint32_t *payload = NULL; //buffer to store GPMF samples from the MP4.", "\n\t// get file return data\n\tif (argc != 2)\n\t{\n\t\tprintf(\"usage: %s <file_with_GPMF>\\n\", argv[0]);\n\t\treturn -1;\n\t}", "\tsize_t mp4 = OpenMP4Source(argv[1], MOV_GPMF_TRAK_TYPE, MOV_GPMF_TRAK_SUBTYPE);", "", "//\tsize_t mp4 = OpenMP4SourceUDTA(argv[1]); //Search for GPMF payload with MP4's udta ", "\tmetadatalength = GetDuration(mp4);", "\tif (metadatalength > 0.0)\n\t{\n\t\tuint32_t index, payloads = GetNumberPayloads(mp4);\n//\t\tprintf(\"found %.2fs of metadata, from %d payloads, within %s\\n\", metadatalength, payloads, argv[1]);", "#if 1\n\t\tif (payloads == 1) // Printf the contents of the single payload\n\t\t{\n\t\t\tuint32_t payloadsize = GetPayloadSize(mp4,0);\n\t\t\tpayload = GetPayload(mp4, payload, 0);\n\t\t\tif(payload == NULL)\n\t\t\t\tgoto cleanup;", "\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\t\t\tif (ret != GPMF_OK)\n\t\t\t\tgoto cleanup;", "\t\t\t// Output (printf) all the contained GPMF data within this payload\n\t\t\tret = GPMF_Validate(ms, GPMF_RECURSE_LEVELS); // optional\n\t\t\tif (GPMF_OK != ret)\n\t\t\t{\n\t\t\t\tprintf(\"Invalid Structure\\n\");\n\t\t\t\tgoto cleanup;\n\t\t\t}", "\t\t\tGPMF_ResetState(ms);\n\t\t\tdo\n\t\t\t{\n\t\t\t\tPrintGPMF(ms); // printf current GPMF KLV\n\t\t\t} while (GPMF_OK == GPMF_Next(ms, GPMF_RECURSE_LEVELS));\n\t\t\tGPMF_ResetState(ms);\n\t\t\tprintf(\"\\n\");", "\t\t}\n#endif", "\n\t\tfor (index = 0; index < payloads; index++)\n\t\t{\n\t\t\tuint32_t payloadsize = GetPayloadSize(mp4, index);", "\t\t\tfloat in = 0.0, out = 0.0; //times", "\t\t\tpayload = GetPayload(mp4, payload, index);\n\t\t\tif (payload == NULL)\n\t\t\t\tgoto cleanup;", "\t\t\tret = GetPayloadTime(mp4, index, &in, &out);\n\t\t\tif (ret != GPMF_OK)\n\t\t\t\tgoto cleanup;", "\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\t\t\tif (ret != GPMF_OK)\n\t\t\t\tgoto cleanup;", "#if 1\t\t// Find all the available Streams and the data carrying FourCC\n\t\t\tif (index == 0) // show first payload \n\t\t\t{\n\t\t\t\tret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);\n\t\t\t\twhile (GPMF_OK == ret)\n\t\t\t\t{\n\t\t\t\t\tret = GPMF_SeekToSamples(ms);\n\t\t\t\t\tif (GPMF_OK == ret) //find the last FOURCC within the stream\n\t\t\t\t\t{\n\t\t\t\t\t\tuint32_t key = GPMF_Key(ms);\n\t\t\t\t\t\tGPMF_SampleType type = GPMF_Type(ms);\n\t\t\t\t\t\tuint32_t elements = GPMF_ElementsInStruct(ms);\n\t\t\t\t\t\t//uint32_t samples = GPMF_Repeat(ms);\n\t\t\t\t\t\tuint32_t samples = GPMF_PayloadSampleCount(ms);", "\t\t\t\t\t\tif (samples)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprintf(\" STRM of %c%c%c%c \", PRINTF_4CC(key));", "\t\t\t\t\t\t\tif (type == GPMF_TYPE_COMPLEX)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tGPMF_stream find_stream;\n\t\t\t\t\t\t\t\tGPMF_CopyState(ms, &find_stream);", "\t\t\t\t\t\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tchar tmp[64];\n\t\t\t\t\t\t\t\t\tchar *data = (char *)GPMF_RawData(&find_stream);\n\t\t\t\t\t\t\t\t\tint size = GPMF_RawDataSize(&find_stream);", "\t\t\t\t\t\t\t\t\tif (size < sizeof(tmp))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tmemcpy(tmp, data, size);\n\t\t\t\t\t\t\t\t\t\ttmp[size] = 0;\n\t\t\t\t\t\t\t\t\t\tprintf(\"of type %s \", tmp);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tprintf(\"of type %c \", type);\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tprintf(\"with %d sample%s \", samples, samples > 1 ? \"s\" : \"\");", "\t\t\t\t\t\t\tif (elements > 1)\n\t\t\t\t\t\t\t\tprintf(\"-- %d elements per sample\", elements);", "\t\t\t\t\t\t\tprintf(\"\\n\");\n\t\t\t\t\t\t}", "\t\t\t\t\t\tret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (ret == GPMF_ERROR_BAD_STRUCTURE) // some payload element was corrupt, skip to the next valid GPMF KLV at the previous level.\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tret = GPMF_Next(ms, GPMF_CURRENT_LEVEL); // this will be the next stream if any more are present.\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tGPMF_ResetState(ms);\n\t\t\t\tprintf(\"\\n\");\n\t\t\t}\n#endif ", "", "\n#if 1\t\t// Find GPS values and return scaled doubles. \n\t\t\tif (index == 0) // show first payload \n\t\t\t{\n\t\t\t\tif (GPMF_OK == GPMF_FindNext(ms, STR2FOURCC(\"GPS5\"), GPMF_RECURSE_LEVELS) || //GoPro Hero5/6/7 GPS\n\t\t\t\t\tGPMF_OK == GPMF_FindNext(ms, STR2FOURCC(\"GPRI\"), GPMF_RECURSE_LEVELS)) //GoPro Karma GPS\n\t\t\t\t{\n\t\t\t\t\tuint32_t key = GPMF_Key(ms);\n\t\t\t\t\tuint32_t samples = GPMF_Repeat(ms);\n\t\t\t\t\tuint32_t elements = GPMF_ElementsInStruct(ms);\n\t\t\t\t\tuint32_t buffersize = samples * elements * sizeof(double);\n\t\t\t\t\tGPMF_stream find_stream;\n\t\t\t\t\tdouble *ptr, *tmpbuffer = malloc(buffersize);\n\t\t\t\t\tchar units[10][6] = { \"\" };\n\t\t\t\t\tuint32_t unit_samples = 1;", "\t\t\t\t\tprintf(\"MP4 Payload time %.3f to %.3f seconds\\n\", in, out);", "\t\t\t\t\tif (tmpbuffer && samples)\n\t\t\t\t\t{\n\t\t\t\t\t\tuint32_t i, j;", "\t\t\t\t\t\t//Search for any units to display\n\t\t\t\t\t\tGPMF_CopyState(ms, &find_stream);\n\t\t\t\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_SI_UNITS, GPMF_CURRENT_LEVEL) ||\n\t\t\t\t\t\t\tGPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_UNITS, GPMF_CURRENT_LEVEL))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tchar *data = (char *)GPMF_RawData(&find_stream);\n\t\t\t\t\t\t\tint ssize = GPMF_StructSize(&find_stream);\n\t\t\t\t\t\t\tunit_samples = GPMF_Repeat(&find_stream);", "\t\t\t\t\t\t\tfor (i = 0; i < unit_samples; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmemcpy(units[i], data, ssize);\n\t\t\t\t\t\t\t\tunits[i][ssize] = 0;\n\t\t\t\t\t\t\t\tdata += ssize;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}", "\t\t\t\t\t\t//GPMF_FormattedData(ms, tmpbuffer, buffersize, 0, samples); // Output data in LittleEnd, but no scale\n\t\t\t\t\t\tGPMF_ScaledData(ms, tmpbuffer, buffersize, 0, samples, GPMF_TYPE_DOUBLE); //Output scaled data as floats", "\t\t\t\t\t\tptr = tmpbuffer;\n\t\t\t\t\t\tfor (i = 0; i < samples; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprintf(\"%c%c%c%c \", PRINTF_4CC(key));\n\t\t\t\t\t\t\tfor (j = 0; j < elements; j++)\n\t\t\t\t\t\t\t\tprintf(\"%.3f%s, \", *ptr++, units[j%unit_samples]);", "\t\t\t\t\t\t\tprintf(\"\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfree(tmpbuffer);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tGPMF_ResetState(ms);\n\t\t\t\tprintf(\"\\n\");\n\t\t\t}\n#endif \n\t\t}", "#if 1\n\t\t// Find all the available Streams and compute they sample rates\n\t\twhile (GPMF_OK == GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS))\n\t\t{\n\t\t\tif (GPMF_OK == GPMF_SeekToSamples(ms)) //find the last FOURCC within the stream\n\t\t\t{", "", "\t\t\t\tuint32_t fourcc = GPMF_Key(ms);", "\t\t\t\tdouble rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE);// GPMF_SAMPLE_RATE_FAST);\n\t\t\t\tprintf(\"%c%c%c%c sampling rate = %f Hz\\n\", PRINTF_4CC(fourcc), rate);", "\t\t\t}\n\t\t}\n#endif", "\n\tcleanup:\n\t\tif (payload) FreePayload(payload); payload = NULL;\n\t\tCloseSource(mp4);\n\t}", "\treturn ret;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 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, 0, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [46, 130, 244, 971, 114], "buggy_code_start_loc": [5, 5, 48, 5, 66], "filenames": ["GPMF_parser.c", "GPMF_parser.h", "demo/GPMF_demo.c", "demo/GPMF_mp4reader.c", "demo/GPMF_mp4reader.h"], "fixing_code_end_loc": [46, 134, 251, 1131, 115], "fixing_code_start_loc": [5, 5, 49, 5, 67], "message": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gopro:gpmf-parser:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "BA83C3BC-F72D-453A-B3E4-DB1065FC99A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c."}, {"lang": "es", "value": "GoPro GPMF-parser versi\u00f3n 1.2.2, presenta una lectura fuera de l\u00edmites y una SEGV en la funci\u00f3n GPMF_Next en el archivo GPMF_parser.c."}], "evaluatorComment": null, "id": "CVE-2019-15147", "lastModified": "2019-08-22T17:00:00.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-08-18T19:15:10.543", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/issues/60"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, "type": "CWE-125"}
236
Determine whether the {function_name} code is vulnerable or not.
[ "/*! @file GPMF_demo.c\n *\n * @brief Demo to extract GPMF from an MP4\n *\n * @version 1.0.1\n *\n * (C) Copyright 2017 GoPro Inc (http://gopro.com/).\n *\t\n * Licensed under either:\n * - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 \n * - MIT license, http://opensource.org/licenses/MIT\n * at your option.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */", "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdint.h>", "#include \"../GPMF_parser.h\"\n#include \"GPMF_mp4reader.h\"", "\nextern void PrintGPMF(GPMF_stream *ms);", "int main(int argc, char *argv[])\n{\n\tint32_t ret = GPMF_OK;\n\tGPMF_stream metadata_stream, *ms = &metadata_stream;\n\tdouble metadatalength;\n\tuint32_t *payload = NULL; //buffer to store GPMF samples from the MP4.", "\n\t// get file return data\n\tif (argc != 2)\n\t{\n\t\tprintf(\"usage: %s <file_with_GPMF>\\n\", argv[0]);\n\t\treturn -1;\n\t}", "\tsize_t mp4 = OpenMP4Source(argv[1], MOV_GPMF_TRAK_TYPE, MOV_GPMF_TRAK_SUBTYPE);", "\tif (mp4 == 0)\n\t{\n\t\tprintf(\"error: %s is an invalid MP4/MOV\\n\", argv[1]);\n\t\treturn -1;\n\t}\n", "//\tsize_t mp4 = OpenMP4SourceUDTA(argv[1]); //Search for GPMF payload with MP4's udta ", "\tmetadatalength = GetDuration(mp4);", "\tif (metadatalength > 0.0)\n\t{\n\t\tuint32_t index, payloads = GetNumberPayloads(mp4);\n//\t\tprintf(\"found %.2fs of metadata, from %d payloads, within %s\\n\", metadatalength, payloads, argv[1]);", "#if 1\n\t\tif (payloads == 1) // Printf the contents of the single payload\n\t\t{\n\t\t\tuint32_t payloadsize = GetPayloadSize(mp4,0);\n\t\t\tpayload = GetPayload(mp4, payload, 0);\n\t\t\tif(payload == NULL)\n\t\t\t\tgoto cleanup;", "\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\t\t\tif (ret != GPMF_OK)\n\t\t\t\tgoto cleanup;", "\t\t\t// Output (printf) all the contained GPMF data within this payload\n\t\t\tret = GPMF_Validate(ms, GPMF_RECURSE_LEVELS); // optional\n\t\t\tif (GPMF_OK != ret)\n\t\t\t{\n\t\t\t\tprintf(\"Invalid Structure\\n\");\n\t\t\t\tgoto cleanup;\n\t\t\t}", "\t\t\tGPMF_ResetState(ms);\n\t\t\tdo\n\t\t\t{\n\t\t\t\tPrintGPMF(ms); // printf current GPMF KLV\n\t\t\t} while (GPMF_OK == GPMF_Next(ms, GPMF_RECURSE_LEVELS));\n\t\t\tGPMF_ResetState(ms);\n\t\t\tprintf(\"\\n\");", "\t\t}\n#endif", "\n\t\tfor (index = 0; index < payloads; index++)\n\t\t{\n\t\t\tuint32_t payloadsize = GetPayloadSize(mp4, index);", "\t\t\tdouble in = 0.0, out = 0.0; //times", "\t\t\tpayload = GetPayload(mp4, payload, index);\n\t\t\tif (payload == NULL)\n\t\t\t\tgoto cleanup;", "\t\t\tret = GetPayloadTime(mp4, index, &in, &out);\n\t\t\tif (ret != GPMF_OK)\n\t\t\t\tgoto cleanup;", "\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\t\t\tif (ret != GPMF_OK)\n\t\t\t\tgoto cleanup;", "#if 1\t\t// Find all the available Streams and the data carrying FourCC\n\t\t\tif (index == 0) // show first payload \n\t\t\t{\n\t\t\t\tret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);\n\t\t\t\twhile (GPMF_OK == ret)\n\t\t\t\t{\n\t\t\t\t\tret = GPMF_SeekToSamples(ms);\n\t\t\t\t\tif (GPMF_OK == ret) //find the last FOURCC within the stream\n\t\t\t\t\t{\n\t\t\t\t\t\tuint32_t key = GPMF_Key(ms);\n\t\t\t\t\t\tGPMF_SampleType type = GPMF_Type(ms);\n\t\t\t\t\t\tuint32_t elements = GPMF_ElementsInStruct(ms);\n\t\t\t\t\t\t//uint32_t samples = GPMF_Repeat(ms);\n\t\t\t\t\t\tuint32_t samples = GPMF_PayloadSampleCount(ms);", "\t\t\t\t\t\tif (samples)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprintf(\" STRM of %c%c%c%c \", PRINTF_4CC(key));", "\t\t\t\t\t\t\tif (type == GPMF_TYPE_COMPLEX)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tGPMF_stream find_stream;\n\t\t\t\t\t\t\t\tGPMF_CopyState(ms, &find_stream);", "\t\t\t\t\t\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tchar tmp[64];\n\t\t\t\t\t\t\t\t\tchar *data = (char *)GPMF_RawData(&find_stream);\n\t\t\t\t\t\t\t\t\tint size = GPMF_RawDataSize(&find_stream);", "\t\t\t\t\t\t\t\t\tif (size < sizeof(tmp))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tmemcpy(tmp, data, size);\n\t\t\t\t\t\t\t\t\t\ttmp[size] = 0;\n\t\t\t\t\t\t\t\t\t\tprintf(\"of type %s \", tmp);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tprintf(\"of type %c \", type);\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tprintf(\"with %d sample%s \", samples, samples > 1 ? \"s\" : \"\");", "\t\t\t\t\t\t\tif (elements > 1)\n\t\t\t\t\t\t\t\tprintf(\"-- %d elements per sample\", elements);", "\t\t\t\t\t\t\tprintf(\"\\n\");\n\t\t\t\t\t\t}", "\t\t\t\t\t\tret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (ret == GPMF_ERROR_BAD_STRUCTURE) // some payload element was corrupt, skip to the next valid GPMF KLV at the previous level.\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tret = GPMF_Next(ms, GPMF_CURRENT_LEVEL); // this will be the next stream if any more are present.\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tGPMF_ResetState(ms);\n\t\t\t\tprintf(\"\\n\");\n\t\t\t}\n#endif ", "", "\n#if 1\t\t// Find GPS values and return scaled doubles. \n\t\t\tif (index == 0) // show first payload \n\t\t\t{\n\t\t\t\tif (GPMF_OK == GPMF_FindNext(ms, STR2FOURCC(\"GPS5\"), GPMF_RECURSE_LEVELS) || //GoPro Hero5/6/7 GPS\n\t\t\t\t\tGPMF_OK == GPMF_FindNext(ms, STR2FOURCC(\"GPRI\"), GPMF_RECURSE_LEVELS)) //GoPro Karma GPS\n\t\t\t\t{\n\t\t\t\t\tuint32_t key = GPMF_Key(ms);\n\t\t\t\t\tuint32_t samples = GPMF_Repeat(ms);\n\t\t\t\t\tuint32_t elements = GPMF_ElementsInStruct(ms);\n\t\t\t\t\tuint32_t buffersize = samples * elements * sizeof(double);\n\t\t\t\t\tGPMF_stream find_stream;\n\t\t\t\t\tdouble *ptr, *tmpbuffer = malloc(buffersize);\n\t\t\t\t\tchar units[10][6] = { \"\" };\n\t\t\t\t\tuint32_t unit_samples = 1;", "\t\t\t\t\tprintf(\"MP4 Payload time %.3f to %.3f seconds\\n\", in, out);", "\t\t\t\t\tif (tmpbuffer && samples)\n\t\t\t\t\t{\n\t\t\t\t\t\tuint32_t i, j;", "\t\t\t\t\t\t//Search for any units to display\n\t\t\t\t\t\tGPMF_CopyState(ms, &find_stream);\n\t\t\t\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_SI_UNITS, GPMF_CURRENT_LEVEL) ||\n\t\t\t\t\t\t\tGPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_UNITS, GPMF_CURRENT_LEVEL))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tchar *data = (char *)GPMF_RawData(&find_stream);\n\t\t\t\t\t\t\tint ssize = GPMF_StructSize(&find_stream);\n\t\t\t\t\t\t\tunit_samples = GPMF_Repeat(&find_stream);", "\t\t\t\t\t\t\tfor (i = 0; i < unit_samples; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmemcpy(units[i], data, ssize);\n\t\t\t\t\t\t\t\tunits[i][ssize] = 0;\n\t\t\t\t\t\t\t\tdata += ssize;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}", "\t\t\t\t\t\t//GPMF_FormattedData(ms, tmpbuffer, buffersize, 0, samples); // Output data in LittleEnd, but no scale\n\t\t\t\t\t\tGPMF_ScaledData(ms, tmpbuffer, buffersize, 0, samples, GPMF_TYPE_DOUBLE); //Output scaled data as floats", "\t\t\t\t\t\tptr = tmpbuffer;\n\t\t\t\t\t\tfor (i = 0; i < samples; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprintf(\"%c%c%c%c \", PRINTF_4CC(key));\n\t\t\t\t\t\t\tfor (j = 0; j < elements; j++)\n\t\t\t\t\t\t\t\tprintf(\"%.3f%s, \", *ptr++, units[j%unit_samples]);", "\t\t\t\t\t\t\tprintf(\"\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfree(tmpbuffer);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tGPMF_ResetState(ms);\n\t\t\t\tprintf(\"\\n\");\n\t\t\t}\n#endif \n\t\t}", "#if 1\n\t\t// Find all the available Streams and compute they sample rates\n\t\twhile (GPMF_OK == GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS))\n\t\t{\n\t\t\tif (GPMF_OK == GPMF_SeekToSamples(ms)) //find the last FOURCC within the stream\n\t\t\t{", "\t\t\t\tdouble in = 0.0, out = 0.0;", "\t\t\t\tuint32_t fourcc = GPMF_Key(ms);", "\t\t\t\tdouble rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE, &in, &out);// GPMF_SAMPLE_RATE_FAST);\n\t\t\t\tprintf(\"%c%c%c%c sampling rate = %f Hz (from %f to %f)\\n\", PRINTF_4CC(fourcc), rate, in, out);", "\t\t\t}\n\t\t}\n#endif", "\n\tcleanup:\n\t\tif (payload) FreePayload(payload); payload = NULL;\n\t\tCloseSource(mp4);\n\t}", "\treturn ret;\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 ]
PreciseBugs
{"buggy_code_end_loc": [46, 130, 244, 971, 114], "buggy_code_start_loc": [5, 5, 48, 5, 66], "filenames": ["GPMF_parser.c", "GPMF_parser.h", "demo/GPMF_demo.c", "demo/GPMF_mp4reader.c", "demo/GPMF_mp4reader.h"], "fixing_code_end_loc": [46, 134, 251, 1131, 115], "fixing_code_start_loc": [5, 5, 49, 5, 67], "message": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gopro:gpmf-parser:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "BA83C3BC-F72D-453A-B3E4-DB1065FC99A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c."}, {"lang": "es", "value": "GoPro GPMF-parser versi\u00f3n 1.2.2, presenta una lectura fuera de l\u00edmites y una SEGV en la funci\u00f3n GPMF_Next en el archivo GPMF_parser.c."}], "evaluatorComment": null, "id": "CVE-2019-15147", "lastModified": "2019-08-22T17:00:00.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-08-18T19:15:10.543", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/issues/60"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, "type": "CWE-125"}
236
Determine whether the {function_name} code is vulnerable or not.
[ "/*! @file mp4reader.c\n*\n* @brief Way Too Crude MP4|MOV reader\n*", "* @version 1.2.1", "*", "* (C) Copyright 2017 GoPro Inc (http://gopro.com/).", "*", "* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0", "*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*/\n", "/* This is not an elegant MP4 parser, only used to help demonstrate extraction of MP4 */\n", "\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdint.h>", "", "#include \"GPMF_mp4reader.h\"", "#define PRINT_MP4_STRUCTURE\t\t0", "#ifdef WIN32", "#define LONGSEEK _fseeki64", "#else", "#define LONGSEEK fseeko", "#endif", "\nuint32_t GetNumberPayloads(size_t handle)\n{\n\tmp4object *mp4 = (mp4object *)handle;", "\tif (mp4)\n\t{\n\t\treturn mp4->indexcount;\n\t}", "\treturn 0;\n}\n", "", "uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return NULL;", "\tuint32_t *MP4buffer = NULL;\n\tif (index < mp4->indexcount && mp4->mediafp)\n\t{\n\t\tMP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]);", "\t\tif (MP4buffer)\n\t\t{", "\t\t\tLONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET);\n\t\t\tfread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp);\n\t\t\treturn MP4buffer;", "\t\t}\n\t}\n\treturn NULL;\n}", "", "void SavePayload(size_t handle, uint32_t *payload, uint32_t index)", "{", "\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return;", "\tuint32_t *MP4buffer = NULL;\n\tif (index < mp4->indexcount && mp4->mediafp && payload)", "\t{", "\t\tLONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET);\n\t\tfwrite(payload, 1, mp4->metasizes[index], mp4->mediafp);", "\t}", "\treturn;", "}", "\n", "\nvoid FreePayload(uint32_t *lastpayload)\n{\n\tif (lastpayload)\n\t\tfree(lastpayload);\n}", "\nuint32_t GetPayloadSize(size_t handle, uint32_t index)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0;", "\tif (mp4->metasizes && mp4->metasize_count > index)\n\t\treturn mp4->metasizes[index];", "\treturn 0;\n}\n", "", "#define MAX_NEST_LEVEL\t20", "size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) //RAW or within MP4\n{\n\tmp4object *mp4 = (mp4object *)malloc(sizeof(mp4object));\n\tif (mp4 == NULL) return 0;", "\tmemset(mp4, 0, sizeof(mp4object));", "", "\n#ifdef _WINDOWS\n\tfopen_s(&mp4->mediafp, filename, \"rb\");\n#else\n\tmp4->mediafp = fopen(filename, \"rb\");\n#endif", "\tif (mp4->mediafp)\n\t{\n\t\tuint32_t qttag, qtsize32, skip, type = 0, subtype = 0, num;\n\t\tsize_t len;\n\t\tint32_t nest = 0;\n\t\tuint64_t nestsize[MAX_NEST_LEVEL] = { 0 };\n\t\tuint64_t lastsize = 0, qtsize;\n", "", "\t\tdo\n\t\t{\n\t\t\tlen = fread(&qtsize32, 1, 4, mp4->mediafp);\n\t\t\tlen += fread(&qttag, 1, 4, mp4->mediafp);", "\t\t\tif (len == 8)", "\t\t\t{\n\t\t\t\tif (!VALID_FOURCC(qttag))\n\t\t\t\t{", "\t\t\t\t\tLONGSEEK(mp4->mediafp, lastsize - 8 - 8, SEEK_CUR);", "\t\t\t\t\tNESTSIZE(lastsize - 8);\n\t\t\t\t\tcontinue;", "\t\t\t\t}", "\t\t\t\tqtsize32 = BYTESWAP32(qtsize32);", "\t\t\t\tif (qtsize32 == 1) // 64-bit Atom\n\t\t\t\t{", "\t\t\t\t\tfread(&qtsize, 1, 8, mp4->mediafp);", "\t\t\t\t\tqtsize = BYTESWAP64(qtsize) - 8;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tqtsize = qtsize32;", "\t\t\t\tnest++;", "\t\t\t\tif (qtsize < 8) break;\n\t\t\t\tif (nest >= MAX_NEST_LEVEL) break;", "\t\t\t\tnestsize[nest] = qtsize;\n\t\t\t\tlastsize = qtsize;", "#if PRINT_MP4_STRUCTURE\t", "\t\t\t\tfor (int i = 1; i < nest; i++) printf(\" \");\n\t\t\t\tprintf(\"%c%c%c%c (%lld)\\n\", (qttag & 0xff), ((qttag >> 8) & 0xff), ((qttag >> 16) & 0xff), ((qttag >> 24) & 0xff), qtsize);", "\t\t\t\tif (qttag == MAKEID('m', 'd', 'a', 't') ||\n\t\t\t\t\tqttag == MAKEID('f', 't', 'y', 'p') ||", "\t\t\t\t\tqttag == MAKEID('u', 'd', 't', 'a'))\n\t\t\t\t{\n\t\t\t\t\tLONGSEEK(mediafp, qtsize - 8, SEEK_CUR);", "\n\t\t\t\t\tNESTSIZE(qtsize);", "\t\t\t\t\tcontinue;\n\t\t\t\t}\n#else\n\t\t\t\tif (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms\n\t\t\t\t\tqttag != MAKEID('m', 'v', 'h', 'd') &&\n\t\t\t\t\tqttag != MAKEID('t', 'r', 'a', 'k') &&\n\t\t\t\t\tqttag != MAKEID('m', 'd', 'i', 'a') &&\n\t\t\t\t\tqttag != MAKEID('m', 'd', 'h', 'd') &&\n\t\t\t\t\tqttag != MAKEID('m', 'i', 'n', 'f') &&\n\t\t\t\t\tqttag != MAKEID('g', 'm', 'i', 'n') &&\n\t\t\t\t\tqttag != MAKEID('d', 'i', 'n', 'f') &&\n\t\t\t\t\tqttag != MAKEID('a', 'l', 'i', 's') &&\n\t\t\t\t\tqttag != MAKEID('s', 't', 's', 'd') &&", "\t\t\t\t\tqttag != MAKEID('a', 'l', 'i', 's') &&\n\t\t\t\t\tqttag != MAKEID('a', 'l', 'i', 's') &&", "\t\t\t\t\tqttag != MAKEID('s', 't', 'b', 'l') &&\n\t\t\t\t\tqttag != MAKEID('s', 't', 't', 's') &&\n\t\t\t\t\tqttag != MAKEID('s', 't', 's', 'c') &&\n\t\t\t\t\tqttag != MAKEID('s', 't', 's', 'z') &&\n\t\t\t\t\tqttag != MAKEID('s', 't', 'c', 'o') &&\n\t\t\t\t\tqttag != MAKEID('c', 'o', '6', '4') &&\n\t\t\t\t\tqttag != MAKEID('h', 'd', 'l', 'r'))\n\t\t\t\t{", "\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);", "\n\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t}\n\t\t\t\telse\n#endif\n\t\t\t\t\tif (qttag == MAKEID('m', 'v', 'h', 'd')) //mvhd movie header\n\t\t\t\t\t{\n\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\tlen += fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\tlen += fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\tlen += fread(&mp4->clockdemon, 1, 4, mp4->mediafp); mp4->clockdemon = BYTESWAP32(mp4->clockdemon);\n\t\t\t\t\t\tlen += fread(&mp4->clockcount, 1, 4, mp4->mediafp); mp4->clockcount = BYTESWAP32(mp4->clockcount);", "\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over mvhd", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('m', 'd', 'h', 'd')) //mdhd media header\n\t\t\t\t\t{\n\t\t\t\t\t\tmedia_header md;\n\t\t\t\t\t\tlen = fread(&md, 1, sizeof(md), mp4->mediafp);\n\t\t\t\t\t\tif (len == sizeof(md))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmd.creation_time = BYTESWAP32(md.creation_time);\n\t\t\t\t\t\t\tmd.modification_time = BYTESWAP32(md.modification_time);\n\t\t\t\t\t\t\tmd.time_scale = BYTESWAP32(md.time_scale);\n\t\t\t\t\t\t\tmd.duration = BYTESWAP32(md.duration);", "\t\t\t\t\t\t\tmp4->trak_clockdemon = md.time_scale;\n\t\t\t\t\t\t\tmp4->trak_clockcount = md.duration;", "\t\t\t\t\t\t\tif (mp4->videolength == 0.0) // Get the video length from the first track\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmp4->videolength = (float)((double)mp4->trak_clockcount / (double)mp4->trak_clockdemon);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}", "\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over mvhd", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('h', 'd', 'l', 'r')) //hldr\n\t\t\t\t\t{\n\t\t\t\t\t\tuint32_t temp;\n\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\tlen += fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\tlen += fread(&temp, 1, 4, mp4->mediafp); // type will be 'meta' for the correct trak.\n", "\t\t\t\t\t\tif (temp != MAKEID('a', 'l', 'i', 's'))", "\t\t\t\t\t\t\ttype = temp;\n", "\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over hldr", "\n\t\t\t\t\t\tNESTSIZE(qtsize);", "\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('s', 't', 's', 'd')) //read the sample decription to determine the type of metadata\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) //like meta\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&subtype, 1, 4, mp4->mediafp); // type will be 'meta' for the correct trak.\n\t\t\t\t\t\t\tif (len == 16)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (subtype != traksubtype) // MP4 metadata \n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype = 0; // MP4\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stsd", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('s', 't', 's', 'c')) // metadata stsc - offset chunks\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) // meta\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&num, 1, 4, mp4->mediafp);", "\t\t\t\t\t\t\tnum = BYTESWAP32(num);\n\t\t\t\t\t\t\tif (num * 12 <= qtsize - 8 - len)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmp4->metastsc_count = num;\n\t\t\t\t\t\t\t\tif (mp4->metastsc) free(mp4->metastsc);", "\t\t\t\t\t\t\t\tmp4->metastsc = (SampleToChunk *)malloc(num * 12);\n\t\t\t\t\t\t\t\tif (mp4->metastsc)", "\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\tuint32_t total_stsc = num;\n\t\t\t\t\t\t\t\t\tlen += fread(mp4->metastsc, 1, num * sizeof(SampleToChunk), mp4->mediafp);", "\t\t\t\t\t\t\t\t\tdo", "\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\tmp4->metastsc[num].chunk_num = BYTESWAP32(mp4->metastsc[num].chunk_num);\n\t\t\t\t\t\t\t\t\t\tmp4->metastsc[num].samples = BYTESWAP32(mp4->metastsc[num].samples);\n\t\t\t\t\t\t\t\t\t\tmp4->metastsc[num].id = BYTESWAP32(mp4->metastsc[num].id);\n\t\t\t\t\t\t\t\t\t} while (num > 0);", "\t\t\t\t\t\t\t\t}", "\n\t\t\t\t\t\t\t\tif (mp4->metastsc_count == 1 && mp4->metastsc[0].samples == 1) // Simplify if the stsc is not reporting any grouped chunks.", "\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\tif (mp4->metastsc) free(mp4->metastsc);\n\t\t\t\t\t\t\t\t\tmp4->metastsc = NULL;\n\t\t\t\t\t\t\t\t\tmp4->metastsc_count = 0;", "\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stsx", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('s', 't', 's', 'z')) // metadata stsz - sizes\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) // meta\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t equalsamplesize;", "\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&equalsamplesize, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&num, 1, 4, mp4->mediafp);", "\t\t\t\t\t\t\tnum = BYTESWAP32(num);\n\t\t\t\t\t\t\tif (num * 4 <= qtsize - 8 - len)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmp4->metasize_count = num;\n\t\t\t\t\t\t\t\tif (mp4->metasizes) free(mp4->metasizes);", "\t\t\t\t\t\t\t\tmp4->metasizes = (uint32_t *)malloc(num * 4);\n\t\t\t\t\t\t\t\tif (mp4->metasizes)", "\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\tif (equalsamplesize == 0)", "\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\tlen += fread(mp4->metasizes, 1, num * 4, mp4->mediafp);\n\t\t\t\t\t\t\t\t\t\tdo", "\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\tmp4->metasizes[num] = BYTESWAP32(mp4->metasizes[num]);\n\t\t\t\t\t\t\t\t\t\t} while (num > 0);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tequalsamplesize = BYTESWAP32(equalsamplesize);\n\t\t\t\t\t\t\t\t\t\tdo", "\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\tmp4->metasizes[num] = equalsamplesize;\n\t\t\t\t\t\t\t\t\t\t} while (num > 0);", "\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}", "", "\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stsz", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('s', 't', 'c', 'o')) // metadata stco - offsets\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) // meta\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&num, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tnum = BYTESWAP32(num);\n\t\t\t\t\t\t\tif (num * 4 <= qtsize - 8 - len)\n\t\t\t\t\t\t\t{", "", "\t\t\t\t\t\t\t\tif (mp4->metastsc_count > 0 && num != mp4->metasize_count)\n\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\tmp4->indexcount = mp4->metasize_count;", "\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets) free(mp4->metaoffsets);", "\t\t\t\t\t\t\t\t\tmp4->metaoffsets = (uint64_t *)malloc(mp4->metasize_count * 8);\n\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets)", "\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\tuint32_t *metaoffsets32 = NULL;\n\t\t\t\t\t\t\t\t\t\tmetaoffsets32 = (uint32_t *)malloc(num * 4);\n\t\t\t\t\t\t\t\t\t\tif (metaoffsets32)", "\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\tuint64_t fileoffset = 0;\n\t\t\t\t\t\t\t\t\t\t\tint stsc_pos = 0;\n\t\t\t\t\t\t\t\t\t\t\tint stco_pos = 0;\n\t\t\t\t\t\t\t\t\t\t\tint repeat = 1;\n\t\t\t\t\t\t\t\t\t\t\tlen += fread(metaoffsets32, 1, num * 4, mp4->mediafp);\n\t\t\t\t\t\t\t\t\t\t\tdo", "\t\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\t\tmetaoffsets32[num] = BYTESWAP32(metaoffsets32[num]);\n\t\t\t\t\t\t\t\t\t\t\t} while (num > 0);", "\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[0] = fileoffset = metaoffsets32[stco_pos];\n\t\t\t\t\t\t\t\t\t\t\tnum = 1;\n\t\t\t\t\t\t\t\t\t\t\twhile (num < mp4->metasize_count)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tif (stsc_pos + 1 < (int)mp4->metastsc_count && num == stsc_pos)", "\t\t\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\t\t\tstco_pos++; stsc_pos++;\n\t\t\t\t\t\t\t\t\t\t\t\t\tfileoffset = (uint64_t)metaoffsets32[stco_pos];\n\t\t\t\t\t\t\t\t\t\t\t\t\trepeat = 1;", "\t\t\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t\t\t\telse if (repeat == mp4->metastsc[stsc_pos].samples)\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tstco_pos++;\n\t\t\t\t\t\t\t\t\t\t\t\t\tfileoffset = (uint64_t)metaoffsets32[stco_pos];\n\t\t\t\t\t\t\t\t\t\t\t\t\trepeat = 1;\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tfileoffset += (uint64_t)mp4->metasizes[num - 1];\n\t\t\t\t\t\t\t\t\t\t\t\t\trepeat++;\n\t\t\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[num] = fileoffset;\n\t\t\t\t\t\t\t\t\t\t\t\t//int delta = metaoffsets[num] - metaoffsets[num - 1];\n\t\t\t\t\t\t\t\t\t\t\t\t//printf(\"%3d:%08x, delta = %08x\\n\", num, (int)fileoffset, delta);", "\t\t\t\t\t\t\t\t\t\t\t\tnum++;", "\t\t\t\t\t\t\t\t\t\t\t}", "\n\t\t\t\t\t\t\t\t\t\t\tif (mp4->metastsc) free(mp4->metastsc);\n\t\t\t\t\t\t\t\t\t\t\tmp4->metastsc = NULL;\n\t\t\t\t\t\t\t\t\t\t\tmp4->metastsc_count = 0;", "\t\t\t\t\t\t\t\t\t\t\tfree(metaoffsets32);", "\t\t\t\t\t\t\t\t\t\t}", "", "\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\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmp4->indexcount = num;\n\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets) free(mp4->metaoffsets);", "\t\t\t\t\t\t\t\t\tmp4->metaoffsets = (uint64_t *)malloc(num * 8);\n\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets)", "\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\tuint32_t *metaoffsets32 = NULL;\n\t\t\t\t\t\t\t\t\t\tmetaoffsets32 = (uint32_t *)malloc(num * 4);\n\t\t\t\t\t\t\t\t\t\tif (metaoffsets32)", "\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\tsize_t readlen = fread(metaoffsets32, 1, num * 4, mp4->mediafp);\n\t\t\t\t\t\t\t\t\t\t\tlen += readlen;\n\t\t\t\t\t\t\t\t\t\t\tdo", "\t\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[num] = BYTESWAP32(metaoffsets32[num]);\n\t\t\t\t\t\t\t\t\t\t\t} while (num > 0);", "\t\t\t\t\t\t\t\t\t\t\tfree(metaoffsets32);", "\t\t\t\t\t\t\t\t\t\t}", "", "\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}", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stco", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}", "\t\t\t\t\telse if (qttag == MAKEID('c', 'o', '6', '4')) // metadata stco - offsets\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) // meta\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&num, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tnum = BYTESWAP32(num);", "", "\t\t\t\t\t\t\tif (num * 8 <= qtsize - 8 - len)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (mp4->metastsc_count > 0 && num != mp4->metasize_count)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmp4->indexcount = mp4->metasize_count;\n\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets) free(mp4->metaoffsets);", "\t\t\t\t\t\t\t\t\tmp4->metaoffsets = (uint64_t *)malloc(mp4->metasize_count * 8);\n\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets)", "\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\tuint64_t *metaoffsets64 = NULL;\n\t\t\t\t\t\t\t\t\t\tmetaoffsets64 = (uint64_t *)malloc(num * 8);\n\t\t\t\t\t\t\t\t\t\tif (metaoffsets64)", "\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\tuint64_t fileoffset = 0;\n\t\t\t\t\t\t\t\t\t\t\tint stsc_pos = 0;\n\t\t\t\t\t\t\t\t\t\t\tint stco_pos = 0;\n\t\t\t\t\t\t\t\t\t\t\tlen += fread(metaoffsets64, 1, num * 8, mp4->mediafp);\n\t\t\t\t\t\t\t\t\t\t\tdo", "\t\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\t\tmetaoffsets64[num] = BYTESWAP64(metaoffsets64[num]);\n\t\t\t\t\t\t\t\t\t\t\t} while (num > 0);", "\t\t\t\t\t\t\t\t\t\t\tfileoffset = metaoffsets64[0];\n\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[0] = fileoffset;\n\t\t\t\t\t\t\t\t\t\t\t//printf(\"%3d:%08x, delta = %08x\\n\", 0, (int)fileoffset, 0);", "\t\t\t\t\t\t\t\t\t\t\tnum = 1;\n\t\t\t\t\t\t\t\t\t\t\twhile (num < mp4->metasize_count)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tif (num != mp4->metastsc[stsc_pos].chunk_num - 1 && 0 == (num - (mp4->metastsc[stsc_pos].chunk_num - 1)) % mp4->metastsc[stsc_pos].samples)", "\t\t\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\t\t\tstco_pos++;\n\t\t\t\t\t\t\t\t\t\t\t\t\tfileoffset = (uint64_t)metaoffsets64[stco_pos];", "\t\t\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tfileoffset += (uint64_t)mp4->metasizes[num - 1];\n\t\t\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[num] = fileoffset;\n\t\t\t\t\t\t\t\t\t\t\t\t//int delta = metaoffsets[num] - metaoffsets[num - 1];\n\t\t\t\t\t\t\t\t\t\t\t\t//printf(\"%3d:%08x, delta = %08x\\n\", num, (int)fileoffset, delta);", "\t\t\t\t\t\t\t\t\t\t\t\tnum++;", "\t\t\t\t\t\t\t\t\t\t\t}", "\n\t\t\t\t\t\t\t\t\t\t\tif (mp4->metastsc) free(mp4->metastsc);\n\t\t\t\t\t\t\t\t\t\t\tmp4->metastsc = NULL;\n\t\t\t\t\t\t\t\t\t\t\tmp4->metastsc_count = 0;", "\t\t\t\t\t\t\t\t\t\t\tfree(metaoffsets64);", "\t\t\t\t\t\t\t\t\t\t}", "", "\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\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmp4->indexcount = num;\n\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets) free(mp4->metaoffsets);\n\t\t\t\t\t\t\t\t\tmp4->metaoffsets = (uint64_t *)malloc(num * 8);\n\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tlen += fread(mp4->metaoffsets, 1, num * 8, mp4->mediafp);\n\t\t\t\t\t\t\t\t\t\tdo\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[num] = BYTESWAP64(mp4->metaoffsets[num]);\n\t\t\t\t\t\t\t\t\t\t} while (num > 0);\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}", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stco", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('s', 't', 't', 's')) // time to samples\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) // meta \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t totaldur = 0, samples = 0;\n\t\t\t\t\t\t\tint32_t entries = 0;\n\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&num, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tnum = BYTESWAP32(num);\n\t\t\t\t\t\t\tif (num * 8 <= qtsize - 8 - len)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tentries = num;", "\t\t\t\t\t\t\t\tmp4->meta_clockdemon = mp4->trak_clockdemon;\n\t\t\t\t\t\t\t\tmp4->meta_clockcount = mp4->trak_clockcount;", "\t\t\t\t\t\t\t\twhile (entries > 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tint32_t samplecount;\n\t\t\t\t\t\t\t\t\tint32_t duration;\n\t\t\t\t\t\t\t\t\tlen += fread(&samplecount, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\t\t\tsamplecount = BYTESWAP32(samplecount);\n\t\t\t\t\t\t\t\t\tlen += fread(&duration, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\t\t\tduration = BYTESWAP32(duration);", "\t\t\t\t\t\t\t\t\tsamples += samplecount;\n\t\t\t\t\t\t\t\t\tentries--;", "\t\t\t\t\t\t\t\t\ttotaldur += duration;\n\t\t\t\t\t\t\t\t\tmp4->metadatalength += (double)((double)samplecount * (double)duration / (double)mp4->meta_clockdemon);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tmp4->basemetadataduration = mp4->metadatalength * (double)mp4->meta_clockdemon / (double)samples;\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stco", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tNESTSIZE(8);\n\t\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (len > 0);", "", "\t}\n\telse\n\t{\n\t\t//\tprintf(\"Could not open %s for input\\n\", filename);\n\t\t//\texit(1);", "\t\tfree(mp4);\n\t\tmp4 = NULL;\n\t}", "\treturn (size_t)mp4;\n}", "\nfloat GetDuration(size_t handle)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0.0;", "\treturn (float)mp4->metadatalength;\n}", "\nvoid CloseSource(size_t handle)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return;", "\tif (mp4->mediafp) fclose(mp4->mediafp), mp4->mediafp = NULL;\n\tif (mp4->metasizes) free(mp4->metasizes), mp4->metasizes = 0;\n\tif (mp4->metaoffsets) free(mp4->metaoffsets), mp4->metaoffsets = 0;", "\tfree(mp4);\n}", "", "uint32_t GetPayloadTime(size_t handle, uint32_t index, float *in, float *out)", "{\n\tmp4object *mp4 = (mp4object *)handle;", "\tif (mp4 == NULL) return 0;", "\tif (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 1;", "\t*in = (float)((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\t*out = (float)((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\treturn 0;", "}", "", "", "\nsize_t OpenMP4SourceUDTA(char *filename)\n{\n\tmp4object *mp4 = (mp4object *)malloc(sizeof(mp4object));\n\tif (mp4 == NULL) return 0;", "\tmemset(mp4, 0, sizeof(mp4object));", "#ifdef _WINDOWS\n\tfopen_s(&mp4->mediafp, filename, \"rb\");\n#else\n\tmp4->mediafp = fopen(filename, \"rb\");\n#endif", "\tif (mp4->mediafp)\n\t{", "\t\tuint32_t qttag, qtsize32, len;", "\t\tint32_t nest = 0;\n\t\tuint64_t nestsize[MAX_NEST_LEVEL] = { 0 };\n\t\tuint64_t lastsize = 0, qtsize;", "\t\tdo\n\t\t{\n\t\t\tlen = fread(&qtsize32, 1, 4, mp4->mediafp);\n\t\t\tlen += fread(&qttag, 1, 4, mp4->mediafp);\n\t\t\tif (len == 8)\n\t\t\t{\n\t\t\t\tif (!GPMF_VALID_FOURCC(qttag))\n\t\t\t\t{", "\t\t\t\t\tLONGSEEK(mp4->mediafp, lastsize - 8 - 8, SEEK_CUR);", "\n\t\t\t\t\tNESTSIZE(lastsize - 8);\n\t\t\t\t\tcontinue;\n\t\t\t\t}", "\t\t\t\tqtsize32 = BYTESWAP32(qtsize32);", "\t\t\t\tif (qtsize32 == 1) // 64-bit Atom\n\t\t\t\t{\n\t\t\t\t\tfread(&qtsize, 1, 8, mp4->mediafp);\n\t\t\t\t\tqtsize = BYTESWAP64(qtsize) - 8;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tqtsize = qtsize32;", "\t\t\t\tnest++;", "\t\t\t\tif (qtsize < 8) break;\n\t\t\t\tif (nest >= MAX_NEST_LEVEL) break;", "\t\t\t\tnestsize[nest] = qtsize;\n\t\t\t\tlastsize = qtsize;", "\t\t\t\tif (qttag == MAKEID('m', 'd', 'a', 't') ||\n\t\t\t\t\tqttag == MAKEID('f', 't', 'y', 'p'))\n\t\t\t\t{", "\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);", "\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\tcontinue;\n\t\t\t\t}", "\t\t\t\tif (qttag == MAKEID('G', 'P', 'M', 'F'))\n\t\t\t\t{\n\t\t\t\t\tmp4->videolength += 1.0;\n\t\t\t\t\tmp4->metadatalength += 1.0;", "\t\t\t\t\tmp4->indexcount = (int)mp4->metadatalength;", "\t\t\t\t\tmp4->metasizes = (uint32_t *)malloc(mp4->indexcount * 4 + 4); memset(mp4->metasizes, 0, mp4->indexcount * 4 + 4);\n\t\t\t\t\tmp4->metaoffsets = (uint64_t *)malloc(mp4->indexcount * 8 + 8); memset(mp4->metaoffsets, 0, mp4->indexcount * 8 + 8);", "\t\t\t\t\tmp4->metasizes[0] = (int)qtsize - 8;\n\t\t\t\t\tmp4->metaoffsets[0] = ftell(mp4->mediafp);\n\t\t\t\t\tmp4->metasize_count = 1;", "\t\t\t\t\treturn (size_t)mp4; // not an MP4, RAW GPMF which has not inherent timing, assigning a during of 1second.\n\t\t\t\t}\n\t\t\t\tif (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms\n\t\t\t\t\tqttag != MAKEID('u', 'd', 't', 'a'))\n\t\t\t\t{", "\t\t\t\t\tLONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);", "\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tNESTSIZE(8);\n\t\t\t\t}\n\t\t\t}\n\t\t} while (len > 0);\n\t}\n\treturn (size_t)mp4;\n}", "", "double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags)", "{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0.0;", "\tGPMF_stream metadata_stream, *ms = &metadata_stream;\n\tuint32_t teststart = 0;\n\tuint32_t testend = mp4->indexcount;\n\tdouble rate = 0.0;\n", "", "\tif (mp4->indexcount < 1)\n\t\treturn 0.0;\n", "\tif (mp4->indexcount > 3) // samples after first and before last are statistically the best, avoiding camera start up or shutdown anomollies. \n\t{\n\t\tteststart++;\n\t\ttestend--;\n\t}", "\tuint32_t *payload = GetPayload(handle, NULL, teststart); // second payload\n\tuint32_t payloadsize = GetPayloadSize(handle, teststart);\n\tint32_t ret = GPMF_Init(ms, payload, payloadsize);", "\n\tif (ret != GPMF_OK)\n\t\tgoto cleanup;", "\t{", "", "\t\tuint32_t startsamples = 0;\n\t\tuint32_t endsamples = 0;", "\t\tuint32_t missing_samples = 0;", "\t\twhile (ret == GPMF_OK && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))", "\t\t{", "\t\t\tmissing_samples = 1;", "\t\t\tteststart++;\n\t\t\tpayload = GetPayload(handle, payload, teststart); // second last payload\n\t\t\tpayloadsize = GetPayloadSize(handle, teststart);\n\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\t\t}\n", "\t\tif (missing_samples)", "\t\t{", "\t\t\tteststart++; //samples after sensor start are statistically the best\n\t\t\tpayload = GetPayload(handle, payload, teststart);\n\t\t\tpayloadsize = GetPayloadSize(handle, teststart);\n\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\t\t}", "\t\tif (ret == GPMF_OK)\n\t\t{\n\t\t\tuint32_t samples = GPMF_Repeat(ms);", "\t\t\tGPMF_stream find_stream;\n\t\t\tGPMF_CopyState(ms, &find_stream);", "\n\t\t\tif (!(flags & GPMF_SAMPLE_RATE_PRECISE) && GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))", "\t\t\t{", "\t\t\t\tstartsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)) - samples;", "\t\t\t\tpayload = GetPayload(handle, payload, testend); // second last payload", "\t\t\t\tpayloadsize = GetPayloadSize(handle, testend);\n\t\t\t\tret = GPMF_Init(ms, payload, payloadsize);", "\t\t\t\tif (ret != GPMF_OK)\n\t\t\t\t\tgoto cleanup;", "\t\t\t\tif (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))\n\t\t\t\t{\n\t\t\t\t\tGPMF_CopyState(ms, &find_stream);\n\t\t\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))\n\t\t\t\t\t{\n\t\t\t\t\t\tendsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream));", "\t\t\t\t\t\trate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);", "\t\t\t\t\t\tgoto cleanup;\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\trate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);\n\t\t\t}\n\t\t\telse // for increased precision, for older GPMF streams sometimes missing the total sample count \n\t\t\t{\n\t\t\t\tuint32_t payloadpos = 0, payloadcount = 0;\n\t\t\t\tdouble slope, top = 0.0, bot = 0.0, meanX = 0, meanY = 0;\n\t\t\t\tuint32_t *repeatarray = malloc(mp4->indexcount * 4 + 4);\n\t\t\t\tmemset(repeatarray, 0, mp4->indexcount * 4 + 4);", "\t\t\t\tsamples = 0;", "\t\t\t\tfor (payloadpos = teststart; payloadpos < testend; payloadcount++, payloadpos++)\n\t\t\t\t{\n\t\t\t\t\tpayload = GetPayload(handle, payload, payloadpos); // second last payload\n\t\t\t\t\tpayloadsize = GetPayloadSize(handle, payloadpos);\n\t\t\t\t\tret = GPMF_Init(ms, payload, payloadsize);", "\t\t\t\t\tif (ret != GPMF_OK)\n\t\t\t\t\t\tgoto cleanup;", "\t\t\t\t\tif (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))\n\t\t\t\t\t{\n\t\t\t\t\t\tGPMF_stream find_stream2;\n\t\t\t\t\t\tGPMF_CopyState(ms, &find_stream2);", "\t\t\t\t\t\tif (GPMF_OK == GPMF_FindNext(&find_stream2, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats", "\t\t\t\t\t\t{", "\t\t\t\t\t\t\tif (repeatarray)", "\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\tfloat in, out;", "\t\t\t\t\t\t\t\tdo", "\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\tsamples++;\n\t\t\t\t\t\t\t\t} while (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_CURRENT_LEVEL));", "\t\t\t\t\t\t\t\trepeatarray[payloadpos] = samples;\n\t\t\t\t\t\t\t\tmeanY += (double)samples;", "\t\t\t\t\t\t\t\tGetPayloadTime(handle, payloadpos, &in, &out);\n\t\t\t\t\t\t\t\tmeanX += out;", "\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{", "\t\t\t\t\t\t\tuint32_t repeat = GPMF_Repeat(ms);\n\t\t\t\t\t\t\tsamples += repeat;", "\t\t\t\t\t\t\tif (repeatarray)", "\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\tfloat in, out;", "\t\t\t\t\t\t\t\trepeatarray[payloadpos] = samples;\n\t\t\t\t\t\t\t\tmeanY += (double)samples;", "\t\t\t\t\t\t\t\tGetPayloadTime(handle, payloadpos, &in, &out);\n\t\t\t\t\t\t\t\tmeanX += out;", "\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}", "\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\t// Compute the line of best fit for a jitter removed sample rate. \n\t\t\t\t// This does assume an unchanging clock, even though the IMU data can thermally impacted causing small clock changes. \n\t\t\t\t// TODO: Next enhancement would be a low order polynominal fit the compensate for any thermal clock drift.\n\t\t\t\tif (repeatarray)\n\t\t\t\t{\n\t\t\t\t\tmeanY /= (double)payloadcount;\n\t\t\t\t\tmeanX /= (double)payloadcount;", "\t\t\t\t\tfor (payloadpos = teststart; payloadpos < testend; payloadpos++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat in, out;\n\t\t\t\t\t\tGetPayloadTime(handle, payloadpos, &in, &out);", "\t\t\t\t\t\ttop += ((double)out - meanX)*((double)repeatarray[payloadpos] - meanY);\n\t\t\t\t\t\tbot += ((double)out - meanX)*((double)out - meanX);\n\t\t\t\t\t}", "\t\t\t\t\tslope = top / bot;\n", "#if 0", "\t\t\t\t\t// This sample code might be useful for compare data latency between channels.\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble intercept;\n\t\t\t\t\t\tintercept = meanY - slope*meanX;\n\t\t\t\t\t\tprintf(\"%c%c%c%c start offset = %f (%.3fms)\\n\", PRINTF_4CC(fourcc), intercept, 1000.0 * intercept / slope);\n\t\t\t\t\t}", "#endif", "\t\t\t\t\trate = slope;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\trate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);\n\t\t\t\t}", "\t\t\t\tfree(repeatarray);", "\t\t\t\tgoto cleanup;", "\t\t\t}\n\t\t}\n\t}", "cleanup:", "\tif (payload) \n\t{", "\t\tFreePayload(payload);", "\t\tpayload = NULL;\n\t}", "\n\treturn rate;\n}", "", "double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0.0;", "\tuint32_t key, insamples;\n\tuint32_t repeat, outsamples;\n\tGPMF_stream find_stream;", "\tif (gs == NULL || mp4->metaoffsets == 0 || mp4->indexcount == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 0.0;", "\tkey = GPMF_Key(gs);\n\trepeat = GPMF_Repeat(gs);\n\tif (rate == 0.0)\n\t\trate = GetGPMFSampleRate(handle, key, GPMF_SAMPLE_RATE_FAST);", "\tif (rate == 0.0)\n\t{\n\t\t*in = *out = 0.0;\n\t\treturn 0.0;\n\t}", "\tGPMF_CopyState(gs, &find_stream);\n\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))\n\t{\n\t\toutsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream));\n\t\tinsamples = outsamples - repeat;", "\t\t*in = ((double)insamples / (double)rate);\n\t\t*out = ((double)outsamples / (double)rate);\n\t}\n\telse\n\t{\n\t\t// might too costly in some applications read all the samples to determine the clock jitter, here I return the estimate from the MP4 track.\n\t\t*in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\t\t*out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\t}\n\treturn rate;\n}" ]
[ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
PreciseBugs
{"buggy_code_end_loc": [46, 130, 244, 971, 114], "buggy_code_start_loc": [5, 5, 48, 5, 66], "filenames": ["GPMF_parser.c", "GPMF_parser.h", "demo/GPMF_demo.c", "demo/GPMF_mp4reader.c", "demo/GPMF_mp4reader.h"], "fixing_code_end_loc": [46, 134, 251, 1131, 115], "fixing_code_start_loc": [5, 5, 49, 5, 67], "message": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gopro:gpmf-parser:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "BA83C3BC-F72D-453A-B3E4-DB1065FC99A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c."}, {"lang": "es", "value": "GoPro GPMF-parser versi\u00f3n 1.2.2, presenta una lectura fuera de l\u00edmites y una SEGV en la funci\u00f3n GPMF_Next en el archivo GPMF_parser.c."}], "evaluatorComment": null, "id": "CVE-2019-15147", "lastModified": "2019-08-22T17:00:00.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-08-18T19:15:10.543", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/issues/60"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, "type": "CWE-125"}
236
Determine whether the {function_name} code is vulnerable or not.
[ "/*! @file mp4reader.c\n*\n* @brief Way Too Crude MP4|MOV reader\n*", "* @version 1.3.1", "*", "* (C) Copyright 2017-2019 GoPro Inc (http://gopro.com/).", "*", "* Licensed under either:\n* - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0\n* - MIT license, http://opensource.org/licenses/MIT\n* at your option.", "*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*/\n", "/* This is not an elegant MP4 parser, only used to help demonstrate extraction of GPMF */", "\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdint.h>", "#include <sys/types.h>\n#include <sys/stat.h>\n", "#include \"GPMF_mp4reader.h\"", "#define PRINT_MP4_STRUCTURE\t\t0", "#ifdef WIN32", "#define LONGSEEK\t_fseeki64\n#define stat64\t\t_stat64", "#else", "#define LONGSEEK\tfseeko", "#endif", "\nuint32_t GetNumberPayloads(size_t handle)\n{\n\tmp4object *mp4 = (mp4object *)handle;", "\tif (mp4)\n\t{\n\t\treturn mp4->indexcount;\n\t}", "\treturn 0;\n}\n", "", "uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return NULL;", "\tuint32_t *MP4buffer = NULL;\n\tif (index < mp4->indexcount && mp4->mediafp)\n\t{\n\t\tMP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]);", "\t\tif (MP4buffer)\n\t\t{", "\t\t\tif (mp4->filesize > mp4->metaoffsets[index]+mp4->metasizes[index])\n\t\t\t{\n\t\t\t\tLONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET);\n\t\t\t\tfread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp);\n\t\t\t\tmp4->filepos = mp4->metaoffsets[index] + mp4->metasizes[index];\n\t\t\t\treturn MP4buffer;\n\t\t\t}", "\t\t}\n\t}\n\treturn NULL;\n}", "", "void LongSeek(mp4object *mp4, int64_t offset)", "{", "\tif (mp4 && offset)", "\t{", "\t\tif (mp4->filepos + offset < mp4->filesize)\n\t\t{\n\t\t\tLONGSEEK(mp4->mediafp, offset, SEEK_CUR);\n\t\t\tmp4->filepos += offset;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmp4->filepos = mp4->filesize;\n\t\t}", "\t}", "", "}", "", "\nvoid FreePayload(uint32_t *lastpayload)\n{\n\tif (lastpayload)\n\t\tfree(lastpayload);\n}", "\nuint32_t GetPayloadSize(size_t handle, uint32_t index)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0;", "\tif (mp4->metasizes && mp4->metasize_count > index)\n\t\treturn mp4->metasizes[index];", "\treturn 0;\n}\n", "", "#define MAX_NEST_LEVEL\t20", "size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) //RAW or within MP4\n{\n\tmp4object *mp4 = (mp4object *)malloc(sizeof(mp4object));\n\tif (mp4 == NULL) return 0;", "\tmemset(mp4, 0, sizeof(mp4object));", "\n\tstruct stat64 mp4stat;\n\tstat64(filename, &mp4stat);\n\tmp4->filesize = mp4stat.st_size;", "\tif (mp4->filesize < 64) return 0;", "\n#ifdef _WINDOWS\n\tfopen_s(&mp4->mediafp, filename, \"rb\");\n#else\n\tmp4->mediafp = fopen(filename, \"rb\");\n#endif", "\tif (mp4->mediafp)\n\t{\n\t\tuint32_t qttag, qtsize32, skip, type = 0, subtype = 0, num;\n\t\tsize_t len;\n\t\tint32_t nest = 0;\n\t\tuint64_t nestsize[MAX_NEST_LEVEL] = { 0 };\n\t\tuint64_t lastsize = 0, qtsize;\n", "", "\t\tdo\n\t\t{\n\t\t\tlen = fread(&qtsize32, 1, 4, mp4->mediafp);\n\t\t\tlen += fread(&qttag, 1, 4, mp4->mediafp);", "\t\t\tmp4->filepos += len;\n\t\t\tif (len == 8 && mp4->filepos < mp4->filesize)", "\t\t\t{\n\t\t\t\tif (!VALID_FOURCC(qttag))\n\t\t\t\t{", "\t\t\t\t\tCloseSource((size_t)mp4);\n\t\t\t\t\tmp4 = NULL;\n\t\t\t\t\tbreak;", "\t\t\t\t}", "\t\t\t\tqtsize32 = BYTESWAP32(qtsize32);", "\t\t\t\tif (qtsize32 == 1) // 64-bit Atom\n\t\t\t\t{", "\t\t\t\t\tlen = fread(&qtsize, 1, 8, mp4->mediafp);\n\t\t\t\t\tmp4->filepos += len;", "\t\t\t\t\tqtsize = BYTESWAP64(qtsize) - 8;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tqtsize = qtsize32;", "\t\t\t\tnest++;", "\t\t\t\tif (qtsize < 8) break;\n\t\t\t\tif (nest >= MAX_NEST_LEVEL) break;", "\t\t\t\tnestsize[nest] = qtsize;\n\t\t\t\tlastsize = qtsize;", "#if PRINT_MP4_STRUCTURE\t", "\t\t\t\tfor (int i = 1; i < nest; i++) printf(\" \");\n\t\t\t\tprintf(\"%c%c%c%c (%lld)\\n\", (qttag & 0xff), ((qttag >> 8) & 0xff), ((qttag >> 16) & 0xff), ((qttag >> 24) & 0xff), qtsize);", "\t\t\t\tif (qttag == MAKEID('m', 'd', 'a', 't') ||\n\t\t\t\t\tqttag == MAKEID('f', 't', 'y', 'p') ||", "\t\t\t\t\tqttag == MAKEID('u', 'd', 't', 'a') ||\n\t\t\t\t\tqttag == MAKEID('f', 'r', 'e', 'e'))\n\t\t\t\t{\n\t\t\t\t\tLongSeek(mp4, qtsize - 8);", "\n\t\t\t\t\tNESTSIZE(qtsize);", "\t\t\t\t\tcontinue;\n\t\t\t\t}\n#else\n\t\t\t\tif (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms\n\t\t\t\t\tqttag != MAKEID('m', 'v', 'h', 'd') &&\n\t\t\t\t\tqttag != MAKEID('t', 'r', 'a', 'k') &&\n\t\t\t\t\tqttag != MAKEID('m', 'd', 'i', 'a') &&\n\t\t\t\t\tqttag != MAKEID('m', 'd', 'h', 'd') &&\n\t\t\t\t\tqttag != MAKEID('m', 'i', 'n', 'f') &&\n\t\t\t\t\tqttag != MAKEID('g', 'm', 'i', 'n') &&\n\t\t\t\t\tqttag != MAKEID('d', 'i', 'n', 'f') &&\n\t\t\t\t\tqttag != MAKEID('a', 'l', 'i', 's') &&\n\t\t\t\t\tqttag != MAKEID('s', 't', 's', 'd') &&", "", "\t\t\t\t\tqttag != MAKEID('s', 't', 'b', 'l') &&\n\t\t\t\t\tqttag != MAKEID('s', 't', 't', 's') &&\n\t\t\t\t\tqttag != MAKEID('s', 't', 's', 'c') &&\n\t\t\t\t\tqttag != MAKEID('s', 't', 's', 'z') &&\n\t\t\t\t\tqttag != MAKEID('s', 't', 'c', 'o') &&\n\t\t\t\t\tqttag != MAKEID('c', 'o', '6', '4') &&\n\t\t\t\t\tqttag != MAKEID('h', 'd', 'l', 'r'))\n\t\t\t\t{", "\t\t\t\t\tLongSeek(mp4, qtsize - 8);", "\n\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t}\n\t\t\t\telse\n#endif\n\t\t\t\t\tif (qttag == MAKEID('m', 'v', 'h', 'd')) //mvhd movie header\n\t\t\t\t\t{\n\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\tlen += fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\tlen += fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\tlen += fread(&mp4->clockdemon, 1, 4, mp4->mediafp); mp4->clockdemon = BYTESWAP32(mp4->clockdemon);\n\t\t\t\t\t\tlen += fread(&mp4->clockcount, 1, 4, mp4->mediafp); mp4->clockcount = BYTESWAP32(mp4->clockcount);", "\n\t\t\t\t\t\tmp4->filepos += len;\n\t\t\t\t\t\tLongSeek(mp4, qtsize - 8 - len); // skip over mvhd", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('m', 'd', 'h', 'd')) //mdhd media header\n\t\t\t\t\t{\n\t\t\t\t\t\tmedia_header md;\n\t\t\t\t\t\tlen = fread(&md, 1, sizeof(md), mp4->mediafp);\n\t\t\t\t\t\tif (len == sizeof(md))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmd.creation_time = BYTESWAP32(md.creation_time);\n\t\t\t\t\t\t\tmd.modification_time = BYTESWAP32(md.modification_time);\n\t\t\t\t\t\t\tmd.time_scale = BYTESWAP32(md.time_scale);\n\t\t\t\t\t\t\tmd.duration = BYTESWAP32(md.duration);", "\t\t\t\t\t\t\tmp4->trak_clockdemon = md.time_scale;\n\t\t\t\t\t\t\tmp4->trak_clockcount = md.duration;", "\t\t\t\t\t\t\tif (mp4->videolength == 0.0) // Get the video length from the first track\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmp4->videolength = (float)((double)mp4->trak_clockcount / (double)mp4->trak_clockdemon);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}", "\n\t\t\t\t\t\tmp4->filepos += len;\n\t\t\t\t\t\tLongSeek(mp4, qtsize - 8 - len); // skip over mvhd", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('h', 'd', 'l', 'r')) //hldr\n\t\t\t\t\t{\n\t\t\t\t\t\tuint32_t temp;\n\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\tlen += fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\tlen += fread(&temp, 1, 4, mp4->mediafp); // type will be 'meta' for the correct trak.\n", "\t\t\t\t\t\tif (temp != MAKEID('a', 'l', 'i', 's') && temp != MAKEID('u', 'r', 'l', ' '))", "\t\t\t\t\t\t\ttype = temp;\n", "\t\t\t\t\t\tmp4->filepos += len;\n\t\t\t\t\t\tLongSeek(mp4, qtsize - 8 - len); // skip over hldr", "\n\t\t\t\t\t\tNESTSIZE(qtsize);", "\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('s', 't', 's', 'd')) //read the sample decription to determine the type of metadata\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) //like meta\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&subtype, 1, 4, mp4->mediafp); // type will be 'meta' for the correct trak.\n\t\t\t\t\t\t\tif (len == 16)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (subtype != traksubtype) // MP4 metadata \n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype = 0; // MP4\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tmp4->filepos += len;\n\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8 - len); // skip over stsd", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('s', 't', 's', 'c')) // metadata stsc - offset chunks\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) // meta\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&num, 1, 4, mp4->mediafp);", "\t\t\t\t\t\t\tnum = BYTESWAP32(num);\n\t\t\t\t\t\t\tif (num * 12 <= qtsize - 8 - len)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmp4->metastsc_count = num;\n\t\t\t\t\t\t\t\tif (mp4->metastsc) free(mp4->metastsc);", "\t\t\t\t\t\t\t\tif (num > 0)", "\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\tmp4->metastsc = (SampleToChunk *)malloc(num * sizeof(SampleToChunk));\n\t\t\t\t\t\t\t\t\tif (mp4->metastsc)", "\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\tlen += fread(mp4->metastsc, 1, num * sizeof(SampleToChunk), mp4->mediafp);", "\t\t\t\t\t\t\t\t\t\tdo\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\tmp4->metastsc[num].chunk_num = BYTESWAP32(mp4->metastsc[num].chunk_num);\n\t\t\t\t\t\t\t\t\t\t\tmp4->metastsc[num].samples = BYTESWAP32(mp4->metastsc[num].samples);\n\t\t\t\t\t\t\t\t\t\t\tmp4->metastsc[num].id = BYTESWAP32(mp4->metastsc[num].id);\n\t\t\t\t\t\t\t\t\t\t} while (num > 0);\n\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\telse", "\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t//size of null\n\t\t\t\t\t\t\t\t\tCloseSource((size_t)mp4);\n\t\t\t\t\t\t\t\t\tmp4 = NULL;\n\t\t\t\t\t\t\t\t\tbreak;", "\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tmp4->filepos += len;\n\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8 - len); // skip over stsx", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('s', 't', 's', 'z')) // metadata stsz - sizes\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) // meta\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t equalsamplesize;", "\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&equalsamplesize, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&num, 1, 4, mp4->mediafp);", "\t\t\t\t\t\t\tnum = BYTESWAP32(num);\n\t\t\t\t\t\t\tif (num * 4 <= qtsize - 8 - len)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmp4->metasize_count = num;\n\t\t\t\t\t\t\t\tif (mp4->metasizes) free(mp4->metasizes);", "\t\t\t\t\t\t\t\tif(num > 0)", "\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\tmp4->metasizes = (uint32_t *)malloc(num * 4);\n\t\t\t\t\t\t\t\t\tif (mp4->metasizes)", "\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\tif (equalsamplesize == 0)", "\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\tlen += fread(mp4->metasizes, 1, num * 4, mp4->mediafp);\n\t\t\t\t\t\t\t\t\t\t\tdo\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\t\tmp4->metasizes[num] = BYTESWAP32(mp4->metasizes[num]);\n\t\t\t\t\t\t\t\t\t\t\t} while (num > 0);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse", "\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\tequalsamplesize = BYTESWAP32(equalsamplesize);\n\t\t\t\t\t\t\t\t\t\t\tdo\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\t\tmp4->metasizes[num] = equalsamplesize;\n\t\t\t\t\t\t\t\t\t\t\t} while (num > 0);\n\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//size of null\n\t\t\t\t\t\t\t\t\tCloseSource((size_t)mp4);\n\t\t\t\t\t\t\t\t\tmp4 = NULL;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tmp4->filepos += len;\n\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8 - len); // skip over stsz", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('s', 't', 'c', 'o')) // metadata stco - offsets\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) // meta\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&num, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tnum = BYTESWAP32(num);\n\t\t\t\t\t\t\tif (num * 4 <= qtsize - 8 - len)\n\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\tuint32_t metastco_count = num;\n", "\t\t\t\t\t\t\t\tif (mp4->metastsc_count > 0 && num != mp4->metasize_count)\n\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\tmp4->indexcount = num;", "\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets) free(mp4->metaoffsets);", "\t\t\t\t\t\t\t\t\tif(num > 0)", "\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets = (uint64_t *)malloc(num * 8);\n\t\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets)", "\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\tuint32_t *metaoffsets32 = NULL;\n\t\t\t\t\t\t\t\t\t\t\tmetaoffsets32 = (uint32_t *)malloc(num * 4);\n\t\t\t\t\t\t\t\t\t\t\tif (metaoffsets32)", "\t\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\t\tuint64_t fileoffset = 0;\n\t\t\t\t\t\t\t\t\t\t\t\tint stsc_pos = 0;\n\t\t\t\t\t\t\t\t\t\t\t\tint stco_pos = 0;\n\t\t\t\t\t\t\t\t\t\t\t\tint repeat = 1;\n\t\t\t\t\t\t\t\t\t\t\t\tlen += fread(metaoffsets32, 1, num * 4, mp4->mediafp);\n\t\t\t\t\t\t\t\t\t\t\t\tdo", "\t\t\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\t\t\tmetaoffsets32[num] = BYTESWAP32(metaoffsets32[num]);\n\t\t\t\t\t\t\t\t\t\t\t\t} while (num > 0);", "\t\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[0] = fileoffset = metaoffsets32[stco_pos];\n\t\t\t\t\t\t\t\t\t\t\t\tnum = 1;\n\t\t\t\t\t\t\t\t\t\t\t\twhile (num < mp4->indexcount)\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tif ((uint32_t)repeat == mp4->metastsc[stsc_pos].samples)\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif ((uint32_t)stco_pos + 1 < metastco_count)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstco_pos++;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfileoffset = (uint64_t)metaoffsets32[stco_pos];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfileoffset += (uint64_t)mp4->metasizes[num - 1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif ((uint32_t)stsc_pos + 1 < mp4->metastsc_count)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (mp4->metastsc[stsc_pos + 1].chunk_num == (uint32_t)stco_pos + 1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstsc_pos++;", "\t\t\t\t\t\t\t\t\t\t\t\t\t\trepeat = 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfileoffset += (uint64_t)mp4->metasizes[num - 1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\trepeat++;\n\t\t\t\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[num] = fileoffset;\n\t\t\t\t\t\t\t\t\t\t\t\t\t//int delta = metaoffsets[num] - metaoffsets[num - 1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t//printf(\"%3d:%08x, delta = %08x\\n\", num, (int)fileoffset, delta);", "\t\t\t\t\t\t\t\t\t\t\t\t\tnum++;", "\t\t\t\t\t\t\t\t\t\t\t\t}", "\n\t\t\t\t\t\t\t\t\t\t\t\tif (mp4->metastsc) free(mp4->metastsc);\n\t\t\t\t\t\t\t\t\t\t\t\tmp4->metastsc = NULL;\n\t\t\t\t\t\t\t\t\t\t\t\tmp4->metastsc_count = 0;", "\t\t\t\t\t\t\t\t\t\t\t\tfree(metaoffsets32);", "\t\t\t\t\t\t\t\t\t\t\t}", "", "\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//size of null\n\t\t\t\t\t\t\t\t\t\tCloseSource((size_t)mp4);\n\t\t\t\t\t\t\t\t\t\tmp4 = NULL;\n\t\t\t\t\t\t\t\t\t\tbreak;", "\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\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmp4->indexcount = num;\n\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets) free(mp4->metaoffsets);", "\t\t\t\t\t\t\t\t\tif (num > 0)", "\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets = (uint64_t *)malloc(num * 8);\n\t\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets)", "\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\tuint32_t *metaoffsets32 = NULL;\n\t\t\t\t\t\t\t\t\t\t\tmetaoffsets32 = (uint32_t *)malloc(num * 4);\n\t\t\t\t\t\t\t\t\t\t\tif (metaoffsets32)", "\t\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\t\tsize_t readlen = fread(metaoffsets32, 1, num * 4, mp4->mediafp);\n\t\t\t\t\t\t\t\t\t\t\t\tlen += readlen;\n\t\t\t\t\t\t\t\t\t\t\t\tdo\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[num] = BYTESWAP32(metaoffsets32[num]);\n\t\t\t\t\t\t\t\t\t\t\t\t} while (num > 0);", "\t\t\t\t\t\t\t\t\t\t\t\tfree(metaoffsets32);\n\t\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//size of null\n\t\t\t\t\t\t\t\t\t\tCloseSource((size_t)mp4);\n\t\t\t\t\t\t\t\t\t\tmp4 = NULL;\n\t\t\t\t\t\t\t\t\t\tbreak;", "\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}", "\t\t\t\t\t\t\tmp4->filepos += len;\n\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8 - len); // skip over stco", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}", "\t\t\t\t\telse if (qttag == MAKEID('c', 'o', '6', '4')) // metadata stco - offsets\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) // meta\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&num, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tnum = BYTESWAP32(num);", "\n\t\t\t\t\t\t\tif(num == 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//size of null\n\t\t\t\t\t\t\t\tCloseSource((size_t)mp4);\n\t\t\t\t\t\t\t\tmp4 = NULL;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t\tif (num * 8 <= qtsize - 8 - len)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (mp4->metastsc_count > 0 && num != mp4->metasize_count)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmp4->indexcount = mp4->metasize_count;\n\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets) free(mp4->metaoffsets);", "\t\t\t\t\t\t\t\t\tif (mp4->metasize_count)", "\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets = (uint64_t *)malloc(mp4->metasize_count * 8);\n\t\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets)", "\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\tuint64_t *metaoffsets64 = NULL;\n\t\t\t\t\t\t\t\t\t\t\tmetaoffsets64 = (uint64_t *)malloc(num * 8);\n\t\t\t\t\t\t\t\t\t\t\tif (metaoffsets64)", "\t\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\t\tuint64_t fileoffset = 0;\n\t\t\t\t\t\t\t\t\t\t\t\tint stsc_pos = 0;\n\t\t\t\t\t\t\t\t\t\t\t\tint stco_pos = 0;\n\t\t\t\t\t\t\t\t\t\t\t\tlen += fread(metaoffsets64, 1, num * 8, mp4->mediafp);\n\t\t\t\t\t\t\t\t\t\t\t\tdo", "\t\t\t\t\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\t\t\tmetaoffsets64[num] = BYTESWAP64(metaoffsets64[num]);\n\t\t\t\t\t\t\t\t\t\t\t\t} while (num > 0);", "\t\t\t\t\t\t\t\t\t\t\t\tfileoffset = metaoffsets64[0];\n\t\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[0] = fileoffset;\n\t\t\t\t\t\t\t\t\t\t\t\t//printf(\"%3d:%08x, delta = %08x\\n\", 0, (int)fileoffset, 0);", "\t\t\t\t\t\t\t\t\t\t\t\tnum = 1;\n\t\t\t\t\t\t\t\t\t\t\t\twhile (num < mp4->metasize_count)\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (num != mp4->metastsc[stsc_pos].chunk_num - 1 && 0 == (num - (mp4->metastsc[stsc_pos].chunk_num - 1)) % mp4->metastsc[stsc_pos].samples)\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstco_pos++;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfileoffset = (uint64_t)metaoffsets64[stco_pos];\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfileoffset += (uint64_t)mp4->metasizes[num - 1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[num] = fileoffset;\n\t\t\t\t\t\t\t\t\t\t\t\t\t//int delta = metaoffsets[num] - metaoffsets[num - 1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t//printf(\"%3d:%08x, delta = %08x\\n\", num, (int)fileoffset, delta);", "\t\t\t\t\t\t\t\t\t\t\t\t\tnum++;", "\t\t\t\t\t\t\t\t\t\t\t\t}", "\n\t\t\t\t\t\t\t\t\t\t\t\tif (mp4->metastsc) free(mp4->metastsc);\n\t\t\t\t\t\t\t\t\t\t\t\tmp4->metastsc = NULL;\n\t\t\t\t\t\t\t\t\t\t\t\tmp4->metastsc_count = 0;", "\t\t\t\t\t\t\t\t\t\t\t\tfree(metaoffsets64);", "\t\t\t\t\t\t\t\t\t\t\t}", "", "\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//size of null\n\t\t\t\t\t\t\t\t\t\tCloseSource((size_t)mp4);\n\t\t\t\t\t\t\t\t\t\tmp4 = NULL;\n\t\t\t\t\t\t\t\t\t\tbreak;", "\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\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmp4->indexcount = num;\n\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets) free(mp4->metaoffsets);\n\t\t\t\t\t\t\t\t\tmp4->metaoffsets = (uint64_t *)malloc(num * 8);\n\t\t\t\t\t\t\t\t\tif (mp4->metaoffsets)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tlen += fread(mp4->metaoffsets, 1, num * 8, mp4->mediafp);\n\t\t\t\t\t\t\t\t\t\tdo\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tnum--;\n\t\t\t\t\t\t\t\t\t\t\tmp4->metaoffsets[num] = BYTESWAP64(mp4->metaoffsets[num]);\n\t\t\t\t\t\t\t\t\t\t} while (num > 0);\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}", "\t\t\t\t\t\t\tmp4->filepos += len;\n\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8 - len); // skip over stco", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse if (qttag == MAKEID('s', 't', 't', 's')) // time to samples\n\t\t\t\t\t{\n\t\t\t\t\t\tif (type == traktype) // meta \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t totaldur = 0, samples = 0;\n\t\t\t\t\t\t\tint32_t entries = 0;\n\t\t\t\t\t\t\tlen = fread(&skip, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tlen += fread(&num, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\tnum = BYTESWAP32(num);\n\t\t\t\t\t\t\tif (num * 8 <= qtsize - 8 - len)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tentries = num;", "\t\t\t\t\t\t\t\tmp4->meta_clockdemon = mp4->trak_clockdemon;\n\t\t\t\t\t\t\t\tmp4->meta_clockcount = mp4->trak_clockcount;", "\t\t\t\t\t\t\t\twhile (entries > 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tint32_t samplecount;\n\t\t\t\t\t\t\t\t\tint32_t duration;\n\t\t\t\t\t\t\t\t\tlen += fread(&samplecount, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\t\t\tsamplecount = BYTESWAP32(samplecount);\n\t\t\t\t\t\t\t\t\tlen += fread(&duration, 1, 4, mp4->mediafp);\n\t\t\t\t\t\t\t\t\tduration = BYTESWAP32(duration);", "\t\t\t\t\t\t\t\t\tsamples += samplecount;\n\t\t\t\t\t\t\t\t\tentries--;", "\t\t\t\t\t\t\t\t\ttotaldur += duration;\n\t\t\t\t\t\t\t\t\tmp4->metadatalength += (double)((double)samplecount * (double)duration / (double)mp4->meta_clockdemon);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tmp4->basemetadataduration = mp4->metadatalength * (double)mp4->meta_clockdemon / (double)samples;\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tmp4->filepos += len;\n\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8 - len); // skip over stco", "\t\t\t\t\t\t}\n\t\t\t\t\t\telse", "\t\t\t\t\t\t\tLongSeek(mp4, qtsize - 8);", "\n\t\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tNESTSIZE(8);\n\t\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (len > 0);", "\n\t\tif (mp4)\n\t\t{\n\t\t\tif (mp4->metasizes == NULL || mp4->metaoffsets == NULL)\n\t\t\t{\n\t\t\t\tCloseSource((size_t)mp4);\n\t\t\t\tmp4 = NULL;\n\t\t\t}\n\t\t}", "\t}\n\telse\n\t{\n\t\t//\tprintf(\"Could not open %s for input\\n\", filename);\n\t\t//\texit(1);", "\t\tfree(mp4);\n\t\tmp4 = NULL;\n\t}", "\treturn (size_t)mp4;\n}", "\nfloat GetDuration(size_t handle)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0.0;", "\treturn (float)mp4->metadatalength;\n}", "\nvoid CloseSource(size_t handle)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return;", "\tif (mp4->mediafp) fclose(mp4->mediafp), mp4->mediafp = NULL;\n\tif (mp4->metasizes) free(mp4->metasizes), mp4->metasizes = 0;\n\tif (mp4->metaoffsets) free(mp4->metaoffsets), mp4->metaoffsets = 0;", "\tfree(mp4);\n}", "", "uint32_t GetPayloadTime(size_t handle, uint32_t index, double *in, double *out)", "{\n\tmp4object *mp4 = (mp4object *)handle;", "\tif (mp4 == NULL) return GPMF_ERROR_MEMORY;", "\tif (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return GPMF_ERROR_MEMORY;", "\t*in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\t*out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\treturn GPMF_OK;", "}", "", "uint32_t GetPayloadRationalTime(size_t handle, uint32_t index, uint32_t *in_numerator, uint32_t *out_numerator, uint32_t *denominator)\n{\n mp4object *mp4 = (mp4object *)handle;\n if (mp4 == NULL) return GPMF_ERROR_MEMORY;\n \n if (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in_numerator == NULL || out_numerator == NULL) return GPMF_ERROR_MEMORY;", "\t*in_numerator = (uint32_t)(index * mp4->basemetadataduration);\n\t*out_numerator = (uint32_t)((index + 1) * mp4->basemetadataduration);\n\t*denominator = (uint32_t)mp4->meta_clockdemon;\n \n return GPMF_OK;\n}", "\nsize_t OpenMP4SourceUDTA(char *filename)\n{\n\tmp4object *mp4 = (mp4object *)malloc(sizeof(mp4object));\n\tif (mp4 == NULL) return 0;", "\tmemset(mp4, 0, sizeof(mp4object));", "#ifdef _WINDOWS\n\tfopen_s(&mp4->mediafp, filename, \"rb\");\n#else\n\tmp4->mediafp = fopen(filename, \"rb\");\n#endif", "\tif (mp4->mediafp)\n\t{", "\t\tuint32_t qttag, qtsize32;\n\t\tsize_t len;", "\t\tint32_t nest = 0;\n\t\tuint64_t nestsize[MAX_NEST_LEVEL] = { 0 };\n\t\tuint64_t lastsize = 0, qtsize;", "\t\tdo\n\t\t{\n\t\t\tlen = fread(&qtsize32, 1, 4, mp4->mediafp);\n\t\t\tlen += fread(&qttag, 1, 4, mp4->mediafp);\n\t\t\tif (len == 8)\n\t\t\t{\n\t\t\t\tif (!GPMF_VALID_FOURCC(qttag))\n\t\t\t\t{", "\t\t\t\t\tLongSeek(mp4, lastsize - 8 - 8);", "\n\t\t\t\t\tNESTSIZE(lastsize - 8);\n\t\t\t\t\tcontinue;\n\t\t\t\t}", "\t\t\t\tqtsize32 = BYTESWAP32(qtsize32);", "\t\t\t\tif (qtsize32 == 1) // 64-bit Atom\n\t\t\t\t{\n\t\t\t\t\tfread(&qtsize, 1, 8, mp4->mediafp);\n\t\t\t\t\tqtsize = BYTESWAP64(qtsize) - 8;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tqtsize = qtsize32;", "\t\t\t\tnest++;", "\t\t\t\tif (qtsize < 8) break;\n\t\t\t\tif (nest >= MAX_NEST_LEVEL) break;", "\t\t\t\tnestsize[nest] = qtsize;\n\t\t\t\tlastsize = qtsize;", "\t\t\t\tif (qttag == MAKEID('m', 'd', 'a', 't') ||\n\t\t\t\t\tqttag == MAKEID('f', 't', 'y', 'p'))\n\t\t\t\t{", "\t\t\t\t\tLongSeek(mp4, qtsize - 8);", "\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\tcontinue;\n\t\t\t\t}", "\t\t\t\tif (qttag == MAKEID('G', 'P', 'M', 'F'))\n\t\t\t\t{\n\t\t\t\t\tmp4->videolength += 1.0;\n\t\t\t\t\tmp4->metadatalength += 1.0;", "\t\t\t\t\tmp4->indexcount = (int)mp4->metadatalength;", "\t\t\t\t\tmp4->metasizes = (uint32_t *)malloc(mp4->indexcount * 4 + 4); memset(mp4->metasizes, 0, mp4->indexcount * 4 + 4);\n\t\t\t\t\tmp4->metaoffsets = (uint64_t *)malloc(mp4->indexcount * 8 + 8); memset(mp4->metaoffsets, 0, mp4->indexcount * 8 + 8);", "\t\t\t\t\tmp4->metasizes[0] = (int)qtsize - 8;\n\t\t\t\t\tmp4->metaoffsets[0] = ftell(mp4->mediafp);\n\t\t\t\t\tmp4->metasize_count = 1;", "\t\t\t\t\treturn (size_t)mp4; // not an MP4, RAW GPMF which has not inherent timing, assigning a during of 1second.\n\t\t\t\t}\n\t\t\t\tif (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms\n\t\t\t\t\tqttag != MAKEID('u', 'd', 't', 'a'))\n\t\t\t\t{", "\t\t\t\t\tLongSeek(mp4, qtsize - 8);", "\t\t\t\t\tNESTSIZE(qtsize);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tNESTSIZE(8);\n\t\t\t\t}\n\t\t\t}\n\t\t} while (len > 0);\n\t}\n\treturn (size_t)mp4;\n}", "", "double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags, double *firstsampletime, double *lastsampletime)", "{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0.0;", "\tGPMF_stream metadata_stream, *ms = &metadata_stream;\n\tuint32_t teststart = 0;\n\tuint32_t testend = mp4->indexcount;\n\tdouble rate = 0.0;\n", "\tuint32_t *payload;\n\tuint32_t payloadsize;\n\tint32_t ret;\n", "\tif (mp4->indexcount < 1)\n\t\treturn 0.0;\n", "\tpayload = GetPayload(handle, NULL, teststart); \n\tpayloadsize = GetPayloadSize(handle, teststart);\n\tret = GPMF_Init(ms, payload, payloadsize);", "\n\tif (ret != GPMF_OK)\n\t\tgoto cleanup;", "\t{", "\t\tuint64_t minimumtimestamp = 0;\n\t\tuint64_t starttimestamp = 0;\n\t\tuint64_t endtimestamp = 0;", "\t\tuint32_t startsamples = 0;\n\t\tuint32_t endsamples = 0;", "\t\tdouble intercept = 0.0;", "", "\t\twhile (teststart < mp4->indexcount && ret == GPMF_OK && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))", "\t\t{", "", "\t\t\tteststart++;\n\t\t\tpayload = GetPayload(handle, payload, teststart); // second last payload\n\t\t\tpayloadsize = GetPayloadSize(handle, teststart);\n\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\t\t}\n", "\t\tif (ret == GPMF_OK && payload)", "\t\t{", "\t\t\tuint32_t samples = GPMF_PayloadSampleCount(ms);", "\t\t\tGPMF_stream find_stream;\n\t\t\tGPMF_CopyState(ms, &find_stream);", "\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))\n\t\t\t\tstartsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)) - samples;", "\t\t\tGPMF_CopyState(ms, &find_stream);\n\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_STAMP, GPMF_CURRENT_LEVEL))\n\t\t\t\tstarttimestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&find_stream));", "\t\t\tif (starttimestamp) // is this earliest in the payload, examine the other streams in this early payload.", "\t\t\t{", "\t\t\t\tGPMF_stream any_stream;\n\t\t\t\tGPMF_Init(&any_stream, payload, payloadsize);", "\t\t\t\tminimumtimestamp = starttimestamp;\n\t\t\t\twhile (GPMF_OK == GPMF_FindNext(&any_stream, GPMF_KEY_TIME_STAMP, GPMF_RECURSE_LEVELS))\n\t\t\t\t{\n\t\t\t\t\tuint64_t timestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&any_stream));\n\t\t\t\t\tif (timestamp < minimumtimestamp)\n\t\t\t\t\t\tminimumtimestamp = timestamp;\n\t\t\t\t}\n\t\t\t}", "\t\t\ttestend = mp4->indexcount;\n\t\t\tdo\n\t\t\t{\n\t\t\t\ttestend--;// last payload with the fourcc needed\n\t\t\t\tpayload = GetPayload(handle, payload, testend);", "\t\t\t\tpayloadsize = GetPayloadSize(handle, testend);\n\t\t\t\tret = GPMF_Init(ms, payload, payloadsize);", "\t\t\t} while (testend > 0 && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS));", "\t\t\tGPMF_CopyState(ms, &find_stream);\n\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))\n\t\t\t\tendsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream));\n\t\t\telse // If there is no TSMP we have to count the samples.\n\t\t\t{\n\t\t\t\tuint32_t i;\n\t\t\t\tfor (i = teststart; i <= testend; i++)\n\t\t\t\t{\n\t\t\t\t\tpayload = GetPayload(handle,payload, i); // second last payload\n\t\t\t\t\tpayloadsize = GetPayloadSize(handle, i);\n\t\t\t\t\tif (GPMF_OK == GPMF_Init(ms, payload, payloadsize))\n\t\t\t\t\t\tif (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))\n\t\t\t\t\t\t\tendsamples += GPMF_PayloadSampleCount(ms);\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (starttimestamp != 0)\n\t\t\t{\n\t\t\t\tuint32_t last_samples = GPMF_PayloadSampleCount(ms);\n\t\t\t\tuint32_t totaltimestamped_samples = endsamples - last_samples - startsamples;\n\t\t\t\tdouble time_stamp_scale = 1000000000.0; // scan for nanoseconds, microseconds to seconds, all base 10.", "\t\t\t\tGPMF_CopyState(ms, &find_stream);\n\t\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_STAMP, GPMF_CURRENT_LEVEL))\n\t\t\t\t\tendtimestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&find_stream));", "\t\t\t\tif (endtimestamp)\n\t\t\t\t{\n\t\t\t\t\tdouble approxrate = 0.0;\n\t\t\t\t\tif (endsamples > startsamples)\n\t\t\t\t\t\tapproxrate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);", "\t\t\t\t\tif (approxrate == 0.0)\n\t\t\t\t\t\tapproxrate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);", "\n\t\t\t\t\twhile (time_stamp_scale >= 1)\n\t\t\t\t\t{\n\t\t\t\t\t\trate = (double)(totaltimestamped_samples) / ((double)(endtimestamp - starttimestamp) / time_stamp_scale);\n\t\t\t\t\t\tif (rate*0.9 < approxrate && approxrate < rate*1.1)\n\t\t\t\t\t\t\tbreak;", "\t\t\t\t\t\ttime_stamp_scale *= 0.1;\n\t\t\t\t\t}\n\t\t\t\t\tif (time_stamp_scale < 1.0) rate = 0.0;\n\t\t\t\t\tintercept = (((double)minimumtimestamp - (double)starttimestamp) / time_stamp_scale) * rate;\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (rate == 0.0) //Timestamps didn't help weren't available\n\t\t\t{\n\t\t\t\tif (!(flags & GPMF_SAMPLE_RATE_PRECISE))\n\t\t\t\t{\n\t\t\t\t\tif (endsamples > startsamples)", "\t\t\t\t\t\trate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);", "\n\t\t\t\t\tif (rate == 0.0)\n\t\t\t\t\t\trate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);", "\t\t\t\t\tdouble in, out;\n\t\t\t\t\tif (GPMF_OK == GetPayloadTime(handle, teststart, &in, &out))\n\t\t\t\t\t\tintercept = (double)-in * rate;\n\t\t\t\t}\n\t\t\t\telse // for increased precision, for older GPMF streams sometimes missing the total sample count \n\t\t\t\t{\n\t\t\t\t\tuint32_t payloadpos = 0, payloadcount = 0;\n\t\t\t\t\tdouble slope, top = 0.0, bot = 0.0, meanX = 0, meanY = 0;\n\t\t\t\t\tuint32_t *repeatarray = malloc(mp4->indexcount * 4 + 4);\n\t\t\t\t\tmemset(repeatarray, 0, mp4->indexcount * 4 + 4);", "\t\t\t\t\tsamples = 0;", "\t\t\t\t\tfor (payloadpos = teststart; payloadpos <= testend; payloadpos++)\n\t\t\t\t\t{\n\t\t\t\t\t\tpayload = GetPayload(handle, payload, payloadpos); // second last payload\n\t\t\t\t\t\tpayloadsize = GetPayloadSize(handle, payloadpos);\n\t\t\t\t\t\tret = GPMF_Init(ms, payload, payloadsize);", "\t\t\t\t\t\tif (ret != GPMF_OK)\n\t\t\t\t\t\t\tgoto cleanup;", "\t\t\t\t\t\tif (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))", "\t\t\t\t\t\t{", "\t\t\t\t\t\t\tGPMF_stream find_stream2;\n\t\t\t\t\t\t\tGPMF_CopyState(ms, &find_stream2);", "\t\t\t\t\t\t\tpayloadcount++;", "\t\t\t\t\t\t\tif (GPMF_OK == GPMF_FindNext(&find_stream2, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats", "\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\tif (repeatarray)", "\t\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\t\tdouble in, out;", "\t\t\t\t\t\t\t\t\tdo\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tsamples++;\n\t\t\t\t\t\t\t\t\t} while (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_CURRENT_LEVEL));", "\t\t\t\t\t\t\t\t\trepeatarray[payloadpos] = samples;\n\t\t\t\t\t\t\t\t\tmeanY += (double)samples;", "\t\t\t\t\t\t\t\t\tif (GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out))\n\t\t\t\t\t\t\t\t\t\tmeanX += out;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tuint32_t repeat = GPMF_PayloadSampleCount(ms);\n\t\t\t\t\t\t\t\tsamples += repeat;", "\t\t\t\t\t\t\t\tif (repeatarray)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdouble in, out;", "\t\t\t\t\t\t\t\t\trepeatarray[payloadpos] = samples;\n\t\t\t\t\t\t\t\t\tmeanY += (double)samples;", "\t\t\t\t\t\t\t\t\tif (GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out))\n\t\t\t\t\t\t\t\t\t\tmeanX += out;\n\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{", "\t\t\t\t\t\t\trepeatarray[payloadpos] = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}", "\t\t\t\t\t// Compute the line of best fit for a jitter removed sample rate. \n\t\t\t\t\t// This does assume an unchanging clock, even though the IMU data can thermally impacted causing small clock changes. \n\t\t\t\t\t// TODO: Next enhancement would be a low order polynominal fit the compensate for any thermal clock drift.\n\t\t\t\t\tif (repeatarray)\n\t\t\t\t\t{\n\t\t\t\t\t\tmeanY /= (double)payloadcount;\n\t\t\t\t\t\tmeanX /= (double)payloadcount;", "\t\t\t\t\t\tfor (payloadpos = teststart; payloadpos <= testend; payloadpos++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble in, out;\n\t\t\t\t\t\t\tif (repeatarray[payloadpos] && GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out))", "\t\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\ttop += ((double)out - meanX)*((double)repeatarray[payloadpos] - meanY);\n\t\t\t\t\t\t\t\tbot += ((double)out - meanX)*((double)out - meanX);", "\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}", "\n\t\t\t\t\t\tslope = top / bot;\n\t\t\t\t\t\trate = slope;", "\t\t\t\t\t\t// This sample code might be useful for compare data latency between channels.\n\t\t\t\t\t\tintercept = meanY - slope * meanX;", "#if 0", "\t\t\t\t\t\tprintf(\"%c%c%c%c start offset = %f (%.3fms) rate = %f\\n\", PRINTF_4CC(fourcc), intercept, 1000.0 * intercept / slope, rate);\n\t\t\t\t\t\tprintf(\"%c%c%c%c first sample at time %.3fms\\n\", PRINTF_4CC(fourcc), -1000.0 * intercept / slope);", "#endif", "\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\trate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);\n\t\t\t\t\t}", "\t\t\t\t\tfree(repeatarray);\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (firstsampletime && lastsampletime)\n\t\t\t{\n\t\t\t\tuint32_t endpayload = mp4->indexcount;\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\tendpayload--;// last payload with the fourcc needed\n\t\t\t\t\tpayload = GetPayload(handle, payload, endpayload);\n\t\t\t\t\tpayloadsize = GetPayloadSize(handle, endpayload);\n\t\t\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\t\t\t\t} while (endpayload > 0 && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS));", "\t\t\t\tif (endpayload > 0 && ret == GPMF_OK)\n\t\t\t\t{\n\t\t\t\t\tuint32_t totalsamples = endsamples - startsamples;\n\t\t\t\t\tfloat timo = 0.0;", "\t\t\t\t\tGPMF_CopyState(ms, &find_stream);\n\t\t\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_OFFSET, GPMF_CURRENT_LEVEL))\n\t\t\t\t\t\tGPMF_FormattedData(&find_stream, &timo, 4, 0, 1);", "\t\t\t\t\tdouble first, last;\n\t\t\t\t\tfirst = -intercept / rate - timo;\n\t\t\t\t\tlast = first + (double)totalsamples / rate;", "\t\t\t\t\t//printf(\"%c%c%c%c first sample at time %.3fms, last at %.3fms\\n\", PRINTF_4CC(fourcc), 1000.0*first, 1000.0*last);", "\t\t\t\t\tif (firstsampletime) *firstsampletime = first;", "\t\t\t\t\tif (lastsampletime) *lastsampletime = last;\n\t\t\t\t}", "\t\t\t}\n\t\t}\n\t}", "cleanup:", "\tif (payload)", "\t\tFreePayload(payload);", "\tpayload = NULL;", "\n\treturn rate;\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 ]
PreciseBugs
{"buggy_code_end_loc": [46, 130, 244, 971, 114], "buggy_code_start_loc": [5, 5, 48, 5, 66], "filenames": ["GPMF_parser.c", "GPMF_parser.h", "demo/GPMF_demo.c", "demo/GPMF_mp4reader.c", "demo/GPMF_mp4reader.h"], "fixing_code_end_loc": [46, 134, 251, 1131, 115], "fixing_code_start_loc": [5, 5, 49, 5, 67], "message": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gopro:gpmf-parser:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "BA83C3BC-F72D-453A-B3E4-DB1065FC99A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c."}, {"lang": "es", "value": "GoPro GPMF-parser versi\u00f3n 1.2.2, presenta una lectura fuera de l\u00edmites y una SEGV en la funci\u00f3n GPMF_Next en el archivo GPMF_parser.c."}], "evaluatorComment": null, "id": "CVE-2019-15147", "lastModified": "2019-08-22T17:00:00.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-08-18T19:15:10.543", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/issues/60"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, "type": "CWE-125"}
236
Determine whether the {function_name} code is vulnerable or not.
[ "/*! @file mp4reader.h\n*\n* @brief Way Too Crude MP4|MOV reader\n*\n* @version 1.2.0\n*\n* (C) Copyright 2017 GoPro Inc (http://gopro.com/).\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a 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, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*/", "#ifndef _GPMF_MP4READER_H\n#define _GPMF_MP4READER_H", "#include \"../GPMF_parser.h\"", "#ifdef __cplusplus\nextern \"C\" {\n#endif", "typedef struct media_header\n{\n\tuint8_t version_flags[4];\n\tuint32_t creation_time;\n\tuint32_t modification_time;\n\tuint32_t time_scale;\n\tuint32_t duration;\n\tuint16_t language;\n\tuint16_t quality;\n} media_header;", "\ntypedef struct SampleToChunk\n{\n\tuint32_t chunk_num;\n\tuint32_t samples;\n\tuint32_t id;\n} SampleToChunk;", "\ntypedef struct mp4object\n{\n\tuint32_t *metasizes;\n\tuint32_t metasize_count;\n\tuint64_t *metaoffsets;\n\tSampleToChunk *metastsc;\n\tuint32_t metastsc_count;\n\tuint32_t indexcount;\n\tdouble videolength;\n\tdouble metadatalength;\n\tuint32_t clockdemon, clockcount;\n\tuint32_t trak_clockdemon, trak_clockcount;\n\tuint32_t meta_clockdemon, meta_clockcount;\n\tdouble basemetadataduration;\n\tFILE *mediafp;", "", "} mp4object;", "#define MAKEID(a,b,c,d)\t\t\t(((d&0xff)<<24)|((c&0xff)<<16)|((b&0xff)<<8)|(a&0xff))\n#define STR2FOURCC(s)\t\t\t((s[0]<<0)|(s[1]<<8)|(s[2]<<16)|(s[3]<<24))", "#define BYTESWAP64(a)\t\t\t(((a&0xff)<<56)|((a&0xff00)<<40)|((a&0xff0000)<<24)|((a&0xff000000)<<8) | ((a>>56)&0xff)|((a>>40)&0xff00)|((a>>24)&0xff0000)|((a>>8)&0xff000000) )\n#define BYTESWAP32(a)\t\t\t(((a&0xff)<<24)|((a&0xff00)<<8)|((a>>8)&0xff00)|((a>>24)&0xff))\n#define BYTESWAP16(a)\t\t\t((((a)>>8)&0xff)|(((a)<<8)&0xff00))\n#define NOSWAP8(a)\t\t\t\t(a)", "", "\n#define MOV_GPMF_TRAK_TYPE\t\tMAKEID('m', 'e', 't', 'a')\t\t// track is the type for metadata\n#define MOV_GPMF_TRAK_SUBTYPE\tMAKEID('g', 'p', 'm', 'd')\t\t// subtype is GPMF\n#define MOV_VIDE_TRAK_TYPE\t\tMAKEID('v', 'i', 'd', 'e')\t\t// MP4 track for video\n#define MOV_SOUN_TRAK_TYPE\t\tMAKEID('s', 'o', 'u', 'n')\t\t// MP4 track for audio\n#define MOV_AVC1_SUBTYPE\t\tMAKEID('a', 'v', 'c', '1')\t\t// subtype H264\n#define MOV_HVC1_SUBTYPE\t\tMAKEID('h', 'v', 'c', '1')\t\t// subtype H265\n#define MOV_MP4A_SUBTYPE\t\tMAKEID('m', 'p', '4', 'a')\t\t// subtype for audio\n#define MOV_CFHD_SUBTYPE\t\tMAKEID('C', 'F', 'H', 'D')\t\t// subtype is CineForm HD\n#define AVI_VIDS_TRAK_TYPE\t\tMAKEID('v', 'i', 'd', 's')\t\t// track is the type for video\n#define AVI_CFHD_SUBTYPE\t\tMAKEID('c', 'f', 'h', 'd')\t\t// subtype is CineForm HD", "#define NESTSIZE(x) { int i = nest; while (i > 0 && nestsize[i] > 0) { nestsize[i] -= x; if(nestsize[i]>=0 && nestsize[i] <= 8) { nestsize[i]=0; nest--; } i--; } }", "#define VALID_FOURCC(a)\t(((((a>>24)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>24)&0xff)>='A'&&((a>>24)&0xff)<='Z') || (((a>>24)&0xff)>='0'&&((a>>24)&0xff)<='9') || (((a>>24)&0xff)==' ') ) && \\\n\t\t\t\t\t\t( (((a>>16)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>16)&0xff)>='A'&&((a>>16)&0xff)<='Z') || (((a>>16)&0xff)>='0'&&((a>>16)&0xff)<='9') || (((a>>16)&0xff)==' ') ) && \\\n\t\t\t\t\t\t( (((a>>8)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>8)&0xff)>='A'&&((a>>8)&0xff)<='Z') || (((a>>8)&0xff)>='0'&&((a>>8)&0xff)<='9') || (((a>>8)&0xff)==' ') ) && \\\n\t\t\t\t\t\t( (((a>>0)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>0)&0xff)>='A'&&((a>>0)&0xff)<='Z') || (((a>>0)&0xff)>='0'&&((a>>0)&0xff)<='9') || (((a>>0)&0xff)==' ') )) ", "size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t subtype);\nsize_t OpenMP4SourceUDTA(char *filename);\nvoid CloseSource(size_t handle);\nfloat GetDuration(size_t handle);\nuint32_t GetNumberPayloads(size_t handle);\nuint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index);", "void SavePayload(size_t handle, uint32_t *payload, uint32_t index);", "void FreePayload(uint32_t *lastpayload);\nuint32_t GetPayloadSize(size_t handle, uint32_t index);", "uint32_t GetPayloadTime(size_t handle, uint32_t index, float *in, float *out); //MP4 timestamps for the payload", "\n#define GPMF_SAMPLE_RATE_FAST\t\t0\n#define GPMF_SAMPLE_RATE_PRECISE\t1\n", "double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags);\ndouble GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double lastrate, uint32_t index, double *in, double *out); //Jitter corrected sample(s) time, if lastrate is unknown, send 0.0 and it will be computed", "\n#ifdef __cplusplus\n}\n#endif", "#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [46, 130, 244, 971, 114], "buggy_code_start_loc": [5, 5, 48, 5, 66], "filenames": ["GPMF_parser.c", "GPMF_parser.h", "demo/GPMF_demo.c", "demo/GPMF_mp4reader.c", "demo/GPMF_mp4reader.h"], "fixing_code_end_loc": [46, 134, 251, 1131, 115], "fixing_code_start_loc": [5, 5, 49, 5, 67], "message": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gopro:gpmf-parser:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "BA83C3BC-F72D-453A-B3E4-DB1065FC99A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c."}, {"lang": "es", "value": "GoPro GPMF-parser versi\u00f3n 1.2.2, presenta una lectura fuera de l\u00edmites y una SEGV en la funci\u00f3n GPMF_Next en el archivo GPMF_parser.c."}], "evaluatorComment": null, "id": "CVE-2019-15147", "lastModified": "2019-08-22T17:00:00.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-08-18T19:15:10.543", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/issues/60"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, "type": "CWE-125"}
236
Determine whether the {function_name} code is vulnerable or not.
[ "/*! @file mp4reader.h\n*\n* @brief Way Too Crude MP4|MOV reader\n*\n* @version 1.2.0\n*\n* (C) Copyright 2017 GoPro Inc (http://gopro.com/).\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a 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, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*/", "#ifndef _GPMF_MP4READER_H\n#define _GPMF_MP4READER_H", "#include \"../GPMF_parser.h\"", "#ifdef __cplusplus\nextern \"C\" {\n#endif", "typedef struct media_header\n{\n\tuint8_t version_flags[4];\n\tuint32_t creation_time;\n\tuint32_t modification_time;\n\tuint32_t time_scale;\n\tuint32_t duration;\n\tuint16_t language;\n\tuint16_t quality;\n} media_header;", "\ntypedef struct SampleToChunk\n{\n\tuint32_t chunk_num;\n\tuint32_t samples;\n\tuint32_t id;\n} SampleToChunk;", "\ntypedef struct mp4object\n{\n\tuint32_t *metasizes;\n\tuint32_t metasize_count;\n\tuint64_t *metaoffsets;\n\tSampleToChunk *metastsc;\n\tuint32_t metastsc_count;\n\tuint32_t indexcount;\n\tdouble videolength;\n\tdouble metadatalength;\n\tuint32_t clockdemon, clockcount;\n\tuint32_t trak_clockdemon, trak_clockcount;\n\tuint32_t meta_clockdemon, meta_clockcount;\n\tdouble basemetadataduration;\n\tFILE *mediafp;", "\tuint64_t filesize;\n\tuint64_t filepos;", "} mp4object;", "#define MAKEID(a,b,c,d)\t\t\t(((d&0xff)<<24)|((c&0xff)<<16)|((b&0xff)<<8)|(a&0xff))\n#define STR2FOURCC(s)\t\t\t((s[0]<<0)|(s[1]<<8)|(s[2]<<16)|(s[3]<<24))", "#define BYTESWAP64(a)\t\t\t(((a&0xff)<<56)|((a&0xff00)<<40)|((a&0xff0000)<<24)|((a&0xff000000)<<8) | ((a>>56)&0xff)|((a>>40)&0xff00)|((a>>24)&0xff0000)|((a>>8)&0xff000000) )\n#define BYTESWAP32(a)\t\t\t(((a&0xff)<<24)|((a&0xff00)<<8)|((a>>8)&0xff00)|((a>>24)&0xff))\n#define BYTESWAP16(a)\t\t\t((((a)>>8)&0xff)|(((a)<<8)&0xff00))\n#define NOSWAP8(a)\t\t\t\t(a)", "", "\n#define MOV_GPMF_TRAK_TYPE\t\tMAKEID('m', 'e', 't', 'a')\t\t// track is the type for metadata\n#define MOV_GPMF_TRAK_SUBTYPE\tMAKEID('g', 'p', 'm', 'd')\t\t// subtype is GPMF\n#define MOV_VIDE_TRAK_TYPE\t\tMAKEID('v', 'i', 'd', 'e')\t\t// MP4 track for video\n#define MOV_SOUN_TRAK_TYPE\t\tMAKEID('s', 'o', 'u', 'n')\t\t// MP4 track for audio\n#define MOV_AVC1_SUBTYPE\t\tMAKEID('a', 'v', 'c', '1')\t\t// subtype H264\n#define MOV_HVC1_SUBTYPE\t\tMAKEID('h', 'v', 'c', '1')\t\t// subtype H265\n#define MOV_MP4A_SUBTYPE\t\tMAKEID('m', 'p', '4', 'a')\t\t// subtype for audio\n#define MOV_CFHD_SUBTYPE\t\tMAKEID('C', 'F', 'H', 'D')\t\t// subtype is CineForm HD\n#define AVI_VIDS_TRAK_TYPE\t\tMAKEID('v', 'i', 'd', 's')\t\t// track is the type for video\n#define AVI_CFHD_SUBTYPE\t\tMAKEID('c', 'f', 'h', 'd')\t\t// subtype is CineForm HD", "#define NESTSIZE(x) { int i = nest; while (i > 0 && nestsize[i] > 0) { nestsize[i] -= x; if(nestsize[i]>=0 && nestsize[i] <= 8) { nestsize[i]=0; nest--; } i--; } }", "#define VALID_FOURCC(a)\t(((((a>>24)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>24)&0xff)>='A'&&((a>>24)&0xff)<='Z') || (((a>>24)&0xff)>='0'&&((a>>24)&0xff)<='9') || (((a>>24)&0xff)==' ') ) && \\\n\t\t\t\t\t\t( (((a>>16)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>16)&0xff)>='A'&&((a>>16)&0xff)<='Z') || (((a>>16)&0xff)>='0'&&((a>>16)&0xff)<='9') || (((a>>16)&0xff)==' ') ) && \\\n\t\t\t\t\t\t( (((a>>8)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>8)&0xff)>='A'&&((a>>8)&0xff)<='Z') || (((a>>8)&0xff)>='0'&&((a>>8)&0xff)<='9') || (((a>>8)&0xff)==' ') ) && \\\n\t\t\t\t\t\t( (((a>>0)&0xff)>='a'&&((a>>24)&0xff)<='z') || (((a>>0)&0xff)>='A'&&((a>>0)&0xff)<='Z') || (((a>>0)&0xff)>='0'&&((a>>0)&0xff)<='9') || (((a>>0)&0xff)==' ') )) ", "size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t subtype);\nsize_t OpenMP4SourceUDTA(char *filename);\nvoid CloseSource(size_t handle);\nfloat GetDuration(size_t handle);\nuint32_t GetNumberPayloads(size_t handle);\nuint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index);", "", "void FreePayload(uint32_t *lastpayload);\nuint32_t GetPayloadSize(size_t handle, uint32_t index);", "uint32_t GetPayloadTime(size_t handle, uint32_t index, double *in, double *out); //MP4 timestamps for the payload\nuint32_t GetPayloadRationalTime(size_t handle, uint32_t index, uint32_t *in_numerator, uint32_t *out_numerator, uint32_t *denominator);", "\n#define GPMF_SAMPLE_RATE_FAST\t\t0\n#define GPMF_SAMPLE_RATE_PRECISE\t1\n", "double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags, double *in, double *out);", "\n#ifdef __cplusplus\n}\n#endif", "#endif" ]
[ 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": [46, 130, 244, 971, 114], "buggy_code_start_loc": [5, 5, 48, 5, 66], "filenames": ["GPMF_parser.c", "GPMF_parser.h", "demo/GPMF_demo.c", "demo/GPMF_mp4reader.c", "demo/GPMF_mp4reader.h"], "fixing_code_end_loc": [46, 134, 251, 1131, 115], "fixing_code_start_loc": [5, 5, 49, 5, 67], "message": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gopro:gpmf-parser:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "BA83C3BC-F72D-453A-B3E4-DB1065FC99A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoPro GPMF-parser 1.2.2 has an out-of-bounds read and SEGV in GPMF_Next in GPMF_parser.c."}, {"lang": "es", "value": "GoPro GPMF-parser versi\u00f3n 1.2.2, presenta una lectura fuera de l\u00edmites y una SEGV en la funci\u00f3n GPMF_Next en el archivo GPMF_parser.c."}], "evaluatorComment": null, "id": "CVE-2019-15147", "lastModified": "2019-08-22T17:00:00.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-08-18T19:15:10.543", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gopro/gpmf-parser/issues/60"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gopro/gpmf-parser/commit/341f12cd5b97ab419e53853ca00176457c9f1681"}, "type": "CWE-125"}
236
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n//----------------------------------------------------------------------\n// Copyright (c) 2011-2016 Raytheon BBN Technologies\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and/or hardware specification (the \"Work\") to\n// deal in the Work without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Work, and to permit persons to whom the Work\n// is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Work.\n//\n// THE WORK IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS\n// IN THE WORK.\n//----------------------------------------------------------------------\n?>\n<?php\nrequire_once(\"settings.php\");\nrequire_once('portal.php');\nrequire_once(\"user.php\");\nrequire_once(\"file_utils.php\");\nrequire_once(\"sr_client.php\");\nrequire_once(\"sr_constants.php\");\nrequire_once(\"am_client.php\");\nrequire_once(\"am_map.php\");\nrequire_once(\"sa_client.php\");\nrequire_once(\"print-text-helpers.php\");\nrequire_once(\"logging_client.php\");\nrequire_once(\"header.php\");\n$user = geni_loadUser();\nif (!isset($user) || is_null($user) || ! $user->isActive()) {\n relative_redirect('home.php');\n}", "function no_slice_error() {\n header('HTTP/1.1 404 Not Found');\n print 'No slice id specified.';\n exit();\n}", "function no_invocation_id_error() {\n header('HTTP/1.1 404 Not Found');\n print 'No omni invocation id and/or user ID specified.';\n exit();\n}", "// redirect if no attributes passed in\nif (! count($_REQUEST)) {\n no_slice_error();\n}", "// set user ID and invocation\nif(array_key_exists(\"invocation_id\", $_REQUEST) &&\n array_key_exists(\"invocation_user\", $_REQUEST)) {\n $invocation_user = $_REQUEST['invocation_user'];\n $invocation_id = $_REQUEST['invocation_id'];", "", "}\nelse {\n no_invocation_id_error();\n}", "// set slice/AM information\nunset($slice);\nunset($am);\ninclude(\"tool-lookupids.php\");\nif (! isset($slice)) {\n no_slice_error();\n}", "// redirect if slice has expired\nif (isset($slice_expired) && convert_boolean($slice_expired)) {\n if (! isset($slice_name)) {\n $slice_name = \"\";\n }\n $_SESSION['lasterror'] = \"Slice \" . $slice_name . \" is expired.\";\n relative_redirect('dashboard.php#slices');\n}", "// redirect if user isn't allowed to look up slice\nif(!$user->isAllowed(SA_ACTION::LOOKUP_SLICE, CS_CONTEXT_TYPE::SLICE, $slice_id)) {\n relative_redirect('home.php');\n}", "// show header and breadcrumbs\nshow_header('GENI Portal: Add Resources to Slice (Results)');\ninclude(\"tool-breadcrumbs.php\");\ninclude(\"tool-showmessage.php\");", "// check that invocation ID actually points to a directory\n$dir_to_check = get_invocation_dir_name($invocation_user, $invocation_id);\nif(!is_dir($dir_to_check)) {\n echo \"<h1>Add Resources to GENI Slice <i>$slice_name</i> (Results)</h1>\";\n echo \"<p class='error'>Files and process data related to omni request\";\n echo \" <b>$invocation_user-$invocation_id</b> not found.\";\n echo \" Older files are periodically removed from the Portal, so it is possible that the files\";\n echo \" and process-related data have been deleted as part of routine maintenance.\";\n echo \"<br><br>\";\n echo \"Please <a href='contact-us.php'>contact us</a> if you require further assistance.</p>\";", " echo '<form method=\"GET\" action=\"back\">';\n echo '<input type=\"button\" value=\"Back\" onClick=\"history.back(-1)\"/>';\n echo '</form>';\n include(\"footer.php\");\n error_log(\"sliceresource.php: Failed to find directory with invocation ID \" .\n \"$invocation_id and user $invocation_user.\");\n exit;\n}", "// set e-mail footer message\n$bug_report_msg1 = \"Attached is a problem report about reserving resources generated from the GENI Portal (https://portal.geni.net/). This problem report contains process-related information such as log files, resource specifications (RSpecs) and metadata.<br><br>User message:\";\n$bug_report_msg2 = \"Thanks,<br>\" . $user->prettyName();\n$bug_report_subject = \"GENI Portal Reservation Problem Report\";", "/*\n since AM ID is optional for this page, it needs to be explicitly\n set if tool-lookupids.php hasn't already set it - there's no else clause\n in tool-lookupids.php because the assumption is that the page would have\n already shown an error earlier if $REQUEST['am_id'] hadn't been specified\n*/\nif(!isset($am_id)) {\n $am_id = NULL;\n}", "print '<script src=\"jacks-lib.js\"></script>';\ninclude(\"sliceresource.js\");", "echo \"<h1>Add Resources to GENI Slice <i>$slice_name</i> (Results)</h1>\";\necho \"<div style='position:relative;'>\";\necho \"<p style='margin-left:0px;'>Total run time: <b><span id='total_run_time'></span></b> \";\necho \"<br>Status: <span id='total_run_time_status'></span></p>\";\necho \"<div style='position:absolute;top:0px;right:0px;'>\";\necho \"<p style='margin:0px;text-align:right;'>Started at: <b><span id='start_time'></span></b><br><span id='last_updated_or_finished_text'>Last updated:</span> <b><span id='last_updated_or_finished_time'></span></b></p>\";\necho \"</div></div>\";", "$request_rspec_filename = $slice_name . \"_request_rspec.xml\";\n$manifest_rspec_filename = $slice_name . \"_manifest_rspec.xml\";\n?>", " <div id='tablist'>\n\t\t<ul class='tabs'>\n\t\t\t<li><a href='#tab_results'>Results</a></li>\n\t\t\t<li><a href='#tab_progress'>Detailed Progress</a></li>\n\t\t\t<li><a href='#tab_request_rspec'>Request RSpec</a></li>\n\t\t\t<li><a href='#tab_manifest_rspec'>Manifest RSpec</a></li>\n\t\t\t<li><a href='#tab_send_bug_report'>Send Problem Report</a></li>\n\t\t\t<li style=\"border-right: none\"><a href='#tab_advanced'>Advanced</a></li>\n\t\t</ul>\n </div>", "<!-- begin tab content -->\n<div class='tabContent'>", "<!-- resource 'tab' - this is empty so that the results (which always appear on\n each tab) will show at the top -->\n<div id='tab_results'>\n</div>", "<!-- progress tab -->\n<div id='tab_progress'>", "<h2>Detailed Progress</h2>\n<pre id='console_data_container' style=\"height:300px;\">\n<span id='console_data'></span>\n</pre>\n<p><button onClick=\"window.location='<?php echo \"get_omni_invocation_data.php?invocation_user=$invocation_user&invocation_id=$invocation_id&slice_id=$slice_id&request=console&download=true&filename=detailed_progress.log\";?>'\" title='Download Detailed Progress Log' id='download_console'>Download Detailed Progress Log</button></p>\n</div>", "<!-- request RSpec tab -->\n<div id='tab_request_rspec'>", "<h2>Request RSpec</h2>\n<pre id='requestrspec_container' style=\"height:300px;\"><span id='requestrspec_data'></span></pre>\n<p><button onClick=\"window.location='<?php echo \"get_omni_invocation_data.php?invocation_user=$invocation_user&invocation_id=$invocation_id&slice_id=$slice_id&request=requestrspec&download=true&filename=$request_rspec_filename\";?>'\" title='Download Request RSpec' id='download_requestrspec'>Download Request RSpec</button></p>\n</div>", "<!-- manifest RSpec tab -->\n<div id='tab_manifest_rspec'>", "<h2>Manifest RSpec</h2>\n<pre id='manifestrspec_container' style=\"height:300px;\"><span id='manifestrspec_data'><i>Manifest RSpec empty</i></span></pre>\n<p><button onClick=\"window.location='<?php echo \"get_omni_invocation_data.php?invocation_user=$invocation_user&invocation_id=$invocation_id&slice_id=$slice_id&request=manifestrspec&download=true&filename=$manifest_rspec_filename\";?>'\" title='Download Manifest RSpec' id='download_manifestrspec' disabled='disabled'>Download Manifest RSpec</button></p>\n</div>", "\n<!-- send bug report tab -->\n<div id='tab_send_bug_report'>", "<script>\nfunction validateBugReportSubmit()\n{\n f1 = document.getElementById(\"f1\");\n to = document.getElementById(\"to\");\n message = document.getElementById(\"message\");", " if (to.value && message.value) {\n f1.submit();\n return true;\n } else if(to.value && !(message.value)) {\n alert(\"Please add a message.\");\n return false;\n } else if(!(to.value) && message.value) {\n alert(\"Please select a recipient e-mail address.\");\n return false;\n } else {\n alert(\"Please select a recipient e-mail address and add a message.\");\n return false;\n }\n}\n</script>", "<h2>Send a Problem Report</h2>", "<p>Ran into a problem or have a question? Search the\n <a target=\"_blank\" href=\"https://groups.google.com/forum/#!forum/geni-users\">\n GENI Users</a> archives for answers to similar questions.\n</p>", "<ul>\n<li>The problem report will include your name, e-mail address, slice and project information, request RSpec, manifest RSpec(s), progress log, debug log, error log and process metadata.</li>\n<li>The report will not include security-sensitive information such as slice credentials, certificates, private keys and SpeaksFor credentials.</li>\n</ul>", "<p>If you are not comfortable sharing your problem report publicly, email it to\n <a href=\"mailto:<?php echo $portal_help_email;?>\">\n <?php echo $portal_help_email;?></a>.\n</p>", "<form id=\"f1\" action=\"send_bug_report.php\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"return validateBugReportSubmit()\">\n<input type=\"hidden\" name=\"invocation_id\" id=\"invocation_id\" value=\"<?php echo $invocation_id;?>\"/>\n<input type=\"hidden\" name=\"invocation_user\" id=\"invocation_user\" value=\"<?php echo $invocation_user;?>\"/>\n<input type=\"hidden\" name=\"slice_id\" id=\"slice_id\" value=\"<?php echo $slice_id;?>\"/>", "<table>\n<tr>\n<th>From</th>\n<td><b><?php echo $user->prettyName() . \" &lt;\" . $user->email() . \"&gt;\"; ?></b> (Copy me on the problem report e-mail:<input type=\"checkbox\" name=\"copy\" id='copy' value=\"true\"/>)</td>\n</tr>\n<tr>\n<th>Subject</th>\n<td><b><?php echo $bug_report_subject; ?></b></td>\n</tr>\n<tr>\n<th>To<br><small>(Required)</small></th>\n<td><b>Recipient e-mail:</b> <input type='text' name='to' id='to' size='30' value='geni-users@googlegroups.com'></input><br></td>\n</tr>\n<tr>\n<th>Message<br><small>(Required)</small></th>\n<td><tt><?php echo $bug_report_msg1;?></tt><br><textarea name='message' id='message' cols='60' rows='4'></textarea><br><br><tt><?php echo $bug_report_msg2;?></tt></td>\n</tr>\n</table>", "<p><input type=\"submit\" value=\"Submit Problem Report\"/></p>", "\n</form>", "</div>", "<!-- advanced tab -->\n<div id='tab_advanced'>", "<h2>Debug Log</h2>\n<pre id='debug_data_container' style=\"height:300px;\">\n<span id='debug_data'></span>\n</pre>\n<p><button onClick=\"window.location='<?php echo \"get_omni_invocation_data.php?invocation_user=$invocation_user&invocation_id=$invocation_id&slice_id=$slice_id&request=debug&download=true&filename=debug.log\";?>'\" title='Download Debug Log' id='download_debug'>Download Debug Log</button></p>", "<h2>Error Log</h2>\n<pre id='error_data_container'><span id='error_data'><i>Error log empty</i></span></pre>\n<p><button onClick=\"window.location='<?php echo \"get_omni_invocation_data.php?invocation_user=$invocation_user&invocation_id=$invocation_id&slice_id=$slice_id&request=error&download=true&filename=error.log\";?>'\" title='Download Error Log' id='download_error' disabled='disabled'>Download Error Log</button></p>", "<h2>Command</h2>\n<pre id='command_data_container'><span id='command_data'></span></pre>", "</div>", "<!-- end tab content -->\n</div>", "<!-- always show results -->\n<h2>Results</h2>\n<?php\n// set AM name if it exists\nif (isset($am_id) && $am_id) {\n $am_url = $am[SR_ARGUMENT::SERVICE_URL];\n $AM_name = am_name($am_url);\n print \"<p>Resources on AM (<b>$AM_name</b>):</p>\";\n}\nelse {\n print \"<p>Resources requested from RSpec:</p>\";\n}\n?>", "<div id='results_stop_msg'></div>\n<div class='resources' id='prettyxml'><p><i>Pending... (See 'Detailed Progress' tab for more information.)</i></p></div>", "<!-- Jacks container -->\n<link rel=\"stylesheet\" type=\"text/css\" href=\"jacks-app.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"jacks-editor-app.css\" />\n<script src=\"<?php echo $jacks_stable_url;?>\"></script>\n<div id='jacksContainer' class='jacks resources' style='background-color: white;display: none;'></div>", "<div id='results_manifest_link'></div>\n<p>\n<a href=\"dashboard.php#slices\">Back to All slices</a><br>\n<a href=\"slice.php?slice_id=<?php echo $slice_id; ?>\">Back to Slice <i><?php echo $slice_name; ?></i></a>\n</p>", "<?php", "include \"tabs.js\";\ninclude(\"footer.php\");", "?>" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [64], "buggy_code_start_loc": [64], "filenames": ["portal/www/portal/sliceresource.php"], "fixing_code_end_loc": [69], "fixing_code_start_loc": [65], "message": "A vulnerability classified as problematic has been found in GENI Portal. This affects the function no_invocation_id_error of the file portal/www/portal/sliceresource.php. The manipulation of the argument invocation_id/invocation_user leads to cross site scripting. It is possible to initiate the attack remotely. The name of the patch is 39a96fb4b822bd3497442a96135de498d4a81337. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-218475.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:geni:geni-portal:*:*:*:*:*:*:*:*", "matchCriteriaId": "3CBA439B-EA3D-4DD2-A84F-AFE2CF9A4DF7", "versionEndExcluding": "2020-08-27", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in GENI Portal. This affects the function no_invocation_id_error of the file portal/www/portal/sliceresource.php. The manipulation of the argument invocation_id/invocation_user leads to cross site scripting. It is possible to initiate the attack remotely. The name of the patch is 39a96fb4b822bd3497442a96135de498d4a81337. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-218475."}], "evaluatorComment": null, "id": "CVE-2020-36654", "lastModified": "2023-01-25T19:25:21.523", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "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"}]}, "published": "2023-01-18T08:15:10.073", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/GENI-NSF/geni-portal/commit/39a96fb4b822bd3497442a96135de498d4a81337"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/GENI-NSF/geni-portal/pull/1824"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.218475"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.218475"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/GENI-NSF/geni-portal/commit/39a96fb4b822bd3497442a96135de498d4a81337"}, "type": "CWE-79"}
237
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n//----------------------------------------------------------------------\n// Copyright (c) 2011-2016 Raytheon BBN Technologies\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and/or hardware specification (the \"Work\") to\n// deal in the Work without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Work, and to permit persons to whom the Work\n// is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Work.\n//\n// THE WORK IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS\n// IN THE WORK.\n//----------------------------------------------------------------------\n?>\n<?php\nrequire_once(\"settings.php\");\nrequire_once('portal.php');\nrequire_once(\"user.php\");\nrequire_once(\"file_utils.php\");\nrequire_once(\"sr_client.php\");\nrequire_once(\"sr_constants.php\");\nrequire_once(\"am_client.php\");\nrequire_once(\"am_map.php\");\nrequire_once(\"sa_client.php\");\nrequire_once(\"print-text-helpers.php\");\nrequire_once(\"logging_client.php\");\nrequire_once(\"header.php\");\n$user = geni_loadUser();\nif (!isset($user) || is_null($user) || ! $user->isActive()) {\n relative_redirect('home.php');\n}", "function no_slice_error() {\n header('HTTP/1.1 404 Not Found');\n print 'No slice id specified.';\n exit();\n}", "function no_invocation_id_error() {\n header('HTTP/1.1 404 Not Found');\n print 'No omni invocation id and/or user ID specified.';\n exit();\n}", "// redirect if no attributes passed in\nif (! count($_REQUEST)) {\n no_slice_error();\n}", "// set user ID and invocation\nif(array_key_exists(\"invocation_id\", $_REQUEST) &&\n array_key_exists(\"invocation_user\", $_REQUEST)) {\n $invocation_user = $_REQUEST['invocation_user'];\n $invocation_id = $_REQUEST['invocation_id'];", " if(!ctype_alnum($invocation_id) || !ctype_alnum($invocation_user))\n {\n relative_redirect('dashboard.php#slices');\n }", "}\nelse {\n no_invocation_id_error();\n}", "// set slice/AM information\nunset($slice);\nunset($am);\ninclude(\"tool-lookupids.php\");\nif (! isset($slice)) {\n no_slice_error();\n}", "// redirect if slice has expired\nif (isset($slice_expired) && convert_boolean($slice_expired)) {\n if (! isset($slice_name)) {\n $slice_name = \"\";\n }\n $_SESSION['lasterror'] = \"Slice \" . $slice_name . \" is expired.\";\n relative_redirect('dashboard.php#slices');\n}", "// redirect if user isn't allowed to look up slice\nif(!$user->isAllowed(SA_ACTION::LOOKUP_SLICE, CS_CONTEXT_TYPE::SLICE, $slice_id)) {\n relative_redirect('home.php');\n}", "// show header and breadcrumbs\nshow_header('GENI Portal: Add Resources to Slice (Results)');\ninclude(\"tool-breadcrumbs.php\");\ninclude(\"tool-showmessage.php\");", "// check that invocation ID actually points to a directory\n$dir_to_check = get_invocation_dir_name($invocation_user, $invocation_id);\nif(!is_dir($dir_to_check)) {\n echo \"<h1>Add Resources to GENI Slice <i>$slice_name</i> (Results)</h1>\";\n echo \"<p class='error'>Files and process data related to omni request\";\n echo \" <b>$invocation_user-$invocation_id</b> not found.\";\n echo \" Older files are periodically removed from the Portal, so it is possible that the files\";\n echo \" and process-related data have been deleted as part of routine maintenance.\";\n echo \"<br><br>\";\n echo \"Please <a href='contact-us.php'>contact us</a> if you require further assistance.</p>\";", " echo '<form method=\"GET\" action=\"back\">';\n echo '<input type=\"button\" value=\"Back\" onClick=\"history.back(-1)\"/>';\n echo '</form>';\n include(\"footer.php\");\n error_log(\"sliceresource.php: Failed to find directory with invocation ID \" .\n \"$invocation_id and user $invocation_user.\");\n exit;\n}", "// set e-mail footer message\n$bug_report_msg1 = \"Attached is a problem report about reserving resources generated from the GENI Portal (https://portal.geni.net/). This problem report contains process-related information such as log files, resource specifications (RSpecs) and metadata.<br><br>User message:\";\n$bug_report_msg2 = \"Thanks,<br>\" . $user->prettyName();\n$bug_report_subject = \"GENI Portal Reservation Problem Report\";", "/*\n since AM ID is optional for this page, it needs to be explicitly\n set if tool-lookupids.php hasn't already set it - there's no else clause\n in tool-lookupids.php because the assumption is that the page would have\n already shown an error earlier if $REQUEST['am_id'] hadn't been specified\n*/\nif(!isset($am_id)) {\n $am_id = NULL;\n}", "print '<script src=\"jacks-lib.js\"></script>';\ninclude(\"sliceresource.js\");", "echo \"<h1>Add Resources to GENI Slice <i>$slice_name</i> (Results)</h1>\";\necho \"<div style='position:relative;'>\";\necho \"<p style='margin-left:0px;'>Total run time: <b><span id='total_run_time'></span></b> \";\necho \"<br>Status: <span id='total_run_time_status'></span></p>\";\necho \"<div style='position:absolute;top:0px;right:0px;'>\";\necho \"<p style='margin:0px;text-align:right;'>Started at: <b><span id='start_time'></span></b><br><span id='last_updated_or_finished_text'>Last updated:</span> <b><span id='last_updated_or_finished_time'></span></b></p>\";\necho \"</div></div>\";", "$request_rspec_filename = $slice_name . \"_request_rspec.xml\";\n$manifest_rspec_filename = $slice_name . \"_manifest_rspec.xml\";\n?>", " <div id='tablist'>\n\t\t<ul class='tabs'>\n\t\t\t<li><a href='#tab_results'>Results</a></li>\n\t\t\t<li><a href='#tab_progress'>Detailed Progress</a></li>\n\t\t\t<li><a href='#tab_request_rspec'>Request RSpec</a></li>\n\t\t\t<li><a href='#tab_manifest_rspec'>Manifest RSpec</a></li>\n\t\t\t<li><a href='#tab_send_bug_report'>Send Problem Report</a></li>\n\t\t\t<li style=\"border-right: none\"><a href='#tab_advanced'>Advanced</a></li>\n\t\t</ul>\n </div>", "<!-- begin tab content -->\n<div class='tabContent'>", "<!-- resource 'tab' - this is empty so that the results (which always appear on\n each tab) will show at the top -->\n<div id='tab_results'>\n</div>", "<!-- progress tab -->\n<div id='tab_progress'>", "<h2>Detailed Progress</h2>\n<pre id='console_data_container' style=\"height:300px;\">\n<span id='console_data'></span>\n</pre>\n<p><button onClick=\"window.location='<?php echo \"get_omni_invocation_data.php?invocation_user=$invocation_user&invocation_id=$invocation_id&slice_id=$slice_id&request=console&download=true&filename=detailed_progress.log\";?>'\" title='Download Detailed Progress Log' id='download_console'>Download Detailed Progress Log</button></p>\n</div>", "<!-- request RSpec tab -->\n<div id='tab_request_rspec'>", "<h2>Request RSpec</h2>\n<pre id='requestrspec_container' style=\"height:300px;\"><span id='requestrspec_data'></span></pre>\n<p><button onClick=\"window.location='<?php echo \"get_omni_invocation_data.php?invocation_user=$invocation_user&invocation_id=$invocation_id&slice_id=$slice_id&request=requestrspec&download=true&filename=$request_rspec_filename\";?>'\" title='Download Request RSpec' id='download_requestrspec'>Download Request RSpec</button></p>\n</div>", "<!-- manifest RSpec tab -->\n<div id='tab_manifest_rspec'>", "<h2>Manifest RSpec</h2>\n<pre id='manifestrspec_container' style=\"height:300px;\"><span id='manifestrspec_data'><i>Manifest RSpec empty</i></span></pre>\n<p><button onClick=\"window.location='<?php echo \"get_omni_invocation_data.php?invocation_user=$invocation_user&invocation_id=$invocation_id&slice_id=$slice_id&request=manifestrspec&download=true&filename=$manifest_rspec_filename\";?>'\" title='Download Manifest RSpec' id='download_manifestrspec' disabled='disabled'>Download Manifest RSpec</button></p>\n</div>", "\n<!-- send bug report tab -->\n<div id='tab_send_bug_report'>", "<script>\nfunction validateBugReportSubmit()\n{\n f1 = document.getElementById(\"f1\");\n to = document.getElementById(\"to\");\n message = document.getElementById(\"message\");", " if (to.value && message.value) {\n f1.submit();\n return true;\n } else if(to.value && !(message.value)) {\n alert(\"Please add a message.\");\n return false;\n } else if(!(to.value) && message.value) {\n alert(\"Please select a recipient e-mail address.\");\n return false;\n } else {\n alert(\"Please select a recipient e-mail address and add a message.\");\n return false;\n }\n}\n</script>", "<h2>Send a Problem Report</h2>", "<p>Ran into a problem or have a question? Search the\n <a target=\"_blank\" href=\"https://groups.google.com/forum/#!forum/geni-users\">\n GENI Users</a> archives for answers to similar questions.\n</p>", "<ul>\n<li>The problem report will include your name, e-mail address, slice and project information, request RSpec, manifest RSpec(s), progress log, debug log, error log and process metadata.</li>\n<li>The report will not include security-sensitive information such as slice credentials, certificates, private keys and SpeaksFor credentials.</li>\n</ul>", "<p>If you are not comfortable sharing your problem report publicly, email it to\n <a href=\"mailto:<?php echo $portal_help_email;?>\">\n <?php echo $portal_help_email;?></a>.\n</p>", "<form id=\"f1\" action=\"send_bug_report.php\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"return validateBugReportSubmit()\">\n<input type=\"hidden\" name=\"invocation_id\" id=\"invocation_id\" value=\"<?php echo $invocation_id;?>\"/>\n<input type=\"hidden\" name=\"invocation_user\" id=\"invocation_user\" value=\"<?php echo $invocation_user;?>\"/>\n<input type=\"hidden\" name=\"slice_id\" id=\"slice_id\" value=\"<?php echo $slice_id;?>\"/>", "<table>\n<tr>\n<th>From</th>\n<td><b><?php echo $user->prettyName() . \" &lt;\" . $user->email() . \"&gt;\"; ?></b> (Copy me on the problem report e-mail:<input type=\"checkbox\" name=\"copy\" id='copy' value=\"true\"/>)</td>\n</tr>\n<tr>\n<th>Subject</th>\n<td><b><?php echo $bug_report_subject; ?></b></td>\n</tr>\n<tr>\n<th>To<br><small>(Required)</small></th>\n<td><b>Recipient e-mail:</b> <input type='text' name='to' id='to' size='30' value='geni-users@googlegroups.com'></input><br></td>\n</tr>\n<tr>\n<th>Message<br><small>(Required)</small></th>\n<td><tt><?php echo $bug_report_msg1;?></tt><br><textarea name='message' id='message' cols='60' rows='4'></textarea><br><br><tt><?php echo $bug_report_msg2;?></tt></td>\n</tr>\n</table>", "<p><input type=\"submit\" value=\"Submit Problem Report\"/></p>", "\n</form>", "</div>", "<!-- advanced tab -->\n<div id='tab_advanced'>", "<h2>Debug Log</h2>\n<pre id='debug_data_container' style=\"height:300px;\">\n<span id='debug_data'></span>\n</pre>\n<p><button onClick=\"window.location='<?php echo \"get_omni_invocation_data.php?invocation_user=$invocation_user&invocation_id=$invocation_id&slice_id=$slice_id&request=debug&download=true&filename=debug.log\";?>'\" title='Download Debug Log' id='download_debug'>Download Debug Log</button></p>", "<h2>Error Log</h2>\n<pre id='error_data_container'><span id='error_data'><i>Error log empty</i></span></pre>\n<p><button onClick=\"window.location='<?php echo \"get_omni_invocation_data.php?invocation_user=$invocation_user&invocation_id=$invocation_id&slice_id=$slice_id&request=error&download=true&filename=error.log\";?>'\" title='Download Error Log' id='download_error' disabled='disabled'>Download Error Log</button></p>", "<h2>Command</h2>\n<pre id='command_data_container'><span id='command_data'></span></pre>", "</div>", "<!-- end tab content -->\n</div>", "<!-- always show results -->\n<h2>Results</h2>\n<?php\n// set AM name if it exists\nif (isset($am_id) && $am_id) {\n $am_url = $am[SR_ARGUMENT::SERVICE_URL];\n $AM_name = am_name($am_url);\n print \"<p>Resources on AM (<b>$AM_name</b>):</p>\";\n}\nelse {\n print \"<p>Resources requested from RSpec:</p>\";\n}\n?>", "<div id='results_stop_msg'></div>\n<div class='resources' id='prettyxml'><p><i>Pending... (See 'Detailed Progress' tab for more information.)</i></p></div>", "<!-- Jacks container -->\n<link rel=\"stylesheet\" type=\"text/css\" href=\"jacks-app.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"jacks-editor-app.css\" />\n<script src=\"<?php echo $jacks_stable_url;?>\"></script>\n<div id='jacksContainer' class='jacks resources' style='background-color: white;display: none;'></div>", "<div id='results_manifest_link'></div>\n<p>\n<a href=\"dashboard.php#slices\">Back to All slices</a><br>\n<a href=\"slice.php?slice_id=<?php echo $slice_id; ?>\">Back to Slice <i><?php echo $slice_name; ?></i></a>\n</p>", "<?php", "include \"tabs.js\";\ninclude(\"footer.php\");", "?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [64], "buggy_code_start_loc": [64], "filenames": ["portal/www/portal/sliceresource.php"], "fixing_code_end_loc": [69], "fixing_code_start_loc": [65], "message": "A vulnerability classified as problematic has been found in GENI Portal. This affects the function no_invocation_id_error of the file portal/www/portal/sliceresource.php. The manipulation of the argument invocation_id/invocation_user leads to cross site scripting. It is possible to initiate the attack remotely. The name of the patch is 39a96fb4b822bd3497442a96135de498d4a81337. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-218475.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:geni:geni-portal:*:*:*:*:*:*:*:*", "matchCriteriaId": "3CBA439B-EA3D-4DD2-A84F-AFE2CF9A4DF7", "versionEndExcluding": "2020-08-27", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in GENI Portal. This affects the function no_invocation_id_error of the file portal/www/portal/sliceresource.php. The manipulation of the argument invocation_id/invocation_user leads to cross site scripting. It is possible to initiate the attack remotely. The name of the patch is 39a96fb4b822bd3497442a96135de498d4a81337. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-218475."}], "evaluatorComment": null, "id": "CVE-2020-36654", "lastModified": "2023-01-25T19:25:21.523", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "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"}]}, "published": "2023-01-18T08:15:10.073", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/GENI-NSF/geni-portal/commit/39a96fb4b822bd3497442a96135de498d4a81337"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/GENI-NSF/geni-portal/pull/1824"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.218475"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.218475"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/GENI-NSF/geni-portal/commit/39a96fb4b822bd3497442a96135de498d4a81337"}, "type": "CWE-79"}
237
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * Copyright (c) 2015 by Contributors\n */\n#ifndef PS_ZMQ_VAN_H_\n#define PS_ZMQ_VAN_H_\n#include <zmq.h>\n#include <stdlib.h>\n#include <thread>\n#include <string>\n#include \"ps/internal/van.h\"\n#if _MSC_VER\n#define rand_r(x) rand()\n#endif", "namespace ps {\n/**\n * \\brief be smart on freeing recved data\n */\ninline void FreeData(void *data, void *hint) {\n if (hint == NULL) {\n delete [] static_cast<char*>(data);\n } else {\n delete static_cast<SArray<char>*>(hint);\n }\n}", "/**\n * \\brief ZMQ based implementation\n */\nclass ZMQVan : public Van {\n public:\n ZMQVan() { }\n virtual ~ZMQVan() { }", " protected:\n void Start() override {\n // start zmq\n context_ = zmq_ctx_new();\n CHECK(context_ != NULL) << \"create 0mq context failed\";\n zmq_ctx_set(context_, ZMQ_MAX_SOCKETS, 65536);\n // zmq_ctx_set(context_, ZMQ_IO_THREADS, 4);\n Van::Start();\n }", " void Stop() override {\n PS_VLOG(1) << my_node_.ShortDebugString() << \" is stopping\";\n Van::Stop();\n // close sockets\n int linger = 0;\n int rc = zmq_setsockopt(receiver_, ZMQ_LINGER, &linger, sizeof(linger));\n CHECK(rc == 0 || errno == ETERM);\n CHECK_EQ(zmq_close(receiver_), 0);\n for (auto& it : senders_) {\n int rc = zmq_setsockopt(it.second, ZMQ_LINGER, &linger, sizeof(linger));\n CHECK(rc == 0 || errno == ETERM);\n CHECK_EQ(zmq_close(it.second), 0);\n }\n zmq_ctx_destroy(context_);\n }", " int Bind(const Node& node, int max_retry) override {\n receiver_ = zmq_socket(context_, ZMQ_ROUTER);\n CHECK(receiver_ != NULL)\n << \"create receiver socket failed: \" << zmq_strerror(errno);\n int local = GetEnv(\"DMLC_LOCAL\", 0);", " std::string addr = local ? \"ipc:///tmp/\" : \"tcp://*:\";", " int port = node.port;\n unsigned seed = static_cast<unsigned>(time(NULL)+port);\n for (int i = 0; i < max_retry+1; ++i) {\n auto address = addr + std::to_string(port);\n if (zmq_bind(receiver_, address.c_str()) == 0) break;\n if (i == max_retry) {\n port = -1;\n } else {\n port = 10000 + rand_r(&seed) % 40000;\n }\n }\n return port;\n }", " void Connect(const Node& node) override {\n CHECK_NE(node.id, node.kEmpty);\n CHECK_NE(node.port, node.kEmpty);\n CHECK(node.hostname.size());\n int id = node.id;\n auto it = senders_.find(id);\n if (it != senders_.end()) {\n zmq_close(it->second);\n }\n // worker doesn't need to connect to the other workers. same for server\n if ((node.role == my_node_.role) &&\n (node.id != my_node_.id)) {\n return;\n }\n void *sender = zmq_socket(context_, ZMQ_DEALER);\n CHECK(sender != NULL)\n << zmq_strerror(errno)\n << \". it often can be solved by \\\"sudo ulimit -n 65536\\\"\"\n << \" or edit /etc/security/limits.conf\";\n if (my_node_.id != Node::kEmpty) {\n std::string my_id = \"ps\" + std::to_string(my_node_.id);\n zmq_setsockopt(sender, ZMQ_IDENTITY, my_id.data(), my_id.size());\n }\n // connect\n std::string addr = \"tcp://\" + node.hostname + \":\" + std::to_string(node.port);\n if (GetEnv(\"DMLC_LOCAL\", 0)) {\n addr = \"ipc:///tmp/\" + std::to_string(node.port);\n }\n if (zmq_connect(sender, addr.c_str()) != 0) {\n LOG(FATAL) << \"connect to \" + addr + \" failed: \" + zmq_strerror(errno);\n }\n senders_[id] = sender;\n }", " int SendMsg(const Message& msg) override {\n std::lock_guard<std::mutex> lk(mu_);\n // find the socket\n int id = msg.meta.recver;\n CHECK_NE(id, Meta::kEmpty);\n auto it = senders_.find(id);\n if (it == senders_.end()) {\n LOG(WARNING) << \"there is no socket to node \" << id;\n return -1;\n }\n void *socket = it->second;", " // send meta\n int meta_size; char* meta_buf;\n PackMeta(msg.meta, &meta_buf, &meta_size);\n int tag = ZMQ_SNDMORE;\n int n = msg.data.size();\n if (n == 0) tag = 0;\n zmq_msg_t meta_msg;\n zmq_msg_init_data(&meta_msg, meta_buf, meta_size, FreeData, NULL);\n while (true) {\n if (zmq_msg_send(&meta_msg, socket, tag) == meta_size) break;\n if (errno == EINTR) continue;\n LOG(WARNING) << \"failed to send message to node [\" << id\n << \"] errno: \" << errno << \" \" << zmq_strerror(errno);\n return -1;\n }\n zmq_msg_close(&meta_msg);\n int send_bytes = meta_size;", " // send data\n for (int i = 0; i < n; ++i) {\n zmq_msg_t data_msg;\n SArray<char>* data = new SArray<char>(msg.data[i]);\n int data_size = data->size();\n zmq_msg_init_data(&data_msg, data->data(), data->size(), FreeData, data);\n if (i == n - 1) tag = 0;\n while (true) {\n if (zmq_msg_send(&data_msg, socket, tag) == data_size) break;\n if (errno == EINTR) continue;\n LOG(WARNING) << \"failed to send message to node [\" << id\n << \"] errno: \" << errno << \" \" << zmq_strerror(errno)\n << \". \" << i << \"/\" << n;\n return -1;\n }\n zmq_msg_close(&data_msg);\n send_bytes += data_size;\n }\n return send_bytes;\n }", " int RecvMsg(Message* msg) override {\n msg->data.clear();\n size_t recv_bytes = 0;\n for (int i = 0; ; ++i) {\n zmq_msg_t* zmsg = new zmq_msg_t;\n CHECK(zmq_msg_init(zmsg) == 0) << zmq_strerror(errno);\n while (true) {\n if (zmq_msg_recv(zmsg, receiver_, 0) != -1) break;\n if (errno == EINTR) continue;\n LOG(WARNING) << \"failed to receive message. errno: \"\n << errno << \" \" << zmq_strerror(errno);\n return -1;\n }\n char* buf = CHECK_NOTNULL((char *)zmq_msg_data(zmsg));\n size_t size = zmq_msg_size(zmsg);\n recv_bytes += size;", " if (i == 0) {\n // identify\n msg->meta.sender = GetNodeID(buf, size);\n msg->meta.recver = my_node_.id;\n CHECK(zmq_msg_more(zmsg));\n zmq_msg_close(zmsg);\n delete zmsg;\n } else if (i == 1) {\n // task\n UnpackMeta(buf, size, &(msg->meta));\n zmq_msg_close(zmsg);\n bool more = zmq_msg_more(zmsg);\n delete zmsg;\n if (!more) break;\n } else {\n // zero-copy\n SArray<char> data;\n data.reset(buf, size, [zmsg, size](char* buf) {\n zmq_msg_close(zmsg);\n delete zmsg;\n });\n msg->data.push_back(data);\n if (!zmq_msg_more(zmsg)) { break; }\n }\n }\n return recv_bytes;\n }", " private:\n /**\n * return the node id given the received identity\n * \\return -1 if not find\n */\n int GetNodeID(const char* buf, size_t size) {\n if (size > 2 && buf[0] == 'p' && buf[1] == 's') {\n int id = 0;\n size_t i = 2;\n for (; i < size; ++i) {\n if (buf[i] >= '0' && buf[i] <= '9') {\n id = id * 10 + buf[i] - '0';\n } else {\n break;\n }\n }\n if (i == size) return id;\n }\n return Meta::kEmpty;\n }", " void *context_ = nullptr;\n /**\n * \\brief node_id to the socket for sending data to this node\n */\n std::unordered_map<int, void*> senders_;\n std::mutex mu_;\n void *receiver_ = nullptr;\n};\n} // namespace ps", "#endif // PS_ZMQ_VAN_H_", "", "", "// monitors the liveness other nodes if this is\n// a schedule node, or monitors the liveness of the scheduler otherwise\n// aliveness monitor\n// CHECK(!zmq_socket_monitor(\n// senders_[kScheduler], \"inproc://monitor\", ZMQ_EVENT_ALL));\n// monitor_thread_ = std::unique_ptr<std::thread>(\n// new std::thread(&Van::Monitoring, this));\n// monitor_thread_->detach();", "// void Van::Monitoring() {\n// void *s = CHECK_NOTNULL(zmq_socket(context_, ZMQ_PAIR));\n// CHECK(!zmq_connect(s, \"inproc://monitor\"));\n// while (true) {\n// // First frame in message contains event number and value\n// zmq_msg_t msg;\n// zmq_msg_init(&msg);\n// if (zmq_msg_recv(&msg, s, 0) == -1) {\n// if (errno == EINTR) continue;\n// break;\n// }\n// uint8_t *data = static_cast<uint8_t*>(zmq_msg_data(&msg));\n// int event = *reinterpret_cast<uint16_t*>(data);\n// // int value = *(uint32_t *)(data + 2);", "// // Second frame in message contains event address. it's just the router's\n// // address. no help", "// if (event == ZMQ_EVENT_DISCONNECTED) {\n// if (!is_scheduler_) {\n// PS_VLOG(1) << my_node_.ShortDebugString() << \": scheduler is dead. exit.\";\n// exit(-1);\n// }\n// }\n// if (event == ZMQ_EVENT_MONITOR_STOPPED) {\n// break;\n// }\n// }\n// zmq_close(s);\n// }" ]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [67], "buggy_code_start_loc": [66], "filenames": ["src/zmq_van.h"], "fixing_code_end_loc": [68], "fixing_code_start_loc": [66], "message": "The clustered setup of Apache MXNet allows users to specify which IP address and port the scheduler will listen on via the DMLC_PS_ROOT_URI and DMLC_PS_ROOT_PORT env variables. In versions older than 1.0.0, however, the MXNet framework will listen on 0.0.0.0 rather than user specified DMLC_PS_ROOT_URI once a scheduler node is initialized. This exposes the instance running MXNet to any attackers reachable via the interface they didn't expect to be listening on. For example: If a user wants to run a clustered setup locally, they may specify to run on 127.0.0.1. But since MXNet will listen on 0.0.0.0, it makes the port accessible on all network interfaces.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:mxnet:*:*:*:*:*:*:*:*", "matchCriteriaId": "0EC14C93-9AF9-40BC-AA91-17399E9E5B6F", "versionEndExcluding": "1.0.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The clustered setup of Apache MXNet allows users to specify which IP address and port the scheduler will listen on via the DMLC_PS_ROOT_URI and DMLC_PS_ROOT_PORT env variables. In versions older than 1.0.0, however, the MXNet framework will listen on 0.0.0.0 rather than user specified DMLC_PS_ROOT_URI once a scheduler node is initialized. This exposes the instance running MXNet to any attackers reachable via the interface they didn't expect to be listening on. For example: If a user wants to run a clustered setup locally, they may specify to run on 127.0.0.1. But since MXNet will listen on 0.0.0.0, it makes the port accessible on all network interfaces."}, {"lang": "es", "value": "La instalaci\u00f3n en cl\u00fasters de Apache MXNet permite que los usuarios especifiquen en qu\u00e9 direcci\u00f3n y puerto IP va a escuchar el scheduler mediante las variables de entorno DMLC_PS_ROOT_URI y DMLC_PS_ROOT_PORT. En las versiones anteriores a la 1.0.0, sin embargo, el framework MXNet escuchar\u00e1 en 0.0.0.0 en lugar del DMLC_PS_ROOT_URI especificado por el usuario una vez se ha inicializado un nodo scheduler. Esto expone la instancia que est\u00e1 ejecutando MXNet a cualquier atacante y la vuelve alcanzable mediante la interfaz que no esperaban que estuviese escuchando. Por ejemplo: si un usuario quiere ejecutar localmente una instalaci\u00f3n en cl\u00fasters, puede especificar que se ejecute en 127.0.0.1. Pero, debido a que MXNet escuchar\u00e1 en 0.0.0.0, hace que el puerto sea accesible en todas las interfaces de red."}], "evaluatorComment": null, "id": "CVE-2018-1281", "lastModified": "2018-08-03T15:53:09.547", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-08T19:29:00.263", "references": [{"source": "security@apache.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/dmlc/ps-lite/commit/4be817e8b03e7e92517e91f2dfcc50865e91c6ea"}], "sourceIdentifier": "security@apache.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/dmlc/ps-lite/commit/4be817e8b03e7e92517e91f2dfcc50865e91c6ea"}, "type": "CWE-200"}
238
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * Copyright (c) 2015 by Contributors\n */\n#ifndef PS_ZMQ_VAN_H_\n#define PS_ZMQ_VAN_H_\n#include <zmq.h>\n#include <stdlib.h>\n#include <thread>\n#include <string>\n#include \"ps/internal/van.h\"\n#if _MSC_VER\n#define rand_r(x) rand()\n#endif", "namespace ps {\n/**\n * \\brief be smart on freeing recved data\n */\ninline void FreeData(void *data, void *hint) {\n if (hint == NULL) {\n delete [] static_cast<char*>(data);\n } else {\n delete static_cast<SArray<char>*>(hint);\n }\n}", "/**\n * \\brief ZMQ based implementation\n */\nclass ZMQVan : public Van {\n public:\n ZMQVan() { }\n virtual ~ZMQVan() { }", " protected:\n void Start() override {\n // start zmq\n context_ = zmq_ctx_new();\n CHECK(context_ != NULL) << \"create 0mq context failed\";\n zmq_ctx_set(context_, ZMQ_MAX_SOCKETS, 65536);\n // zmq_ctx_set(context_, ZMQ_IO_THREADS, 4);\n Van::Start();\n }", " void Stop() override {\n PS_VLOG(1) << my_node_.ShortDebugString() << \" is stopping\";\n Van::Stop();\n // close sockets\n int linger = 0;\n int rc = zmq_setsockopt(receiver_, ZMQ_LINGER, &linger, sizeof(linger));\n CHECK(rc == 0 || errno == ETERM);\n CHECK_EQ(zmq_close(receiver_), 0);\n for (auto& it : senders_) {\n int rc = zmq_setsockopt(it.second, ZMQ_LINGER, &linger, sizeof(linger));\n CHECK(rc == 0 || errno == ETERM);\n CHECK_EQ(zmq_close(it.second), 0);\n }\n zmq_ctx_destroy(context_);\n }", " int Bind(const Node& node, int max_retry) override {\n receiver_ = zmq_socket(context_, ZMQ_ROUTER);\n CHECK(receiver_ != NULL)\n << \"create receiver socket failed: \" << zmq_strerror(errno);\n int local = GetEnv(\"DMLC_LOCAL\", 0);", " std::string hostname = node.hostname.empty() ? \"*\" : node.hostname;\n std::string addr = local ? \"ipc:///tmp/\" : \"tcp://\" + hostname + \":\";", " int port = node.port;\n unsigned seed = static_cast<unsigned>(time(NULL)+port);\n for (int i = 0; i < max_retry+1; ++i) {\n auto address = addr + std::to_string(port);\n if (zmq_bind(receiver_, address.c_str()) == 0) break;\n if (i == max_retry) {\n port = -1;\n } else {\n port = 10000 + rand_r(&seed) % 40000;\n }\n }\n return port;\n }", " void Connect(const Node& node) override {\n CHECK_NE(node.id, node.kEmpty);\n CHECK_NE(node.port, node.kEmpty);\n CHECK(node.hostname.size());\n int id = node.id;\n auto it = senders_.find(id);\n if (it != senders_.end()) {\n zmq_close(it->second);\n }\n // worker doesn't need to connect to the other workers. same for server\n if ((node.role == my_node_.role) &&\n (node.id != my_node_.id)) {\n return;\n }\n void *sender = zmq_socket(context_, ZMQ_DEALER);\n CHECK(sender != NULL)\n << zmq_strerror(errno)\n << \". it often can be solved by \\\"sudo ulimit -n 65536\\\"\"\n << \" or edit /etc/security/limits.conf\";\n if (my_node_.id != Node::kEmpty) {\n std::string my_id = \"ps\" + std::to_string(my_node_.id);\n zmq_setsockopt(sender, ZMQ_IDENTITY, my_id.data(), my_id.size());\n }\n // connect\n std::string addr = \"tcp://\" + node.hostname + \":\" + std::to_string(node.port);\n if (GetEnv(\"DMLC_LOCAL\", 0)) {\n addr = \"ipc:///tmp/\" + std::to_string(node.port);\n }\n if (zmq_connect(sender, addr.c_str()) != 0) {\n LOG(FATAL) << \"connect to \" + addr + \" failed: \" + zmq_strerror(errno);\n }\n senders_[id] = sender;\n }", " int SendMsg(const Message& msg) override {\n std::lock_guard<std::mutex> lk(mu_);\n // find the socket\n int id = msg.meta.recver;\n CHECK_NE(id, Meta::kEmpty);\n auto it = senders_.find(id);\n if (it == senders_.end()) {\n LOG(WARNING) << \"there is no socket to node \" << id;\n return -1;\n }\n void *socket = it->second;", " // send meta\n int meta_size; char* meta_buf;\n PackMeta(msg.meta, &meta_buf, &meta_size);\n int tag = ZMQ_SNDMORE;\n int n = msg.data.size();\n if (n == 0) tag = 0;\n zmq_msg_t meta_msg;\n zmq_msg_init_data(&meta_msg, meta_buf, meta_size, FreeData, NULL);\n while (true) {\n if (zmq_msg_send(&meta_msg, socket, tag) == meta_size) break;\n if (errno == EINTR) continue;\n LOG(WARNING) << \"failed to send message to node [\" << id\n << \"] errno: \" << errno << \" \" << zmq_strerror(errno);\n return -1;\n }\n zmq_msg_close(&meta_msg);\n int send_bytes = meta_size;", " // send data\n for (int i = 0; i < n; ++i) {\n zmq_msg_t data_msg;\n SArray<char>* data = new SArray<char>(msg.data[i]);\n int data_size = data->size();\n zmq_msg_init_data(&data_msg, data->data(), data->size(), FreeData, data);\n if (i == n - 1) tag = 0;\n while (true) {\n if (zmq_msg_send(&data_msg, socket, tag) == data_size) break;\n if (errno == EINTR) continue;\n LOG(WARNING) << \"failed to send message to node [\" << id\n << \"] errno: \" << errno << \" \" << zmq_strerror(errno)\n << \". \" << i << \"/\" << n;\n return -1;\n }\n zmq_msg_close(&data_msg);\n send_bytes += data_size;\n }\n return send_bytes;\n }", " int RecvMsg(Message* msg) override {\n msg->data.clear();\n size_t recv_bytes = 0;\n for (int i = 0; ; ++i) {\n zmq_msg_t* zmsg = new zmq_msg_t;\n CHECK(zmq_msg_init(zmsg) == 0) << zmq_strerror(errno);\n while (true) {\n if (zmq_msg_recv(zmsg, receiver_, 0) != -1) break;\n if (errno == EINTR) continue;\n LOG(WARNING) << \"failed to receive message. errno: \"\n << errno << \" \" << zmq_strerror(errno);\n return -1;\n }\n char* buf = CHECK_NOTNULL((char *)zmq_msg_data(zmsg));\n size_t size = zmq_msg_size(zmsg);\n recv_bytes += size;", " if (i == 0) {\n // identify\n msg->meta.sender = GetNodeID(buf, size);\n msg->meta.recver = my_node_.id;\n CHECK(zmq_msg_more(zmsg));\n zmq_msg_close(zmsg);\n delete zmsg;\n } else if (i == 1) {\n // task\n UnpackMeta(buf, size, &(msg->meta));\n zmq_msg_close(zmsg);\n bool more = zmq_msg_more(zmsg);\n delete zmsg;\n if (!more) break;\n } else {\n // zero-copy\n SArray<char> data;\n data.reset(buf, size, [zmsg, size](char* buf) {\n zmq_msg_close(zmsg);\n delete zmsg;\n });\n msg->data.push_back(data);\n if (!zmq_msg_more(zmsg)) { break; }\n }\n }\n return recv_bytes;\n }", " private:\n /**\n * return the node id given the received identity\n * \\return -1 if not find\n */\n int GetNodeID(const char* buf, size_t size) {\n if (size > 2 && buf[0] == 'p' && buf[1] == 's') {\n int id = 0;\n size_t i = 2;\n for (; i < size; ++i) {\n if (buf[i] >= '0' && buf[i] <= '9') {\n id = id * 10 + buf[i] - '0';\n } else {\n break;\n }\n }\n if (i == size) return id;\n }\n return Meta::kEmpty;\n }", " void *context_ = nullptr;\n /**\n * \\brief node_id to the socket for sending data to this node\n */\n std::unordered_map<int, void*> senders_;\n std::mutex mu_;\n void *receiver_ = nullptr;\n};\n} // namespace ps", "#endif // PS_ZMQ_VAN_H_", "", "", "// monitors the liveness other nodes if this is\n// a schedule node, or monitors the liveness of the scheduler otherwise\n// aliveness monitor\n// CHECK(!zmq_socket_monitor(\n// senders_[kScheduler], \"inproc://monitor\", ZMQ_EVENT_ALL));\n// monitor_thread_ = std::unique_ptr<std::thread>(\n// new std::thread(&Van::Monitoring, this));\n// monitor_thread_->detach();", "// void Van::Monitoring() {\n// void *s = CHECK_NOTNULL(zmq_socket(context_, ZMQ_PAIR));\n// CHECK(!zmq_connect(s, \"inproc://monitor\"));\n// while (true) {\n// // First frame in message contains event number and value\n// zmq_msg_t msg;\n// zmq_msg_init(&msg);\n// if (zmq_msg_recv(&msg, s, 0) == -1) {\n// if (errno == EINTR) continue;\n// break;\n// }\n// uint8_t *data = static_cast<uint8_t*>(zmq_msg_data(&msg));\n// int event = *reinterpret_cast<uint16_t*>(data);\n// // int value = *(uint32_t *)(data + 2);", "// // Second frame in message contains event address. it's just the router's\n// // address. no help", "// if (event == ZMQ_EVENT_DISCONNECTED) {\n// if (!is_scheduler_) {\n// PS_VLOG(1) << my_node_.ShortDebugString() << \": scheduler is dead. exit.\";\n// exit(-1);\n// }\n// }\n// if (event == ZMQ_EVENT_MONITOR_STOPPED) {\n// break;\n// }\n// }\n// zmq_close(s);\n// }" ]
[ 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": [67], "buggy_code_start_loc": [66], "filenames": ["src/zmq_van.h"], "fixing_code_end_loc": [68], "fixing_code_start_loc": [66], "message": "The clustered setup of Apache MXNet allows users to specify which IP address and port the scheduler will listen on via the DMLC_PS_ROOT_URI and DMLC_PS_ROOT_PORT env variables. In versions older than 1.0.0, however, the MXNet framework will listen on 0.0.0.0 rather than user specified DMLC_PS_ROOT_URI once a scheduler node is initialized. This exposes the instance running MXNet to any attackers reachable via the interface they didn't expect to be listening on. For example: If a user wants to run a clustered setup locally, they may specify to run on 127.0.0.1. But since MXNet will listen on 0.0.0.0, it makes the port accessible on all network interfaces.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:mxnet:*:*:*:*:*:*:*:*", "matchCriteriaId": "0EC14C93-9AF9-40BC-AA91-17399E9E5B6F", "versionEndExcluding": "1.0.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The clustered setup of Apache MXNet allows users to specify which IP address and port the scheduler will listen on via the DMLC_PS_ROOT_URI and DMLC_PS_ROOT_PORT env variables. In versions older than 1.0.0, however, the MXNet framework will listen on 0.0.0.0 rather than user specified DMLC_PS_ROOT_URI once a scheduler node is initialized. This exposes the instance running MXNet to any attackers reachable via the interface they didn't expect to be listening on. For example: If a user wants to run a clustered setup locally, they may specify to run on 127.0.0.1. But since MXNet will listen on 0.0.0.0, it makes the port accessible on all network interfaces."}, {"lang": "es", "value": "La instalaci\u00f3n en cl\u00fasters de Apache MXNet permite que los usuarios especifiquen en qu\u00e9 direcci\u00f3n y puerto IP va a escuchar el scheduler mediante las variables de entorno DMLC_PS_ROOT_URI y DMLC_PS_ROOT_PORT. En las versiones anteriores a la 1.0.0, sin embargo, el framework MXNet escuchar\u00e1 en 0.0.0.0 en lugar del DMLC_PS_ROOT_URI especificado por el usuario una vez se ha inicializado un nodo scheduler. Esto expone la instancia que est\u00e1 ejecutando MXNet a cualquier atacante y la vuelve alcanzable mediante la interfaz que no esperaban que estuviese escuchando. Por ejemplo: si un usuario quiere ejecutar localmente una instalaci\u00f3n en cl\u00fasters, puede especificar que se ejecute en 127.0.0.1. Pero, debido a que MXNet escuchar\u00e1 en 0.0.0.0, hace que el puerto sea accesible en todas las interfaces de red."}], "evaluatorComment": null, "id": "CVE-2018-1281", "lastModified": "2018-08-03T15:53:09.547", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-08T19:29:00.263", "references": [{"source": "security@apache.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/dmlc/ps-lite/commit/4be817e8b03e7e92517e91f2dfcc50865e91c6ea"}], "sourceIdentifier": "security@apache.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/dmlc/ps-lite/commit/4be817e8b03e7e92517e91f2dfcc50865e91c6ea"}, "type": "CWE-200"}
238
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2009-2020, Salvatore Sanfilippo <antirez at gmail dot com>\n * Copyright (c) 2020, Redis Labs, Inc\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * Neither the name of Redis nor the names of its contributors may be used\n * to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */", "#include \"server.h\"\n#include \"util.h\"\n#include \"sha1.h\" /* SHA1 is used for DEBUG DIGEST */\n#include \"crc64.h\"\n#include \"bio.h\"\n#include \"quicklist.h\"", "#include <arpa/inet.h>\n#include <signal.h>\n#include <dlfcn.h>\n#include <fcntl.h>\n#include <sys/mman.h>\n#include <unistd.h>", "#ifdef HAVE_BACKTRACE\n#include <execinfo.h>\n#ifndef __OpenBSD__\n#include <ucontext.h>\n#else\ntypedef ucontext_t sigcontext_t;\n#endif\n#endif /* HAVE_BACKTRACE */", "#ifdef __CYGWIN__\n#ifndef SA_ONSTACK\n#define SA_ONSTACK 0x08000000\n#endif\n#endif", "#if defined(__APPLE__) && defined(__arm64__)\n#include <mach/mach.h>\n#endif", "/* Globals */\nstatic int bug_report_start = 0; /* True if bug report header was already logged. */\nstatic pthread_mutex_t bug_report_start_mutex = PTHREAD_MUTEX_INITIALIZER;", "/* Forward declarations */\nvoid bugReportStart(void);\nvoid printCrashReport(void);\nvoid bugReportEnd(int killViaSignal, int sig);\nvoid logStackTrace(void *eip, int uplevel);", "/* ================================= Debugging ============================== */", "/* Compute the sha1 of string at 's' with 'len' bytes long.\n * The SHA1 is then xored against the string pointed by digest.\n * Since xor is commutative, this operation is used in order to\n * \"add\" digests relative to unordered elements.\n *\n * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */\nvoid xorDigest(unsigned char *digest, const void *ptr, size_t len) {\n SHA1_CTX ctx;\n unsigned char hash[20];\n int j;", " SHA1Init(&ctx);\n SHA1Update(&ctx,ptr,len);\n SHA1Final(hash,&ctx);", " for (j = 0; j < 20; j++)\n digest[j] ^= hash[j];\n}", "void xorStringObjectDigest(unsigned char *digest, robj *o) {\n o = getDecodedObject(o);\n xorDigest(digest,o->ptr,sdslen(o->ptr));\n decrRefCount(o);\n}", "/* This function instead of just computing the SHA1 and xoring it\n * against digest, also perform the digest of \"digest\" itself and\n * replace the old value with the new one.\n *\n * So the final digest will be:\n *\n * digest = SHA1(digest xor SHA1(data))\n *\n * This function is used every time we want to preserve the order so\n * that digest(a,b,c,d) will be different than digest(b,c,d,a)\n *\n * Also note that mixdigest(\"foo\") followed by mixdigest(\"bar\")\n * will lead to a different digest compared to \"fo\", \"obar\".\n */\nvoid mixDigest(unsigned char *digest, const void *ptr, size_t len) {\n SHA1_CTX ctx;", " xorDigest(digest,ptr,len);\n SHA1Init(&ctx);\n SHA1Update(&ctx,digest,20);\n SHA1Final(digest,&ctx);\n}", "void mixStringObjectDigest(unsigned char *digest, robj *o) {\n o = getDecodedObject(o);\n mixDigest(digest,o->ptr,sdslen(o->ptr));\n decrRefCount(o);\n}", "/* This function computes the digest of a data structure stored in the\n * object 'o'. It is the core of the DEBUG DIGEST command: when taking the\n * digest of a whole dataset, we take the digest of the key and the value\n * pair, and xor all those together.\n *\n * Note that this function does not reset the initial 'digest' passed, it\n * will continue mixing this object digest to anything that was already\n * present. */\nvoid xorObjectDigest(redisDb *db, robj *keyobj, unsigned char *digest, robj *o) {\n uint32_t aux = htonl(o->type);\n mixDigest(digest,&aux,sizeof(aux));\n long long expiretime = getExpire(db,keyobj);\n char buf[128];", " /* Save the key and associated value */\n if (o->type == OBJ_STRING) {\n mixStringObjectDigest(digest,o);\n } else if (o->type == OBJ_LIST) {\n listTypeIterator *li = listTypeInitIterator(o,0,LIST_TAIL);\n listTypeEntry entry;\n while(listTypeNext(li,&entry)) {\n robj *eleobj = listTypeGet(&entry);\n mixStringObjectDigest(digest,eleobj);\n decrRefCount(eleobj);\n }\n listTypeReleaseIterator(li);\n } else if (o->type == OBJ_SET) {\n setTypeIterator *si = setTypeInitIterator(o);\n sds sdsele;\n while((sdsele = setTypeNextObject(si)) != NULL) {\n xorDigest(digest,sdsele,sdslen(sdsele));\n sdsfree(sdsele);\n }\n setTypeReleaseIterator(si);\n } else if (o->type == OBJ_ZSET) {\n unsigned char eledigest[20];", " if (o->encoding == OBJ_ENCODING_LISTPACK) {\n unsigned char *zl = o->ptr;\n unsigned char *eptr, *sptr;\n unsigned char *vstr;\n unsigned int vlen;\n long long vll;\n double score;", " eptr = lpSeek(zl,0);\n serverAssert(eptr != NULL);\n sptr = lpNext(zl,eptr);\n serverAssert(sptr != NULL);", " while (eptr != NULL) {\n vstr = lpGetValue(eptr,&vlen,&vll);\n score = zzlGetScore(sptr);", " memset(eledigest,0,20);\n if (vstr != NULL) {\n mixDigest(eledigest,vstr,vlen);\n } else {\n ll2string(buf,sizeof(buf),vll);\n mixDigest(eledigest,buf,strlen(buf));\n }", " snprintf(buf,sizeof(buf),\"%.17g\",score);\n mixDigest(eledigest,buf,strlen(buf));\n xorDigest(digest,eledigest,20);\n zzlNext(zl,&eptr,&sptr);\n }\n } else if (o->encoding == OBJ_ENCODING_SKIPLIST) {\n zset *zs = o->ptr;\n dictIterator *di = dictGetIterator(zs->dict);\n dictEntry *de;", " while((de = dictNext(di)) != NULL) {\n sds sdsele = dictGetKey(de);\n double *score = dictGetVal(de);", " snprintf(buf,sizeof(buf),\"%.17g\",*score);\n memset(eledigest,0,20);\n mixDigest(eledigest,sdsele,sdslen(sdsele));\n mixDigest(eledigest,buf,strlen(buf));\n xorDigest(digest,eledigest,20);\n }\n dictReleaseIterator(di);\n } else {\n serverPanic(\"Unknown sorted set encoding\");\n }\n } else if (o->type == OBJ_HASH) {\n hashTypeIterator *hi = hashTypeInitIterator(o);\n while (hashTypeNext(hi) != C_ERR) {\n unsigned char eledigest[20];\n sds sdsele;", " memset(eledigest,0,20);\n sdsele = hashTypeCurrentObjectNewSds(hi,OBJ_HASH_KEY);\n mixDigest(eledigest,sdsele,sdslen(sdsele));\n sdsfree(sdsele);\n sdsele = hashTypeCurrentObjectNewSds(hi,OBJ_HASH_VALUE);\n mixDigest(eledigest,sdsele,sdslen(sdsele));\n sdsfree(sdsele);\n xorDigest(digest,eledigest,20);\n }\n hashTypeReleaseIterator(hi);\n } else if (o->type == OBJ_STREAM) {\n streamIterator si;\n streamIteratorStart(&si,o->ptr,NULL,NULL,0);\n streamID id;\n int64_t numfields;", " while(streamIteratorGetID(&si,&id,&numfields)) {\n sds itemid = sdscatfmt(sdsempty(),\"%U.%U\",id.ms,id.seq);\n mixDigest(digest,itemid,sdslen(itemid));\n sdsfree(itemid);", " while(numfields--) {\n unsigned char *field, *value;\n int64_t field_len, value_len;\n streamIteratorGetField(&si,&field,&value,\n &field_len,&value_len);\n mixDigest(digest,field,field_len);\n mixDigest(digest,value,value_len);\n }\n }\n streamIteratorStop(&si);\n } else if (o->type == OBJ_MODULE) {\n RedisModuleDigest md = {{0},{0},keyobj,db->id};\n moduleValue *mv = o->ptr;\n moduleType *mt = mv->type;\n moduleInitDigestContext(md);\n if (mt->digest) {\n mt->digest(&md,mv->value);\n xorDigest(digest,md.x,sizeof(md.x));\n }\n } else {\n serverPanic(\"Unknown object type\");\n }\n /* If the key has an expire, add it to the mix */\n if (expiretime != -1) xorDigest(digest,\"!!expire!!\",10);\n}", "/* Compute the dataset digest. Since keys, sets elements, hashes elements\n * are not ordered, we use a trick: every aggregate digest is the xor\n * of the digests of their elements. This way the order will not change\n * the result. For list instead we use a feedback entering the output digest\n * as input in order to ensure that a different ordered list will result in\n * a different digest. */\nvoid computeDatasetDigest(unsigned char *final) {\n unsigned char digest[20];\n dictIterator *di = NULL;\n dictEntry *de;\n int j;\n uint32_t aux;", " memset(final,0,20); /* Start with a clean result */", " for (j = 0; j < server.dbnum; j++) {\n redisDb *db = server.db+j;", " if (dictSize(db->dict) == 0) continue;\n di = dictGetSafeIterator(db->dict);", " /* hash the DB id, so the same dataset moved in a different\n * DB will lead to a different digest */\n aux = htonl(j);\n mixDigest(final,&aux,sizeof(aux));", " /* Iterate this DB writing every entry */\n while((de = dictNext(di)) != NULL) {\n sds key;\n robj *keyobj, *o;", " memset(digest,0,20); /* This key-val digest */\n key = dictGetKey(de);\n keyobj = createStringObject(key,sdslen(key));", " mixDigest(digest,key,sdslen(key));", " o = dictGetVal(de);\n xorObjectDigest(db,keyobj,digest,o);", " /* We can finally xor the key-val digest to the final digest */\n xorDigest(final,digest,20);\n decrRefCount(keyobj);\n }\n dictReleaseIterator(di);\n }\n}", "#ifdef USE_JEMALLOC\nvoid mallctl_int(client *c, robj **argv, int argc) {\n int ret;\n /* start with the biggest size (int64), and if that fails, try smaller sizes (int32, bool) */\n int64_t old = 0, val;\n if (argc > 1) {\n long long ll;\n if (getLongLongFromObjectOrReply(c, argv[1], &ll, NULL) != C_OK)\n return;\n val = ll;\n }\n size_t sz = sizeof(old);\n while (sz > 0) {\n if ((ret=je_mallctl(argv[0]->ptr, &old, &sz, argc > 1? &val: NULL, argc > 1?sz: 0))) {\n if (ret == EPERM && argc > 1) {\n /* if this option is write only, try just writing to it. */\n if (!(ret=je_mallctl(argv[0]->ptr, NULL, 0, &val, sz))) {\n addReply(c, shared.ok);\n return;\n }\n }\n if (ret==EINVAL) {\n /* size might be wrong, try a smaller one */\n sz /= 2;\n#if BYTE_ORDER == BIG_ENDIAN\n val <<= 8*sz;\n#endif\n continue;\n }\n addReplyErrorFormat(c,\"%s\", strerror(ret));\n return;\n } else {\n#if BYTE_ORDER == BIG_ENDIAN\n old >>= 64 - 8*sz;\n#endif\n addReplyLongLong(c, old);\n return;\n }\n }\n addReplyErrorFormat(c,\"%s\", strerror(EINVAL));\n}", "void mallctl_string(client *c, robj **argv, int argc) {\n int rret, wret;\n char *old;\n size_t sz = sizeof(old);\n /* for strings, it seems we need to first get the old value, before overriding it. */\n if ((rret=je_mallctl(argv[0]->ptr, &old, &sz, NULL, 0))) {\n /* return error unless this option is write only. */\n if (!(rret == EPERM && argc > 1)) {\n addReplyErrorFormat(c,\"%s\", strerror(rret));\n return;\n }\n }\n if(argc > 1) {\n char *val = argv[1]->ptr;\n char **valref = &val;\n if ((!strcmp(val,\"VOID\")))\n valref = NULL, sz = 0;\n wret = je_mallctl(argv[0]->ptr, NULL, 0, valref, sz);\n }\n if (!rret)\n addReplyBulkCString(c, old);\n else if (wret)\n addReplyErrorFormat(c,\"%s\", strerror(wret));\n else\n addReply(c, shared.ok);\n}\n#endif", "void debugCommand(client *c) {\n if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,\"help\")) {\n const char *help[] = {\n\"AOF-FLUSH-SLEEP <microsec>\",\n\" Server will sleep before flushing the AOF, this is used for testing.\",\n\"ASSERT\",\n\" Crash by assertion failed.\",\n\"CHANGE-REPL-ID\",\n\" Change the replication IDs of the instance.\",\n\" Dangerous: should be used only for testing the replication subsystem.\",\n\"CONFIG-REWRITE-FORCE-ALL\",\n\" Like CONFIG REWRITE but writes all configuration options, including\",\n\" keywords not listed in original configuration file or default values.\",\n\"CRASH-AND-RECOVER [<milliseconds>]\",\n\" Hard crash and restart after a <milliseconds> delay (default 0).\",\n\"DIGEST\",\n\" Output a hex signature representing the current DB content.\",\n\"DIGEST-VALUE <key> [<key> ...]\",\n\" Output a hex signature of the values of all the specified keys.\",\n\"ERROR <string>\",\n\" Return a Redis protocol error with <string> as message. Useful for clients\",\n\" unit tests to simulate Redis errors.\",\n\"LEAK <string>\",\n\" Create a memory leak of the input string.\",\n\"LOG <message>\",\n\" Write <message> to the server log.\",\n\"HTSTATS <dbid>\",\n\" Return hash table statistics of the specified Redis database.\",\n\"HTSTATS-KEY <key>\",\n\" Like HTSTATS but for the hash table stored at <key>'s value.\",\n\"LOADAOF\",\n\" Flush the AOF buffers on disk and reload the AOF in memory.\",\n\"REPLICATE <string>\",\n\" Replicates the provided string to replicas, allowing data divergence.\",\n#ifdef USE_JEMALLOC\n\"MALLCTL <key> [<val>]\",\n\" Get or set a malloc tuning integer.\",\n\"MALLCTL-STR <key> [<val>]\",\n\" Get or set a malloc tuning string.\",\n#endif\n\"OBJECT <key>\",\n\" Show low level info about `key` and associated value.\",\n\"DROP-CLUSTER-PACKET-FILTER <packet-type>\",\n\" Drop all packets that match the filtered type. Set to -1 allow all packets.\",\n\"OOM\",\n\" Crash the server simulating an out-of-memory error.\",\n\"PANIC\",\n\" Crash the server simulating a panic.\",\n\"POPULATE <count> [<prefix>] [<size>]\",\n\" Create <count> string keys named key:<num>. If <prefix> is specified then\",\n\" it is used instead of the 'key' prefix. These are not propagated to\",\n\" replicas. Cluster slots are not respected so keys not belonging to the\",\n\" current node can be created in cluster mode.\",\n\"PROTOCOL <type>\",\n\" Reply with a test value of the specified type. <type> can be: string,\",\n\" integer, double, bignum, null, array, set, map, attrib, push, verbatim,\",\n\" true, false.\",\n\"RELOAD [option ...]\",\n\" Save the RDB on disk and reload it back to memory. Valid <option> values:\",\n\" * MERGE: conflicting keys will be loaded from RDB.\",\n\" * NOFLUSH: the existing database will not be removed before load, but\",\n\" conflicting keys will generate an exception and kill the server.\",\n\" * NOSAVE: the database will be loaded from an existing RDB file.\",\n\" Examples:\",\n\" * DEBUG RELOAD: verify that the server is able to persist, flush and reload\",\n\" the database.\",\n\" * DEBUG RELOAD NOSAVE: replace the current database with the contents of an\",\n\" existing RDB file.\",\n\" * DEBUG RELOAD NOSAVE NOFLUSH MERGE: add the contents of an existing RDB\",\n\" file to the database.\",\n\"RESTART [<milliseconds>]\",\n\" Graceful restart: save config, db, restart after a <milliseconds> delay (default 0).\",\n\"SDSLEN <key>\",\n\" Show low level SDS string info representing `key` and value.\",\n\"SEGFAULT\",\n\" Crash the server with sigsegv.\",\n\"SET-ACTIVE-EXPIRE <0|1>\",\n\" Setting it to 0 disables expiring keys in background when they are not\",\n\" accessed (otherwise the Redis behavior). Setting it to 1 reenables back the\",\n\" default.\",\n\"QUICKLIST-PACKED-THRESHOLD <size>\",\n\" Sets the threshold for elements to be inserted as plain vs packed nodes\",\n\" Default value is 1GB, allows values up to 4GB. Setting to 0 restores to default.\",\n\"SET-SKIP-CHECKSUM-VALIDATION <0|1>\",\n\" Enables or disables checksum checks for RDB files and RESTORE's payload.\",\n\"SLEEP <seconds>\",\n\" Stop the server for <seconds>. Decimals allowed.\",\n\"STRINGMATCH-TEST\",\n\" Run a fuzz tester against the stringmatchlen() function.\",\n\"STRUCTSIZE\",\n\" Return the size of different Redis core C structures.\",\n\"LISTPACK <key>\",\n\" Show low level info about the listpack encoding of <key>.\",\n\"QUICKLIST <key> [<0|1>]\",\n\" Show low level info about the quicklist encoding of <key>.\",\n\" The optional argument (0 by default) sets the level of detail\",\n\"CLIENT-EVICTION\",\n\" Show low level client eviction pools info (maxmemory-clients).\",\n\"PAUSE-CRON <0|1>\",\n\" Stop periodic cron job processing.\",\n\"REPLYBUFFER PEAK-RESET-TIME <NEVER||RESET|time>\",\n\" Sets the time (in milliseconds) to wait between client reply buffer peak resets.\",\n\" In case NEVER is provided the last observed peak will never be reset\",\n\" In case RESET is provided the peak reset time will be restored to the default value\",\n\"REPLYBUFFER RESIZING <0|1>\",\n\" Enable or disable the reply buffer resize cron job\",\nNULL\n };\n addReplyHelp(c, help);\n } else if (!strcasecmp(c->argv[1]->ptr,\"segfault\")) {\n /* Compiler gives warnings about writing to a random address\n * e.g \"*((char*)-1) = 'x';\". As a workaround, we map a read-only area\n * and try to write there to trigger segmentation fault. */\n char* p = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANON, -1, 0);\n *p = 'x';\n } else if (!strcasecmp(c->argv[1]->ptr,\"panic\")) {\n serverPanic(\"DEBUG PANIC called at Unix time %lld\", (long long)time(NULL));\n } else if (!strcasecmp(c->argv[1]->ptr,\"restart\") ||\n !strcasecmp(c->argv[1]->ptr,\"crash-and-recover\"))\n {\n long long delay = 0;\n if (c->argc >= 3) {\n if (getLongLongFromObjectOrReply(c, c->argv[2], &delay, NULL)\n != C_OK) return;\n if (delay < 0) delay = 0;\n }\n int flags = !strcasecmp(c->argv[1]->ptr,\"restart\") ?\n (RESTART_SERVER_GRACEFULLY|RESTART_SERVER_CONFIG_REWRITE) :\n RESTART_SERVER_NONE;\n restartServer(flags,delay);\n addReplyError(c,\"failed to restart the server. Check server logs.\");\n } else if (!strcasecmp(c->argv[1]->ptr,\"oom\")) {\n void *ptr = zmalloc(ULONG_MAX); /* Should trigger an out of memory. */\n zfree(ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"assert\")) {\n serverAssertWithInfo(c,c->argv[0],1 == 2);\n } else if (!strcasecmp(c->argv[1]->ptr,\"log\") && c->argc == 3) {\n serverLog(LL_WARNING, \"DEBUG LOG: %s\", (char*)c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"leak\") && c->argc == 3) {\n sdsdup(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"reload\")) {\n int flush = 1, save = 1;\n int flags = RDBFLAGS_NONE;", " /* Parse the additional options that modify the RELOAD\n * behavior. */\n for (int j = 2; j < c->argc; j++) {\n char *opt = c->argv[j]->ptr;\n if (!strcasecmp(opt,\"MERGE\")) {\n flags |= RDBFLAGS_ALLOW_DUP;\n } else if (!strcasecmp(opt,\"NOFLUSH\")) {\n flush = 0;\n } else if (!strcasecmp(opt,\"NOSAVE\")) {\n save = 0;\n } else {\n addReplyError(c,\"DEBUG RELOAD only supports the \"\n \"MERGE, NOFLUSH and NOSAVE options.\");\n return;\n }\n }", " /* The default behavior is to save the RDB file before loading\n * it back. */\n if (save) {\n rdbSaveInfo rsi, *rsiptr;\n rsiptr = rdbPopulateSaveInfo(&rsi);\n if (rdbSave(SLAVE_REQ_NONE,server.rdb_filename,rsiptr) != C_OK) {\n addReplyErrorObject(c,shared.err);\n return;\n }\n }", " /* The default behavior is to remove the current dataset from\n * memory before loading the RDB file, however when MERGE is\n * used together with NOFLUSH, we are able to merge two datasets. */\n if (flush) emptyData(-1,EMPTYDB_NO_FLAGS,NULL);", " protectClient(c);\n int ret = rdbLoad(server.rdb_filename,NULL,flags);\n unprotectClient(c);\n if (ret != RDB_OK) {\n addReplyError(c,\"Error trying to load the RDB dump, check server logs.\");\n return;\n }\n serverLog(LL_WARNING,\"DB reloaded by DEBUG RELOAD\");\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"loadaof\")) {\n if (server.aof_state != AOF_OFF) flushAppendOnlyFile(1);\n emptyData(-1,EMPTYDB_NO_FLAGS,NULL);\n protectClient(c);\n if (server.aof_manifest) aofManifestFree(server.aof_manifest);\n aofLoadManifestFromDisk();\n aofDelHistoryFiles();\n int ret = loadAppendOnlyFiles(server.aof_manifest);\n if (ret != AOF_OK && ret != AOF_EMPTY)\n exit(1);\n unprotectClient(c);\n server.dirty = 0; /* Prevent AOF / replication */\n serverLog(LL_WARNING,\"Append Only File loaded by DEBUG LOADAOF\");\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"drop-cluster-packet-filter\") && c->argc == 3) {\n long packet_type;\n if (getLongFromObjectOrReply(c, c->argv[2], &packet_type, NULL) != C_OK)\n return;\n server.cluster_drop_packet_filter = packet_type;\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"object\") && c->argc == 3) {\n dictEntry *de;\n robj *val;\n char *strenc;", " if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) {\n addReplyErrorObject(c,shared.nokeyerr);\n return;\n }\n val = dictGetVal(de);\n strenc = strEncoding(val->encoding);", " char extra[138] = {0};\n if (val->encoding == OBJ_ENCODING_QUICKLIST) {\n char *nextra = extra;\n int remaining = sizeof(extra);\n quicklist *ql = val->ptr;\n /* Add number of quicklist nodes */\n int used = snprintf(nextra, remaining, \" ql_nodes:%lu\", ql->len);\n nextra += used;\n remaining -= used;\n /* Add average quicklist fill factor */\n double avg = (double)ql->count/ql->len;\n used = snprintf(nextra, remaining, \" ql_avg_node:%.2f\", avg);\n nextra += used;\n remaining -= used;\n /* Add quicklist fill level / max listpack size */\n used = snprintf(nextra, remaining, \" ql_listpack_max:%d\", ql->fill);\n nextra += used;\n remaining -= used;\n /* Add isCompressed? */\n int compressed = ql->compress != 0;\n used = snprintf(nextra, remaining, \" ql_compressed:%d\", compressed);\n nextra += used;\n remaining -= used;\n /* Add total uncompressed size */\n unsigned long sz = 0;\n for (quicklistNode *node = ql->head; node; node = node->next) {\n sz += node->sz;\n }\n used = snprintf(nextra, remaining, \" ql_uncompressed_size:%lu\", sz);\n nextra += used;\n remaining -= used;\n }", " addReplyStatusFormat(c,\n \"Value at:%p refcount:%d \"\n \"encoding:%s serializedlength:%zu \"\n \"lru:%d lru_seconds_idle:%llu%s\",\n (void*)val, val->refcount,\n strenc, rdbSavedObjectLen(val, c->argv[2], c->db->id),\n val->lru, estimateObjectIdleTime(val)/1000, extra);\n } else if (!strcasecmp(c->argv[1]->ptr,\"sdslen\") && c->argc == 3) {\n dictEntry *de;\n robj *val;\n sds key;", " if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) {\n addReplyErrorObject(c,shared.nokeyerr);\n return;\n }\n val = dictGetVal(de);\n key = dictGetKey(de);", " if (val->type != OBJ_STRING || !sdsEncodedObject(val)) {\n addReplyError(c,\"Not an sds encoded string.\");\n } else {\n addReplyStatusFormat(c,\n \"key_sds_len:%lld, key_sds_avail:%lld, key_zmalloc: %lld, \"\n \"val_sds_len:%lld, val_sds_avail:%lld, val_zmalloc: %lld\",\n (long long) sdslen(key),\n (long long) sdsavail(key),\n (long long) sdsZmallocSize(key),\n (long long) sdslen(val->ptr),\n (long long) sdsavail(val->ptr),\n (long long) getStringObjectSdsUsedMemory(val));\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"listpack\") && c->argc == 3) {\n robj *o;", " if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.nokeyerr))\n == NULL) return;", " if (o->encoding != OBJ_ENCODING_LISTPACK) {\n addReplyError(c,\"Not a listpack encoded object.\");\n } else {\n lpRepr(o->ptr);\n addReplyStatus(c,\"Listpack structure printed on stdout\");\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"quicklist\") && (c->argc == 3 || c->argc == 4)) {\n robj *o;", " if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.nokeyerr))\n == NULL) return;", " int full = 0;\n if (c->argc == 4)\n full = atoi(c->argv[3]->ptr);\n if (o->encoding != OBJ_ENCODING_QUICKLIST) {\n addReplyError(c,\"Not a quicklist encoded object.\");\n } else {\n quicklistRepr(o->ptr, full);\n addReplyStatus(c,\"Quicklist structure printed on stdout\");\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"populate\") &&\n c->argc >= 3 && c->argc <= 5) {\n long keys, j;\n robj *key, *val;\n char buf[128];", " if (getPositiveLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != C_OK)\n return;", " dictExpand(c->db->dict,keys);\n long valsize = 0;\n if ( c->argc == 5 && getPositiveLongFromObjectOrReply(c, c->argv[4], &valsize, NULL) != C_OK ) \n return;", " for (j = 0; j < keys; j++) {\n snprintf(buf,sizeof(buf),\"%s:%lu\",\n (c->argc == 3) ? \"key\" : (char*)c->argv[3]->ptr, j);\n key = createStringObject(buf,strlen(buf));\n if (lookupKeyWrite(c->db,key) != NULL) {\n decrRefCount(key);\n continue;\n }\n snprintf(buf,sizeof(buf),\"value:%lu\",j);\n if (valsize==0)\n val = createStringObject(buf,strlen(buf));\n else {\n int buflen = strlen(buf);\n val = createStringObject(NULL,valsize);\n memcpy(val->ptr, buf, valsize<=buflen? valsize: buflen);\n }\n dbAdd(c->db,key,val);\n signalModifiedKey(c,c->db,key);\n decrRefCount(key);\n }\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"digest\") && c->argc == 2) {\n /* DEBUG DIGEST (form without keys specified) */\n unsigned char digest[20];\n sds d = sdsempty();", " computeDatasetDigest(digest);\n for (int i = 0; i < 20; i++) d = sdscatprintf(d, \"%02x\",digest[i]);\n addReplyStatus(c,d);\n sdsfree(d);\n } else if (!strcasecmp(c->argv[1]->ptr,\"digest-value\") && c->argc >= 2) {\n /* DEBUG DIGEST-VALUE key key key ... key. */\n addReplyArrayLen(c,c->argc-2);\n for (int j = 2; j < c->argc; j++) {\n unsigned char digest[20];\n memset(digest,0,20); /* Start with a clean result */", " /* We don't use lookupKey because a debug command should\n * work on logically expired keys */\n dictEntry *de;\n robj *o = ((de = dictFind(c->db->dict,c->argv[j]->ptr)) == NULL) ? NULL : dictGetVal(de);\n if (o) xorObjectDigest(c->db,c->argv[j],digest,o);", " sds d = sdsempty();\n for (int i = 0; i < 20; i++) d = sdscatprintf(d, \"%02x\",digest[i]);\n addReplyStatus(c,d);\n sdsfree(d);\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"protocol\") && c->argc == 3) {\n /* DEBUG PROTOCOL [string|integer|double|bignum|null|array|set|map|\n * attrib|push|verbatim|true|false] */\n char *name = c->argv[2]->ptr;\n if (!strcasecmp(name,\"string\")) {\n addReplyBulkCString(c,\"Hello World\");\n } else if (!strcasecmp(name,\"integer\")) {\n addReplyLongLong(c,12345);\n } else if (!strcasecmp(name,\"double\")) {\n addReplyDouble(c,3.141);\n } else if (!strcasecmp(name,\"bignum\")) {\n addReplyBigNum(c,\"1234567999999999999999999999999999999\",37);\n } else if (!strcasecmp(name,\"null\")) {\n addReplyNull(c);\n } else if (!strcasecmp(name,\"array\")) {\n addReplyArrayLen(c,3);\n for (int j = 0; j < 3; j++) addReplyLongLong(c,j);\n } else if (!strcasecmp(name,\"set\")) {\n addReplySetLen(c,3);\n for (int j = 0; j < 3; j++) addReplyLongLong(c,j);\n } else if (!strcasecmp(name,\"map\")) {\n addReplyMapLen(c,3);\n for (int j = 0; j < 3; j++) {\n addReplyLongLong(c,j);\n addReplyBool(c, j == 1);\n }\n } else if (!strcasecmp(name,\"attrib\")) {\n if (c->resp >= 3) {\n addReplyAttributeLen(c,1);\n addReplyBulkCString(c,\"key-popularity\");\n addReplyArrayLen(c,2);\n addReplyBulkCString(c,\"key:123\");\n addReplyLongLong(c,90);\n }\n /* Attributes are not real replies, so a well formed reply should\n * also have a normal reply type after the attribute. */\n addReplyBulkCString(c,\"Some real reply following the attribute\");\n } else if (!strcasecmp(name,\"push\")) {\n if (c->resp < 3) {\n addReplyError(c,\"RESP2 is not supported by this command\");\n return;\n\t }\n addReplyPushLen(c,2);\n addReplyBulkCString(c,\"server-cpu-usage\");\n addReplyLongLong(c,42);\n /* Push replies are not synchronous replies, so we emit also a\n * normal reply in order for blocking clients just discarding the\n * push reply, to actually consume the reply and continue. */\n addReplyBulkCString(c,\"Some real reply following the push reply\");\n } else if (!strcasecmp(name,\"true\")) {\n addReplyBool(c,1);\n } else if (!strcasecmp(name,\"false\")) {\n addReplyBool(c,0);\n } else if (!strcasecmp(name,\"verbatim\")) {\n addReplyVerbatim(c,\"This is a verbatim\\nstring\",25,\"txt\");\n } else {\n addReplyError(c,\"Wrong protocol type name. Please use one of the following: string|integer|double|bignum|null|array|set|map|attrib|push|verbatim|true|false\");\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"sleep\") && c->argc == 3) {\n double dtime = strtod(c->argv[2]->ptr,NULL);\n long long utime = dtime*1000000;\n struct timespec tv;", " tv.tv_sec = utime / 1000000;\n tv.tv_nsec = (utime % 1000000) * 1000;\n nanosleep(&tv, NULL);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"set-active-expire\") &&\n c->argc == 3)\n {\n server.active_expire_enabled = atoi(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"quicklist-packed-threshold\") &&\n c->argc == 3)\n {\n int memerr;\n unsigned long long sz = memtoull((const char *)c->argv[2]->ptr, &memerr);\n if (memerr || !quicklistisSetPackedThreshold(sz)) {\n addReplyError(c, \"argument must be a memory value bigger than 1 and smaller than 4gb\");\n } else {\n addReply(c,shared.ok);\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"set-skip-checksum-validation\") &&\n c->argc == 3)\n {\n server.skip_checksum_validation = atoi(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"aof-flush-sleep\") &&\n c->argc == 3)\n {\n server.aof_flush_sleep = atoi(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"replicate\") && c->argc >= 3) {\n replicationFeedSlaves(server.slaves, -1,\n c->argv + 2, c->argc - 2);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"error\") && c->argc == 3) {\n sds errstr = sdsnewlen(\"-\",1);", " errstr = sdscatsds(errstr,c->argv[2]->ptr);\n errstr = sdsmapchars(errstr,\"\\n\\r\",\" \",2); /* no newlines in errors. */\n errstr = sdscatlen(errstr,\"\\r\\n\",2);\n addReplySds(c,errstr);\n } else if (!strcasecmp(c->argv[1]->ptr,\"structsize\") && c->argc == 2) {\n sds sizes = sdsempty();\n sizes = sdscatprintf(sizes,\"bits:%d \",(sizeof(void*) == 8)?64:32);\n sizes = sdscatprintf(sizes,\"robj:%d \",(int)sizeof(robj));\n sizes = sdscatprintf(sizes,\"dictentry:%d \",(int)sizeof(dictEntry));\n sizes = sdscatprintf(sizes,\"sdshdr5:%d \",(int)sizeof(struct sdshdr5));\n sizes = sdscatprintf(sizes,\"sdshdr8:%d \",(int)sizeof(struct sdshdr8));\n sizes = sdscatprintf(sizes,\"sdshdr16:%d \",(int)sizeof(struct sdshdr16));\n sizes = sdscatprintf(sizes,\"sdshdr32:%d \",(int)sizeof(struct sdshdr32));\n sizes = sdscatprintf(sizes,\"sdshdr64:%d \",(int)sizeof(struct sdshdr64));\n addReplyBulkSds(c,sizes);\n } else if (!strcasecmp(c->argv[1]->ptr,\"htstats\") && c->argc == 3) {\n long dbid;\n sds stats = sdsempty();\n char buf[4096];", " if (getLongFromObjectOrReply(c, c->argv[2], &dbid, NULL) != C_OK) {\n sdsfree(stats);\n return;\n }\n if (dbid < 0 || dbid >= server.dbnum) {\n sdsfree(stats);\n addReplyError(c,\"Out of range database\");\n return;\n }", " stats = sdscatprintf(stats,\"[Dictionary HT]\\n\");\n dictGetStats(buf,sizeof(buf),server.db[dbid].dict);\n stats = sdscat(stats,buf);", " stats = sdscatprintf(stats,\"[Expires HT]\\n\");\n dictGetStats(buf,sizeof(buf),server.db[dbid].expires);\n stats = sdscat(stats,buf);", " addReplyVerbatim(c,stats,sdslen(stats),\"txt\");\n sdsfree(stats);\n } else if (!strcasecmp(c->argv[1]->ptr,\"htstats-key\") && c->argc == 3) {\n robj *o;\n dict *ht = NULL;", " if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.nokeyerr))\n == NULL) return;", " /* Get the hash table reference from the object, if possible. */\n switch (o->encoding) {\n case OBJ_ENCODING_SKIPLIST:\n {\n zset *zs = o->ptr;\n ht = zs->dict;\n }\n break;\n case OBJ_ENCODING_HT:\n ht = o->ptr;\n break;\n }", " if (ht == NULL) {\n addReplyError(c,\"The value stored at the specified key is not \"\n \"represented using an hash table\");\n } else {\n char buf[4096];\n dictGetStats(buf,sizeof(buf),ht);\n addReplyVerbatim(c,buf,strlen(buf),\"txt\");\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"change-repl-id\") && c->argc == 2) {\n serverLog(LL_WARNING,\"Changing replication IDs after receiving DEBUG change-repl-id\");\n changeReplicationId();\n clearReplicationId2();\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"stringmatch-test\") && c->argc == 2)\n {\n stringmatchlen_fuzz_test();\n addReplyStatus(c,\"Apparently Redis did not crash: test passed\");\n } else if (!strcasecmp(c->argv[1]->ptr,\"set-disable-deny-scripts\") && c->argc == 3)\n {\n server.script_disable_deny_script = atoi(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"config-rewrite-force-all\") && c->argc == 2)\n {\n if (rewriteConfig(server.configfile, 1) == -1)\n addReplyErrorFormat(c, \"CONFIG-REWRITE-FORCE-ALL failed: %s\", strerror(errno));\n else\n addReply(c, shared.ok);\n } else if(!strcasecmp(c->argv[1]->ptr,\"client-eviction\") && c->argc == 2) {\n sds bucket_info = sdsempty();\n for (int j = 0; j < CLIENT_MEM_USAGE_BUCKETS; j++) {\n if (j == 0)\n bucket_info = sdscatprintf(bucket_info, \"bucket 0\");\n else\n bucket_info = sdscatprintf(bucket_info, \"bucket %10zu\", (size_t)1<<(j-1+CLIENT_MEM_USAGE_BUCKET_MIN_LOG));\n if (j == CLIENT_MEM_USAGE_BUCKETS-1)\n bucket_info = sdscatprintf(bucket_info, \"+ : \");\n else\n bucket_info = sdscatprintf(bucket_info, \" - %10zu: \", ((size_t)1<<(j+CLIENT_MEM_USAGE_BUCKET_MIN_LOG))-1);\n bucket_info = sdscatprintf(bucket_info, \"tot-mem: %10zu, clients: %lu\\n\",\n server.client_mem_usage_buckets[j].mem_usage_sum,\n server.client_mem_usage_buckets[j].clients->len);\n }\n addReplyVerbatim(c,bucket_info,sdslen(bucket_info),\"txt\");\n sdsfree(bucket_info);\n#ifdef USE_JEMALLOC\n } else if(!strcasecmp(c->argv[1]->ptr,\"mallctl\") && c->argc >= 3) {\n mallctl_int(c, c->argv+2, c->argc-2);\n return;\n } else if(!strcasecmp(c->argv[1]->ptr,\"mallctl-str\") && c->argc >= 3) {\n mallctl_string(c, c->argv+2, c->argc-2);\n return;\n#endif\n } else if (!strcasecmp(c->argv[1]->ptr,\"pause-cron\") && c->argc == 3)\n {\n server.pause_cron = atoi(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"replybuffer\") && c->argc == 4 ) {\n if(!strcasecmp(c->argv[2]->ptr, \"peak-reset-time\")) {\n if (!strcasecmp(c->argv[3]->ptr, \"never\")) {\n server.reply_buffer_peak_reset_time = -1;\n } else if(!strcasecmp(c->argv[3]->ptr, \"reset\")) {\n server.reply_buffer_peak_reset_time = REPLY_BUFFER_DEFAULT_PEAK_RESET_TIME;\n } else {\n if (getLongFromObjectOrReply(c, c->argv[3], &server.reply_buffer_peak_reset_time, NULL) != C_OK)\n return;\n }\n } else if(!strcasecmp(c->argv[2]->ptr,\"resizing\")) {\n server.reply_buffer_resizing_enabled = atoi(c->argv[3]->ptr);\n } else {\n addReplySubcommandSyntaxError(c);\n return;\n }\n addReply(c, shared.ok);\n } else {\n addReplySubcommandSyntaxError(c);\n return;\n }\n}", "/* =========================== Crash handling ============================== */", "void _serverAssert(const char *estr, const char *file, int line) {\n bugReportStart();\n serverLog(LL_WARNING,\"=== ASSERTION FAILED ===\");\n serverLog(LL_WARNING,\"==> %s:%d '%s' is not true\",file,line,estr);", " if (server.crashlog_enabled) {\n#ifdef HAVE_BACKTRACE\n logStackTrace(NULL, 1);\n#endif\n printCrashReport();\n }", " // remove the signal handler so on abort() we will output the crash report.\n removeSignalHandlers();\n bugReportEnd(0, 0);\n}", "void _serverAssertPrintClientInfo(const client *c) {\n int j;\n char conninfo[CONN_INFO_LEN];", " bugReportStart();\n serverLog(LL_WARNING,\"=== ASSERTION FAILED CLIENT CONTEXT ===\");\n serverLog(LL_WARNING,\"client->flags = %llu\", (unsigned long long) c->flags);\n serverLog(LL_WARNING,\"client->conn = %s\", connGetInfo(c->conn, conninfo, sizeof(conninfo)));\n serverLog(LL_WARNING,\"client->argc = %d\", c->argc);\n for (j=0; j < c->argc; j++) {\n char buf[128];\n char *arg;", " if (c->argv[j]->type == OBJ_STRING && sdsEncodedObject(c->argv[j])) {\n arg = (char*) c->argv[j]->ptr;\n } else {\n snprintf(buf,sizeof(buf),\"Object type: %u, encoding: %u\",\n c->argv[j]->type, c->argv[j]->encoding);\n arg = buf;\n }\n serverLog(LL_WARNING,\"client->argv[%d] = \\\"%s\\\" (refcount: %d)\",\n j, arg, c->argv[j]->refcount);\n }\n}", "void serverLogObjectDebugInfo(const robj *o) {\n serverLog(LL_WARNING,\"Object type: %u\", o->type);\n serverLog(LL_WARNING,\"Object encoding: %u\", o->encoding);\n serverLog(LL_WARNING,\"Object refcount: %d\", o->refcount);\n#if UNSAFE_CRASH_REPORT\n /* This code is now disabled. o->ptr may be unreliable to print. in some\n * cases a ziplist could have already been freed by realloc, but not yet\n * updated to o->ptr. in other cases the call to ziplistLen may need to\n * iterate on all the items in the list (and possibly crash again).\n * For some cases it may be ok to crash here again, but these could cause\n * invalid memory access which will bother valgrind and also possibly cause\n * random memory portion to be \"leaked\" into the logfile. */\n if (o->type == OBJ_STRING && sdsEncodedObject(o)) {\n serverLog(LL_WARNING,\"Object raw string len: %zu\", sdslen(o->ptr));\n if (sdslen(o->ptr) < 4096) {\n sds repr = sdscatrepr(sdsempty(),o->ptr,sdslen(o->ptr));\n serverLog(LL_WARNING,\"Object raw string content: %s\", repr);\n sdsfree(repr);\n }\n } else if (o->type == OBJ_LIST) {\n serverLog(LL_WARNING,\"List length: %d\", (int) listTypeLength(o));\n } else if (o->type == OBJ_SET) {\n serverLog(LL_WARNING,\"Set size: %d\", (int) setTypeSize(o));\n } else if (o->type == OBJ_HASH) {\n serverLog(LL_WARNING,\"Hash size: %d\", (int) hashTypeLength(o));\n } else if (o->type == OBJ_ZSET) {\n serverLog(LL_WARNING,\"Sorted set size: %d\", (int) zsetLength(o));\n if (o->encoding == OBJ_ENCODING_SKIPLIST)\n serverLog(LL_WARNING,\"Skiplist level: %d\", (int) ((const zset*)o->ptr)->zsl->level);\n } else if (o->type == OBJ_STREAM) {\n serverLog(LL_WARNING,\"Stream size: %d\", (int) streamLength(o));\n }\n#endif\n}", "void _serverAssertPrintObject(const robj *o) {\n bugReportStart();\n serverLog(LL_WARNING,\"=== ASSERTION FAILED OBJECT CONTEXT ===\");\n serverLogObjectDebugInfo(o);\n}", "void _serverAssertWithInfo(const client *c, const robj *o, const char *estr, const char *file, int line) {\n if (c) _serverAssertPrintClientInfo(c);\n if (o) _serverAssertPrintObject(o);\n _serverAssert(estr,file,line);\n}", "void _serverPanic(const char *file, int line, const char *msg, ...) {\n va_list ap;\n va_start(ap,msg);\n char fmtmsg[256];\n vsnprintf(fmtmsg,sizeof(fmtmsg),msg,ap);\n va_end(ap);", " bugReportStart();\n serverLog(LL_WARNING,\"------------------------------------------------\");\n serverLog(LL_WARNING,\"!!! Software Failure. Press left mouse button to continue\");\n serverLog(LL_WARNING,\"Guru Meditation: %s #%s:%d\",fmtmsg,file,line);", " if (server.crashlog_enabled) {\n#ifdef HAVE_BACKTRACE\n logStackTrace(NULL, 1);\n#endif\n printCrashReport();\n }", " // remove the signal handler so on abort() we will output the crash report.\n removeSignalHandlers();\n bugReportEnd(0, 0);\n}", "void bugReportStart(void) {\n pthread_mutex_lock(&bug_report_start_mutex);\n if (bug_report_start == 0) {\n serverLogRaw(LL_WARNING|LL_RAW,\n \"\\n\\n=== REDIS BUG REPORT START: Cut & paste starting from here ===\\n\");\n bug_report_start = 1;\n }\n pthread_mutex_unlock(&bug_report_start_mutex);\n}", "#ifdef HAVE_BACKTRACE", "static void *getMcontextEip(ucontext_t *uc) {", "#define NOT_SUPPORTED() do {\\\n UNUSED(uc);\\", "", " return NULL;\\", "", "} while(0)\n#if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)\n /* OSX < 10.6 */\n #if defined(__x86_64__)", " return (void*) uc->uc_mcontext->__ss.__rip;", " #elif defined(__i386__)", " return (void*) uc->uc_mcontext->__ss.__eip;", " #else", " return (void*) uc->uc_mcontext->__ss.__srr0;", " #endif\n#elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)\n /* OSX >= 10.6 */\n #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)", " return (void*) uc->uc_mcontext->__ss.__rip;", " #elif defined(__i386__)", " return (void*) uc->uc_mcontext->__ss.__eip;", " #else\n /* OSX ARM64 */", " return (void*) arm_thread_state64_get_pc(uc->uc_mcontext->__ss);", " #endif\n#elif defined(__linux__)\n /* Linux */\n #if defined(__i386__) || ((defined(__X86_64__) || defined(__x86_64__)) && defined(__ILP32__))", " return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */", " #elif defined(__X86_64__) || defined(__x86_64__)", " return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */", " #elif defined(__ia64__) /* Linux IA64 */", " return (void*) uc->uc_mcontext.sc_ip;", " #elif defined(__arm__) /* Linux ARM */", " return (void*) uc->uc_mcontext.arm_pc;", " #elif defined(__aarch64__) /* Linux AArch64 */", " return (void*) uc->uc_mcontext.pc;", " #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__FreeBSD__)\n /* FreeBSD */\n #if defined(__i386__)", " return (void*) uc->uc_mcontext.mc_eip;", " #elif defined(__x86_64__)", " return (void*) uc->uc_mcontext.mc_rip;", " #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__OpenBSD__)\n /* OpenBSD */\n #if defined(__i386__)", " return (void*) uc->sc_eip;", " #elif defined(__x86_64__)", " return (void*) uc->sc_rip;", " #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__NetBSD__)\n #if defined(__i386__)", " return (void*) uc->uc_mcontext.__gregs[_REG_EIP];", " #elif defined(__x86_64__)", " return (void*) uc->uc_mcontext.__gregs[_REG_RIP];", " #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__DragonFly__)", " return (void*) uc->uc_mcontext.mc_rip;", "#else\n NOT_SUPPORTED();\n#endif\n#undef NOT_SUPPORTED\n}", "REDIS_NO_SANITIZE(\"address\")\nvoid logStackContent(void **sp) {\n int i;\n for (i = 15; i >= 0; i--) {\n unsigned long addr = (unsigned long) sp+i;\n unsigned long val = (unsigned long) sp[i];", " if (sizeof(long) == 4)\n serverLog(LL_WARNING, \"(%08lx) -> %08lx\", addr, val);\n else\n serverLog(LL_WARNING, \"(%016lx) -> %016lx\", addr, val);\n }\n}", "/* Log dump of processor registers */\nvoid logRegisters(ucontext_t *uc) {\n serverLog(LL_WARNING|LL_RAW, \"\\n------ REGISTERS ------\\n\");\n#define NOT_SUPPORTED() do {\\\n UNUSED(uc);\\\n serverLog(LL_WARNING,\\\n \" Dumping of registers not supported for this OS/arch\");\\\n} while(0)", "/* OSX */\n#if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)\n /* OSX AMD64 */\n #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCS :%016lx FS:%016lx GS:%016lx\",\n (unsigned long) uc->uc_mcontext->__ss.__rax,\n (unsigned long) uc->uc_mcontext->__ss.__rbx,\n (unsigned long) uc->uc_mcontext->__ss.__rcx,\n (unsigned long) uc->uc_mcontext->__ss.__rdx,\n (unsigned long) uc->uc_mcontext->__ss.__rdi,\n (unsigned long) uc->uc_mcontext->__ss.__rsi,\n (unsigned long) uc->uc_mcontext->__ss.__rbp,\n (unsigned long) uc->uc_mcontext->__ss.__rsp,\n (unsigned long) uc->uc_mcontext->__ss.__r8,\n (unsigned long) uc->uc_mcontext->__ss.__r9,\n (unsigned long) uc->uc_mcontext->__ss.__r10,\n (unsigned long) uc->uc_mcontext->__ss.__r11,\n (unsigned long) uc->uc_mcontext->__ss.__r12,\n (unsigned long) uc->uc_mcontext->__ss.__r13,\n (unsigned long) uc->uc_mcontext->__ss.__r14,\n (unsigned long) uc->uc_mcontext->__ss.__r15,\n (unsigned long) uc->uc_mcontext->__ss.__rip,\n (unsigned long) uc->uc_mcontext->__ss.__rflags,\n (unsigned long) uc->uc_mcontext->__ss.__cs,\n (unsigned long) uc->uc_mcontext->__ss.__fs,\n (unsigned long) uc->uc_mcontext->__ss.__gs\n );\n logStackContent((void**)uc->uc_mcontext->__ss.__rsp);\n #elif defined(__i386__)\n /* OSX x86 */\n serverLog(LL_WARNING,\n \"\\n\"\n \"EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\\n\"\n \"EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\\n\"\n \"SS:%08lx EFL:%08lx EIP:%08lx CS :%08lx\\n\"\n \"DS:%08lx ES:%08lx FS :%08lx GS :%08lx\",\n (unsigned long) uc->uc_mcontext->__ss.__eax,\n (unsigned long) uc->uc_mcontext->__ss.__ebx,\n (unsigned long) uc->uc_mcontext->__ss.__ecx,\n (unsigned long) uc->uc_mcontext->__ss.__edx,\n (unsigned long) uc->uc_mcontext->__ss.__edi,\n (unsigned long) uc->uc_mcontext->__ss.__esi,\n (unsigned long) uc->uc_mcontext->__ss.__ebp,\n (unsigned long) uc->uc_mcontext->__ss.__esp,\n (unsigned long) uc->uc_mcontext->__ss.__ss,\n (unsigned long) uc->uc_mcontext->__ss.__eflags,\n (unsigned long) uc->uc_mcontext->__ss.__eip,\n (unsigned long) uc->uc_mcontext->__ss.__cs,\n (unsigned long) uc->uc_mcontext->__ss.__ds,\n (unsigned long) uc->uc_mcontext->__ss.__es,\n (unsigned long) uc->uc_mcontext->__ss.__fs,\n (unsigned long) uc->uc_mcontext->__ss.__gs\n );\n logStackContent((void**)uc->uc_mcontext->__ss.__esp);\n #else\n /* OSX ARM64 */\n serverLog(LL_WARNING,\n \"\\n\"\n \"x0:%016lx x1:%016lx x2:%016lx x3:%016lx\\n\"\n \"x4:%016lx x5:%016lx x6:%016lx x7:%016lx\\n\"\n \"x8:%016lx x9:%016lx x10:%016lx x11:%016lx\\n\"\n \"x12:%016lx x13:%016lx x14:%016lx x15:%016lx\\n\"\n \"x16:%016lx x17:%016lx x18:%016lx x19:%016lx\\n\"\n \"x20:%016lx x21:%016lx x22:%016lx x23:%016lx\\n\"\n \"x24:%016lx x25:%016lx x26:%016lx x27:%016lx\\n\"\n \"x28:%016lx fp:%016lx lr:%016lx\\n\"\n \"sp:%016lx pc:%016lx cpsr:%08lx\\n\",\n (unsigned long) uc->uc_mcontext->__ss.__x[0],\n (unsigned long) uc->uc_mcontext->__ss.__x[1],\n (unsigned long) uc->uc_mcontext->__ss.__x[2],\n (unsigned long) uc->uc_mcontext->__ss.__x[3],\n (unsigned long) uc->uc_mcontext->__ss.__x[4],\n (unsigned long) uc->uc_mcontext->__ss.__x[5],\n (unsigned long) uc->uc_mcontext->__ss.__x[6],\n (unsigned long) uc->uc_mcontext->__ss.__x[7],\n (unsigned long) uc->uc_mcontext->__ss.__x[8],\n (unsigned long) uc->uc_mcontext->__ss.__x[9],\n (unsigned long) uc->uc_mcontext->__ss.__x[10],\n (unsigned long) uc->uc_mcontext->__ss.__x[11],\n (unsigned long) uc->uc_mcontext->__ss.__x[12],\n (unsigned long) uc->uc_mcontext->__ss.__x[13],\n (unsigned long) uc->uc_mcontext->__ss.__x[14],\n (unsigned long) uc->uc_mcontext->__ss.__x[15],\n (unsigned long) uc->uc_mcontext->__ss.__x[16],\n (unsigned long) uc->uc_mcontext->__ss.__x[17],\n (unsigned long) uc->uc_mcontext->__ss.__x[18],\n (unsigned long) uc->uc_mcontext->__ss.__x[19],\n (unsigned long) uc->uc_mcontext->__ss.__x[20],\n (unsigned long) uc->uc_mcontext->__ss.__x[21],\n (unsigned long) uc->uc_mcontext->__ss.__x[22],\n (unsigned long) uc->uc_mcontext->__ss.__x[23],\n (unsigned long) uc->uc_mcontext->__ss.__x[24],\n (unsigned long) uc->uc_mcontext->__ss.__x[25],\n (unsigned long) uc->uc_mcontext->__ss.__x[26],\n (unsigned long) uc->uc_mcontext->__ss.__x[27],\n (unsigned long) uc->uc_mcontext->__ss.__x[28],\n (unsigned long) arm_thread_state64_get_fp(uc->uc_mcontext->__ss),\n (unsigned long) arm_thread_state64_get_lr(uc->uc_mcontext->__ss),\n (unsigned long) arm_thread_state64_get_sp(uc->uc_mcontext->__ss),\n (unsigned long) arm_thread_state64_get_pc(uc->uc_mcontext->__ss),\n (unsigned long) uc->uc_mcontext->__ss.__cpsr\n );\n logStackContent((void**) arm_thread_state64_get_sp(uc->uc_mcontext->__ss));\n #endif\n/* Linux */\n#elif defined(__linux__)\n /* Linux x86 */\n #if defined(__i386__) || ((defined(__X86_64__) || defined(__x86_64__)) && defined(__ILP32__))\n serverLog(LL_WARNING,\n \"\\n\"\n \"EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\\n\"\n \"EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\\n\"\n \"SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\\n\"\n \"DS :%08lx ES :%08lx FS :%08lx GS:%08lx\",\n (unsigned long) uc->uc_mcontext.gregs[11],\n (unsigned long) uc->uc_mcontext.gregs[8],\n (unsigned long) uc->uc_mcontext.gregs[10],\n (unsigned long) uc->uc_mcontext.gregs[9],\n (unsigned long) uc->uc_mcontext.gregs[4],\n (unsigned long) uc->uc_mcontext.gregs[5],\n (unsigned long) uc->uc_mcontext.gregs[6],\n (unsigned long) uc->uc_mcontext.gregs[7],\n (unsigned long) uc->uc_mcontext.gregs[18],\n (unsigned long) uc->uc_mcontext.gregs[17],\n (unsigned long) uc->uc_mcontext.gregs[14],\n (unsigned long) uc->uc_mcontext.gregs[15],\n (unsigned long) uc->uc_mcontext.gregs[3],\n (unsigned long) uc->uc_mcontext.gregs[2],\n (unsigned long) uc->uc_mcontext.gregs[1],\n (unsigned long) uc->uc_mcontext.gregs[0]\n );\n logStackContent((void**)uc->uc_mcontext.gregs[7]);\n #elif defined(__X86_64__) || defined(__x86_64__)\n /* Linux AMD64 */\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCSGSFS:%016lx\",\n (unsigned long) uc->uc_mcontext.gregs[13],\n (unsigned long) uc->uc_mcontext.gregs[11],\n (unsigned long) uc->uc_mcontext.gregs[14],\n (unsigned long) uc->uc_mcontext.gregs[12],\n (unsigned long) uc->uc_mcontext.gregs[8],\n (unsigned long) uc->uc_mcontext.gregs[9],\n (unsigned long) uc->uc_mcontext.gregs[10],\n (unsigned long) uc->uc_mcontext.gregs[15],\n (unsigned long) uc->uc_mcontext.gregs[0],\n (unsigned long) uc->uc_mcontext.gregs[1],\n (unsigned long) uc->uc_mcontext.gregs[2],\n (unsigned long) uc->uc_mcontext.gregs[3],\n (unsigned long) uc->uc_mcontext.gregs[4],\n (unsigned long) uc->uc_mcontext.gregs[5],\n (unsigned long) uc->uc_mcontext.gregs[6],\n (unsigned long) uc->uc_mcontext.gregs[7],\n (unsigned long) uc->uc_mcontext.gregs[16],\n (unsigned long) uc->uc_mcontext.gregs[17],\n (unsigned long) uc->uc_mcontext.gregs[18]\n );\n logStackContent((void**)uc->uc_mcontext.gregs[15]);\n #elif defined(__aarch64__) /* Linux AArch64 */\n serverLog(LL_WARNING,\n\t \"\\n\"\n\t \"X18:%016lx X19:%016lx\\nX20:%016lx X21:%016lx\\n\"\n\t \"X22:%016lx X23:%016lx\\nX24:%016lx X25:%016lx\\n\"\n\t \"X26:%016lx X27:%016lx\\nX28:%016lx X29:%016lx\\n\"\n\t \"X30:%016lx\\n\"\n\t \"pc:%016lx sp:%016lx\\npstate:%016lx fault_address:%016lx\\n\",\n\t (unsigned long) uc->uc_mcontext.regs[18],\n\t (unsigned long) uc->uc_mcontext.regs[19],\n\t (unsigned long) uc->uc_mcontext.regs[20],\n\t (unsigned long) uc->uc_mcontext.regs[21],\n\t (unsigned long) uc->uc_mcontext.regs[22],\n\t (unsigned long) uc->uc_mcontext.regs[23],\n\t (unsigned long) uc->uc_mcontext.regs[24],\n\t (unsigned long) uc->uc_mcontext.regs[25],\n\t (unsigned long) uc->uc_mcontext.regs[26],\n\t (unsigned long) uc->uc_mcontext.regs[27],\n\t (unsigned long) uc->uc_mcontext.regs[28],\n\t (unsigned long) uc->uc_mcontext.regs[29],\n\t (unsigned long) uc->uc_mcontext.regs[30],\n\t (unsigned long) uc->uc_mcontext.pc,\n\t (unsigned long) uc->uc_mcontext.sp,\n\t (unsigned long) uc->uc_mcontext.pstate,\n\t (unsigned long) uc->uc_mcontext.fault_address\n\t\t );\n\t logStackContent((void**)uc->uc_mcontext.sp);\n #elif defined(__arm__) /* Linux ARM */\n serverLog(LL_WARNING,\n\t \"\\n\"\n\t \"R10:%016lx R9 :%016lx\\nR8 :%016lx R7 :%016lx\\n\"\n\t \"R6 :%016lx R5 :%016lx\\nR4 :%016lx R3 :%016lx\\n\"\n\t \"R2 :%016lx R1 :%016lx\\nR0 :%016lx EC :%016lx\\n\"\n\t \"fp: %016lx ip:%016lx\\n\"\n\t \"pc:%016lx sp:%016lx\\ncpsr:%016lx fault_address:%016lx\\n\",\n\t (unsigned long) uc->uc_mcontext.arm_r10,\n\t (unsigned long) uc->uc_mcontext.arm_r9,\n\t (unsigned long) uc->uc_mcontext.arm_r8,\n\t (unsigned long) uc->uc_mcontext.arm_r7,\n\t (unsigned long) uc->uc_mcontext.arm_r6,\n\t (unsigned long) uc->uc_mcontext.arm_r5,\n\t (unsigned long) uc->uc_mcontext.arm_r4,\n\t (unsigned long) uc->uc_mcontext.arm_r3,\n\t (unsigned long) uc->uc_mcontext.arm_r2,\n\t (unsigned long) uc->uc_mcontext.arm_r1,\n\t (unsigned long) uc->uc_mcontext.arm_r0,\n\t (unsigned long) uc->uc_mcontext.error_code,\n\t (unsigned long) uc->uc_mcontext.arm_fp,\n\t (unsigned long) uc->uc_mcontext.arm_ip,\n\t (unsigned long) uc->uc_mcontext.arm_pc,\n\t (unsigned long) uc->uc_mcontext.arm_sp,\n\t (unsigned long) uc->uc_mcontext.arm_cpsr,\n\t (unsigned long) uc->uc_mcontext.fault_address\n\t\t );\n\t logStackContent((void**)uc->uc_mcontext.arm_sp);\n #else\n\tNOT_SUPPORTED();\n #endif\n#elif defined(__FreeBSD__)\n #if defined(__x86_64__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCSGSFS:%016lx\",\n (unsigned long) uc->uc_mcontext.mc_rax,\n (unsigned long) uc->uc_mcontext.mc_rbx,\n (unsigned long) uc->uc_mcontext.mc_rcx,\n (unsigned long) uc->uc_mcontext.mc_rdx,\n (unsigned long) uc->uc_mcontext.mc_rdi,\n (unsigned long) uc->uc_mcontext.mc_rsi,\n (unsigned long) uc->uc_mcontext.mc_rbp,\n (unsigned long) uc->uc_mcontext.mc_rsp,\n (unsigned long) uc->uc_mcontext.mc_r8,\n (unsigned long) uc->uc_mcontext.mc_r9,\n (unsigned long) uc->uc_mcontext.mc_r10,\n (unsigned long) uc->uc_mcontext.mc_r11,\n (unsigned long) uc->uc_mcontext.mc_r12,\n (unsigned long) uc->uc_mcontext.mc_r13,\n (unsigned long) uc->uc_mcontext.mc_r14,\n (unsigned long) uc->uc_mcontext.mc_r15,\n (unsigned long) uc->uc_mcontext.mc_rip,\n (unsigned long) uc->uc_mcontext.mc_rflags,\n (unsigned long) uc->uc_mcontext.mc_cs\n );\n logStackContent((void**)uc->uc_mcontext.mc_rsp);\n #elif defined(__i386__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\\n\"\n \"EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\\n\"\n \"SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\\n\"\n \"DS :%08lx ES :%08lx FS :%08lx GS:%08lx\",\n (unsigned long) uc->uc_mcontext.mc_eax,\n (unsigned long) uc->uc_mcontext.mc_ebx,\n (unsigned long) uc->uc_mcontext.mc_ebx,\n (unsigned long) uc->uc_mcontext.mc_edx,\n (unsigned long) uc->uc_mcontext.mc_edi,\n (unsigned long) uc->uc_mcontext.mc_esi,\n (unsigned long) uc->uc_mcontext.mc_ebp,\n (unsigned long) uc->uc_mcontext.mc_esp,\n (unsigned long) uc->uc_mcontext.mc_ss,\n (unsigned long) uc->uc_mcontext.mc_eflags,\n (unsigned long) uc->uc_mcontext.mc_eip,\n (unsigned long) uc->uc_mcontext.mc_cs,\n (unsigned long) uc->uc_mcontext.mc_es,\n (unsigned long) uc->uc_mcontext.mc_fs,\n (unsigned long) uc->uc_mcontext.mc_gs\n );\n logStackContent((void**)uc->uc_mcontext.mc_esp);\n #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__OpenBSD__)\n #if defined(__x86_64__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCSGSFS:%016lx\",\n (unsigned long) uc->sc_rax,\n (unsigned long) uc->sc_rbx,\n (unsigned long) uc->sc_rcx,\n (unsigned long) uc->sc_rdx,\n (unsigned long) uc->sc_rdi,\n (unsigned long) uc->sc_rsi,\n (unsigned long) uc->sc_rbp,\n (unsigned long) uc->sc_rsp,\n (unsigned long) uc->sc_r8,\n (unsigned long) uc->sc_r9,\n (unsigned long) uc->sc_r10,\n (unsigned long) uc->sc_r11,\n (unsigned long) uc->sc_r12,\n (unsigned long) uc->sc_r13,\n (unsigned long) uc->sc_r14,\n (unsigned long) uc->sc_r15,\n (unsigned long) uc->sc_rip,\n (unsigned long) uc->sc_rflags,\n (unsigned long) uc->sc_cs\n );\n logStackContent((void**)uc->sc_rsp);\n #elif defined(__i386__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\\n\"\n \"EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\\n\"\n \"SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\\n\"\n \"DS :%08lx ES :%08lx FS :%08lx GS:%08lx\",\n (unsigned long) uc->sc_eax,\n (unsigned long) uc->sc_ebx,\n (unsigned long) uc->sc_ebx,\n (unsigned long) uc->sc_edx,\n (unsigned long) uc->sc_edi,\n (unsigned long) uc->sc_esi,\n (unsigned long) uc->sc_ebp,\n (unsigned long) uc->sc_esp,\n (unsigned long) uc->sc_ss,\n (unsigned long) uc->sc_eflags,\n (unsigned long) uc->sc_eip,\n (unsigned long) uc->sc_cs,\n (unsigned long) uc->sc_es,\n (unsigned long) uc->sc_fs,\n (unsigned long) uc->sc_gs\n );\n logStackContent((void**)uc->sc_esp);\n #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__NetBSD__)\n #if defined(__x86_64__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCSGSFS:%016lx\",\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RAX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RBX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RCX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RDX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RDI],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RSI],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RBP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RSP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R8],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R9],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R10],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R11],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R12],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R13],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R14],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R15],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RIP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RFLAGS],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_CS]\n );\n logStackContent((void**)uc->uc_mcontext.__gregs[_REG_RSP]);\n #elif defined(__i386__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\\n\"\n \"EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\\n\"\n \"SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\\n\"\n \"DS :%08lx ES :%08lx FS :%08lx GS:%08lx\",\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EAX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EBX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EDX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EDI],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_ESI],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EBP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_ESP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_SS],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EFLAGS],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EIP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_CS],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_ES],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_FS],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_GS]\n );\n #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__DragonFly__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCSGSFS:%016lx\",\n (unsigned long) uc->uc_mcontext.mc_rax,\n (unsigned long) uc->uc_mcontext.mc_rbx,\n (unsigned long) uc->uc_mcontext.mc_rcx,\n (unsigned long) uc->uc_mcontext.mc_rdx,\n (unsigned long) uc->uc_mcontext.mc_rdi,\n (unsigned long) uc->uc_mcontext.mc_rsi,\n (unsigned long) uc->uc_mcontext.mc_rbp,\n (unsigned long) uc->uc_mcontext.mc_rsp,\n (unsigned long) uc->uc_mcontext.mc_r8,\n (unsigned long) uc->uc_mcontext.mc_r9,\n (unsigned long) uc->uc_mcontext.mc_r10,\n (unsigned long) uc->uc_mcontext.mc_r11,\n (unsigned long) uc->uc_mcontext.mc_r12,\n (unsigned long) uc->uc_mcontext.mc_r13,\n (unsigned long) uc->uc_mcontext.mc_r14,\n (unsigned long) uc->uc_mcontext.mc_r15,\n (unsigned long) uc->uc_mcontext.mc_rip,\n (unsigned long) uc->uc_mcontext.mc_rflags,\n (unsigned long) uc->uc_mcontext.mc_cs\n );\n logStackContent((void**)uc->uc_mcontext.mc_rsp);\n#else\n NOT_SUPPORTED();\n#endif\n#undef NOT_SUPPORTED\n}", "#endif /* HAVE_BACKTRACE */", "/* Return a file descriptor to write directly to the Redis log with the\n * write(2) syscall, that can be used in critical sections of the code\n * where the rest of Redis can't be trusted (for example during the memory\n * test) or when an API call requires a raw fd.\n *\n * Close it with closeDirectLogFiledes(). */\nint openDirectLogFiledes(void) {\n int log_to_stdout = server.logfile[0] == '\\0';\n int fd = log_to_stdout ?\n STDOUT_FILENO :\n open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644);\n return fd;\n}", "/* Used to close what closeDirectLogFiledes() returns. */\nvoid closeDirectLogFiledes(int fd) {\n int log_to_stdout = server.logfile[0] == '\\0';\n if (!log_to_stdout) close(fd);\n}", "#ifdef HAVE_BACKTRACE", "/* Logs the stack trace using the backtrace() call. This function is designed\n * to be called from signal handlers safely.\n * The eip argument is optional (can take NULL).\n * The uplevel argument indicates how many of the calling functions to skip.\n */\nvoid logStackTrace(void *eip, int uplevel) {\n void *trace[100];\n int trace_size = 0, fd = openDirectLogFiledes();\n char *msg;\n uplevel++; /* skip this function */", " if (fd == -1) return; /* If we can't log there is anything to do. */", " /* Get the stack trace first! */\n trace_size = backtrace(trace, 100);", " msg = \"\\n------ STACK TRACE ------\\n\";\n if (write(fd,msg,strlen(msg)) == -1) {/* Avoid warning. */};", " if (eip) {\n /* Write EIP to the log file*/\n msg = \"EIP:\\n\";\n if (write(fd,msg,strlen(msg)) == -1) {/* Avoid warning. */};\n backtrace_symbols_fd(&eip, 1, fd);\n }", " /* Write symbols to log file */\n msg = \"\\nBacktrace:\\n\";\n if (write(fd,msg,strlen(msg)) == -1) {/* Avoid warning. */};\n backtrace_symbols_fd(trace+uplevel, trace_size-uplevel, fd);", " /* Cleanup */\n closeDirectLogFiledes(fd);\n}", "#endif /* HAVE_BACKTRACE */", "/* Log global server info */\nvoid logServerInfo(void) {\n sds infostring, clients;\n serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ INFO OUTPUT ------\\n\");\n int all = 0, everything = 0;\n robj *argv[1];\n argv[0] = createStringObject(\"all\", strlen(\"all\"));\n dict *section_dict = genInfoSectionDict(argv, 1, NULL, &all, &everything);\n infostring = genRedisInfoString(section_dict, all, everything);\n serverLogRaw(LL_WARNING|LL_RAW, infostring);\n serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ CLIENT LIST OUTPUT ------\\n\");\n clients = getAllClientsInfoString(-1);\n serverLogRaw(LL_WARNING|LL_RAW, clients);\n sdsfree(infostring);\n sdsfree(clients);\n releaseInfoSectionDict(section_dict);\n decrRefCount(argv[0]);\n}", "/* Log certain config values, which can be used for debuggin */\nvoid logConfigDebugInfo(void) {\n sds configstring;\n configstring = getConfigDebugInfo();\n serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ CONFIG DEBUG OUTPUT ------\\n\");\n serverLogRaw(LL_WARNING|LL_RAW, configstring);\n sdsfree(configstring);\n}", "/* Log modules info. Something we wanna do last since we fear it may crash. */\nvoid logModulesInfo(void) {\n serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ MODULES INFO OUTPUT ------\\n\");\n sds infostring = modulesCollectInfo(sdsempty(), NULL, 1, 0);\n serverLogRaw(LL_WARNING|LL_RAW, infostring);\n sdsfree(infostring);\n}", "/* Log information about the \"current\" client, that is, the client that is\n * currently being served by Redis. May be NULL if Redis is not serving a\n * client right now. */\nvoid logCurrentClient(void) {\n if (server.current_client == NULL) return;", " client *cc = server.current_client;\n sds client;\n int j;", " serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ CURRENT CLIENT INFO ------\\n\");\n client = catClientInfoString(sdsempty(),cc);\n serverLog(LL_WARNING|LL_RAW,\"%s\\n\", client);\n sdsfree(client);\n for (j = 0; j < cc->argc; j++) {\n robj *decoded;\n decoded = getDecodedObject(cc->argv[j]);\n sds repr = sdscatrepr(sdsempty(),decoded->ptr, min(sdslen(decoded->ptr), 128));\n serverLog(LL_WARNING|LL_RAW,\"argv[%d]: '%s'\\n\", j, (char*)repr);\n sdsfree(repr);\n decrRefCount(decoded);\n }\n /* Check if the first argument, usually a key, is found inside the\n * selected DB, and if so print info about the associated object. */\n if (cc->argc > 1) {\n robj *val, *key;\n dictEntry *de;", " key = getDecodedObject(cc->argv[1]);\n de = dictFind(cc->db->dict, key->ptr);\n if (de) {\n val = dictGetVal(de);\n serverLog(LL_WARNING,\"key '%s' found in DB containing the following object:\", (char*)key->ptr);\n serverLogObjectDebugInfo(val);\n }\n decrRefCount(key);\n }\n}", "#if defined(HAVE_PROC_MAPS)", "#define MEMTEST_MAX_REGIONS 128", "/* A non destructive memory test executed during segfault. */\nint memtest_test_linux_anonymous_maps(void) {\n FILE *fp;\n char line[1024];\n char logbuf[1024];\n size_t start_addr, end_addr, size;\n size_t start_vect[MEMTEST_MAX_REGIONS];\n size_t size_vect[MEMTEST_MAX_REGIONS];\n int regions = 0, j;", " int fd = openDirectLogFiledes();\n if (!fd) return 0;", " fp = fopen(\"/proc/self/maps\",\"r\");\n if (!fp) {\n closeDirectLogFiledes(fd);\n return 0;\n }\n while(fgets(line,sizeof(line),fp) != NULL) {\n char *start, *end, *p = line;", " start = p;\n p = strchr(p,'-');\n if (!p) continue;\n *p++ = '\\0';\n end = p;\n p = strchr(p,' ');\n if (!p) continue;\n *p++ = '\\0';\n if (strstr(p,\"stack\") ||\n strstr(p,\"vdso\") ||\n strstr(p,\"vsyscall\")) continue;\n if (!strstr(p,\"00:00\")) continue;\n if (!strstr(p,\"rw\")) continue;", " start_addr = strtoul(start,NULL,16);\n end_addr = strtoul(end,NULL,16);\n size = end_addr-start_addr;", " start_vect[regions] = start_addr;\n size_vect[regions] = size;\n snprintf(logbuf,sizeof(logbuf),\n \"*** Preparing to test memory region %lx (%lu bytes)\\n\",\n (unsigned long) start_vect[regions],\n (unsigned long) size_vect[regions]);\n if (write(fd,logbuf,strlen(logbuf)) == -1) { /* Nothing to do. */ }\n regions++;\n }", " int errors = 0;\n for (j = 0; j < regions; j++) {\n if (write(fd,\".\",1) == -1) { /* Nothing to do. */ }\n errors += memtest_preserving_test((void*)start_vect[j],size_vect[j],1);\n if (write(fd, errors ? \"E\" : \"O\",1) == -1) { /* Nothing to do. */ }\n }\n if (write(fd,\"\\n\",1) == -1) { /* Nothing to do. */ }", " /* NOTE: It is very important to close the file descriptor only now\n * because closing it before may result into unmapping of some memory\n * region that we are testing. */\n fclose(fp);\n closeDirectLogFiledes(fd);\n return errors;\n}\n#endif /* HAVE_PROC_MAPS */", "static void killMainThread(void) {\n int err;\n if (pthread_self() != server.main_thread_id && pthread_cancel(server.main_thread_id) == 0) {\n if ((err = pthread_join(server.main_thread_id,NULL)) != 0) {\n serverLog(LL_WARNING, \"main thread can not be joined: %s\", strerror(err));\n } else {\n serverLog(LL_WARNING, \"main thread terminated\");\n }\n }\n}", "/* Kill the running threads (other than current) in an unclean way. This function\n * should be used only when it's critical to stop the threads for some reason.\n * Currently Redis does this only on crash (for instance on SIGSEGV) in order\n * to perform a fast memory check without other threads messing with memory. */\nvoid killThreads(void) {\n killMainThread();\n bioKillThreads();\n killIOThreads();\n}", "void doFastMemoryTest(void) {\n#if defined(HAVE_PROC_MAPS)\n if (server.memcheck_enabled) {\n /* Test memory */\n serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ FAST MEMORY TEST ------\\n\");\n killThreads();\n if (memtest_test_linux_anonymous_maps()) {\n serverLogRaw(LL_WARNING|LL_RAW,\n \"!!! MEMORY ERROR DETECTED! Check your memory ASAP !!!\\n\");\n } else {\n serverLogRaw(LL_WARNING|LL_RAW,\n \"Fast memory test PASSED, however your memory can still be broken. Please run a memory test for several hours if possible.\\n\");\n }\n }\n#endif /* HAVE_PROC_MAPS */\n}", "/* Scans the (assumed) x86 code starting at addr, for a max of `len`\n * bytes, searching for E8 (callq) opcodes, and dumping the symbols\n * and the call offset if they appear to be valid. */\nvoid dumpX86Calls(void *addr, size_t len) {\n size_t j;\n unsigned char *p = addr;\n Dl_info info;\n /* Hash table to best-effort avoid printing the same symbol\n * multiple times. */\n unsigned long ht[256] = {0};", " if (len < 5) return;\n for (j = 0; j < len-4; j++) {\n if (p[j] != 0xE8) continue; /* Not an E8 CALL opcode. */\n unsigned long target = (unsigned long)addr+j+5;\n uint32_t tmp;\n memcpy(&tmp, p+j+1, sizeof(tmp));\n target += tmp;\n if (dladdr((void*)target, &info) != 0 && info.dli_sname != NULL) {\n if (ht[target&0xff] != target) {\n printf(\"Function at 0x%lx is %s\\n\",target,info.dli_sname);\n ht[target&0xff] = target;\n }\n j += 4; /* Skip the 32 bit immediate. */\n }\n }\n}", "void dumpCodeAroundEIP(void *eip) {\n Dl_info info;\n if (dladdr(eip, &info) != 0) {\n serverLog(LL_WARNING|LL_RAW,\n \"\\n------ DUMPING CODE AROUND EIP ------\\n\"\n \"Symbol: %s (base: %p)\\n\"\n \"Module: %s (base %p)\\n\"\n \"$ xxd -r -p /tmp/dump.hex /tmp/dump.bin\\n\"\n \"$ objdump --adjust-vma=%p -D -b binary -m i386:x86-64 /tmp/dump.bin\\n\"\n \"------\\n\",\n info.dli_sname, info.dli_saddr, info.dli_fname, info.dli_fbase,\n info.dli_saddr);\n size_t len = (long)eip - (long)info.dli_saddr;\n unsigned long sz = sysconf(_SC_PAGESIZE);\n if (len < 1<<13) { /* we don't have functions over 8k (verified) */\n /* Find the address of the next page, which is our \"safety\"\n * limit when dumping. Then try to dump just 128 bytes more\n * than EIP if there is room, or stop sooner. */\n void *base = (void *)info.dli_saddr;\n unsigned long next = ((unsigned long)eip + sz) & ~(sz-1);\n unsigned long end = (unsigned long)eip + 128;\n if (end > next) end = next;\n len = end - (unsigned long)base;\n serverLogHexDump(LL_WARNING, \"dump of function\",\n base, len);\n dumpX86Calls(base, len);\n }\n }\n}\n", "", "void sigsegvHandler(int sig, siginfo_t *info, void *secret) {\n UNUSED(secret);\n UNUSED(info);", " bugReportStart();\n serverLog(LL_WARNING,\n \"Redis %s crashed by signal: %d, si_code: %d\", REDIS_VERSION, sig, info->si_code);\n if (sig == SIGSEGV || sig == SIGBUS) {\n serverLog(LL_WARNING,\n \"Accessing address: %p\", (void*)info->si_addr);\n }\n if (info->si_code == SI_USER && info->si_pid != -1) {\n serverLog(LL_WARNING, \"Killed by PID: %ld, UID: %d\", (long) info->si_pid, info->si_uid);\n }", "#ifdef HAVE_BACKTRACE\n ucontext_t *uc = (ucontext_t*) secret;", " void *eip = getMcontextEip(uc);", " if (eip != NULL) {\n serverLog(LL_WARNING,\n \"Crashed running the instruction at: %p\", eip);\n }\n", " logStackTrace(getMcontextEip(uc), 1);", "\n logRegisters(uc);\n#endif", " printCrashReport();", "#ifdef HAVE_BACKTRACE\n if (eip != NULL)\n dumpCodeAroundEIP(eip);\n#endif", " bugReportEnd(1, sig);\n}", "void printCrashReport(void) {\n /* Log INFO and CLIENT LIST */\n logServerInfo();", " /* Log the current client */\n logCurrentClient();", " /* Log modules info. Something we wanna do last since we fear it may crash. */\n logModulesInfo();", " /* Log debug config information, which are some values\n * which may be useful for debugging crashes. */\n logConfigDebugInfo();", " /* Run memory test in case the crash was triggered by memory corruption. */\n doFastMemoryTest();\n}", "void bugReportEnd(int killViaSignal, int sig) {\n struct sigaction act;", " serverLogRaw(LL_WARNING|LL_RAW,\n\"\\n=== REDIS BUG REPORT END. Make sure to include from START to END. ===\\n\\n\"\n\" Please report the crash by opening an issue on github:\\n\\n\"\n\" http://github.com/redis/redis/issues\\n\\n\"\n\" If a Redis module was involved, please open in the module's repo instead.\\n\\n\"\n\" Suspect RAM error? Use redis-server --test-memory to verify it.\\n\\n\"\n\" Some other issues could be detected by redis-server --check-system\\n\"\n);", " /* free(messages); Don't call free() with possibly corrupted memory. */\n if (server.daemonize && server.supervised == 0 && server.pidfile) unlink(server.pidfile);", " if (!killViaSignal) {\n /* To avoid issues with valgrind, we may wanna exit rahter than generate a signal */\n if (server.use_exit_on_panic) {\n /* Using _exit to bypass false leak reports by gcc ASAN */\n fflush(stdout);\n _exit(1);\n }\n abort();\n }", " /* Make sure we exit with the right signal at the end. So for instance\n * the core will be dumped if enabled. */\n sigemptyset (&act.sa_mask);\n act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;\n act.sa_handler = SIG_DFL;\n sigaction (sig, &act, NULL);\n kill(getpid(),sig);\n}", "/* ==================== Logging functions for debugging ===================== */", "void serverLogHexDump(int level, char *descr, void *value, size_t len) {\n char buf[65], *b;\n unsigned char *v = value;\n char charset[] = \"0123456789abcdef\";", " serverLog(level,\"%s (hexdump of %zu bytes):\", descr, len);\n b = buf;\n while(len) {\n b[0] = charset[(*v)>>4];\n b[1] = charset[(*v)&0xf];\n b[2] = '\\0';\n b += 2;\n len--;\n v++;\n if (b-buf == 64 || len == 0) {\n serverLogRaw(level|LL_RAW,buf);\n b = buf;\n }\n }\n serverLogRaw(level|LL_RAW,\"\\n\");\n}", "/* =========================== Software Watchdog ============================ */\n#include <sys/time.h>", "void watchdogSignalHandler(int sig, siginfo_t *info, void *secret) {\n#ifdef HAVE_BACKTRACE\n ucontext_t *uc = (ucontext_t*) secret;\n#else\n (void)secret;\n#endif\n UNUSED(info);\n UNUSED(sig);", " serverLogFromHandler(LL_WARNING,\"\\n--- WATCHDOG TIMER EXPIRED ---\");\n#ifdef HAVE_BACKTRACE", " logStackTrace(getMcontextEip(uc), 1);", "#else\n serverLogFromHandler(LL_WARNING,\"Sorry: no support for backtrace().\");\n#endif\n serverLogFromHandler(LL_WARNING,\"--------\\n\");\n}", "/* Schedule a SIGALRM delivery after the specified period in milliseconds.\n * If a timer is already scheduled, this function will re-schedule it to the\n * specified time. If period is 0 the current timer is disabled. */\nvoid watchdogScheduleSignal(int period) {\n struct itimerval it;", " /* Will stop the timer if period is 0. */\n it.it_value.tv_sec = period/1000;\n it.it_value.tv_usec = (period%1000)*1000;\n /* Don't automatically restart. */\n it.it_interval.tv_sec = 0;\n it.it_interval.tv_usec = 0;\n setitimer(ITIMER_REAL, &it, NULL);\n}\nvoid applyWatchdogPeriod() {\n struct sigaction act;", " /* Disable watchdog when period is 0 */\n if (server.watchdog_period == 0) {\n watchdogScheduleSignal(0); /* Stop the current timer. */", " /* Set the signal handler to SIG_IGN, this will also remove pending\n * signals from the queue. */\n sigemptyset(&act.sa_mask);\n act.sa_flags = 0;\n act.sa_handler = SIG_IGN;\n sigaction(SIGALRM, &act, NULL);\n } else {\n /* Setup the signal handler. */\n sigemptyset(&act.sa_mask);\n act.sa_flags = SA_SIGINFO;\n act.sa_sigaction = watchdogSignalHandler;\n sigaction(SIGALRM, &act, NULL);", " /* If the configured period is smaller than twice the timer period, it is\n * too short for the software watchdog to work reliably. Fix it now\n * if needed. */\n int min_period = (1000/server.hz)*2;\n if (server.watchdog_period < min_period) server.watchdog_period = min_period;\n watchdogScheduleSignal(server.watchdog_period); /* Adjust the current timer. */\n }\n}", "/* Positive input is sleep time in microseconds. Negative input is fractions\n * of microseconds, i.e. -10 means 100 nanoseconds. */\nvoid debugDelay(int usec) {\n /* Since even the shortest sleep results in context switch and system call,\n * the way we achieve short sleeps is by statistically sleeping less often. */\n if (usec < 0) usec = (rand() % -usec) == 0 ? 1: 0;\n if (usec) usleep(usec);\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, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 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, 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, 0, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [2083], "buggy_code_start_loc": [1126], "filenames": ["src/debug.c"], "fixing_code_end_loc": [2119], "fixing_code_start_loc": [1126], "message": "** DISPUTED ** A vulnerability, which was classified as problematic, was found in Redis. Affected is the function sigsegvHandler of the file debug.c of the component Crash Report. The manipulation leads to denial of service. The real existence of this vulnerability is still doubted at the moment. The name of the patch is 0bf90d944313919eb8e63d3588bf63a367f020a3. It is recommended to apply a patch to fix this issue. VDB-211962 is the identifier assigned to this vulnerability. NOTE: The vendor claims that this is not a DoS because it applies to the crash logging mechanism which is triggered after a crash has occurred.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redis:redis:*:*:*:*:*:*:*:*", "matchCriteriaId": "1A9E9EB4-7E92-4672-B9C7-35C22F5D6B50", "versionEndExcluding": "2022-09-29", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "** DISPUTED ** A vulnerability, which was classified as problematic, was found in Redis. Affected is the function sigsegvHandler of the file debug.c of the component Crash Report. The manipulation leads to denial of service. The real existence of this vulnerability is still doubted at the moment. The name of the patch is 0bf90d944313919eb8e63d3588bf63a367f020a3. It is recommended to apply a patch to fix this issue. VDB-211962 is the identifier assigned to this vulnerability. NOTE: The vendor claims that this is not a DoS because it applies to the crash logging mechanism which is triggered after a crash has occurred."}, {"lang": "es", "value": "** EN DISPUTA ** Se ha encontrado una vulnerabilidad, clasificada como problem\u00e1tica, en Redis. La funci\u00f3n afectada es sigsegvHandler del archivo debug.c del componente Crash Report. La manipulaci\u00f3n conlleva a una denegaci\u00f3n de servicio. El nombre del parche es 0bf90d944313919eb8e63d3588bf63a367f020a3. Es recomendado aplicar un parche para corregir este problema. VDB-211962 es el identificador asignado a esta vulnerabilidad. NOTA: El proveedor afirma que esto no es un DoS porque se aplica al mecanismo de registro de fallos que se activa despu\u00e9s de que se haya producido un fallo"}], "evaluatorComment": null, "id": "CVE-2022-3647", "lastModified": "2022-11-29T16:22:24.607", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 3.3, "baseSeverity": "LOW", "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:L", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.1, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:A/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}]}, "published": "2022-10-21T18:15:10.183", "references": [{"source": "cna@vuldb.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/redis/redis/commit/0bf90d944313919eb8e63d3588bf63a367f020a3"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.211962"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-404"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/redis/redis/commit/0bf90d944313919eb8e63d3588bf63a367f020a3"}, "type": "CWE-404"}
239
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2009-2020, Salvatore Sanfilippo <antirez at gmail dot com>\n * Copyright (c) 2020, Redis Labs, Inc\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * Neither the name of Redis nor the names of its contributors may be used\n * to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */", "#include \"server.h\"\n#include \"util.h\"\n#include \"sha1.h\" /* SHA1 is used for DEBUG DIGEST */\n#include \"crc64.h\"\n#include \"bio.h\"\n#include \"quicklist.h\"", "#include <arpa/inet.h>\n#include <signal.h>\n#include <dlfcn.h>\n#include <fcntl.h>\n#include <sys/mman.h>\n#include <unistd.h>", "#ifdef HAVE_BACKTRACE\n#include <execinfo.h>\n#ifndef __OpenBSD__\n#include <ucontext.h>\n#else\ntypedef ucontext_t sigcontext_t;\n#endif\n#endif /* HAVE_BACKTRACE */", "#ifdef __CYGWIN__\n#ifndef SA_ONSTACK\n#define SA_ONSTACK 0x08000000\n#endif\n#endif", "#if defined(__APPLE__) && defined(__arm64__)\n#include <mach/mach.h>\n#endif", "/* Globals */\nstatic int bug_report_start = 0; /* True if bug report header was already logged. */\nstatic pthread_mutex_t bug_report_start_mutex = PTHREAD_MUTEX_INITIALIZER;", "/* Forward declarations */\nvoid bugReportStart(void);\nvoid printCrashReport(void);\nvoid bugReportEnd(int killViaSignal, int sig);\nvoid logStackTrace(void *eip, int uplevel);", "/* ================================= Debugging ============================== */", "/* Compute the sha1 of string at 's' with 'len' bytes long.\n * The SHA1 is then xored against the string pointed by digest.\n * Since xor is commutative, this operation is used in order to\n * \"add\" digests relative to unordered elements.\n *\n * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */\nvoid xorDigest(unsigned char *digest, const void *ptr, size_t len) {\n SHA1_CTX ctx;\n unsigned char hash[20];\n int j;", " SHA1Init(&ctx);\n SHA1Update(&ctx,ptr,len);\n SHA1Final(hash,&ctx);", " for (j = 0; j < 20; j++)\n digest[j] ^= hash[j];\n}", "void xorStringObjectDigest(unsigned char *digest, robj *o) {\n o = getDecodedObject(o);\n xorDigest(digest,o->ptr,sdslen(o->ptr));\n decrRefCount(o);\n}", "/* This function instead of just computing the SHA1 and xoring it\n * against digest, also perform the digest of \"digest\" itself and\n * replace the old value with the new one.\n *\n * So the final digest will be:\n *\n * digest = SHA1(digest xor SHA1(data))\n *\n * This function is used every time we want to preserve the order so\n * that digest(a,b,c,d) will be different than digest(b,c,d,a)\n *\n * Also note that mixdigest(\"foo\") followed by mixdigest(\"bar\")\n * will lead to a different digest compared to \"fo\", \"obar\".\n */\nvoid mixDigest(unsigned char *digest, const void *ptr, size_t len) {\n SHA1_CTX ctx;", " xorDigest(digest,ptr,len);\n SHA1Init(&ctx);\n SHA1Update(&ctx,digest,20);\n SHA1Final(digest,&ctx);\n}", "void mixStringObjectDigest(unsigned char *digest, robj *o) {\n o = getDecodedObject(o);\n mixDigest(digest,o->ptr,sdslen(o->ptr));\n decrRefCount(o);\n}", "/* This function computes the digest of a data structure stored in the\n * object 'o'. It is the core of the DEBUG DIGEST command: when taking the\n * digest of a whole dataset, we take the digest of the key and the value\n * pair, and xor all those together.\n *\n * Note that this function does not reset the initial 'digest' passed, it\n * will continue mixing this object digest to anything that was already\n * present. */\nvoid xorObjectDigest(redisDb *db, robj *keyobj, unsigned char *digest, robj *o) {\n uint32_t aux = htonl(o->type);\n mixDigest(digest,&aux,sizeof(aux));\n long long expiretime = getExpire(db,keyobj);\n char buf[128];", " /* Save the key and associated value */\n if (o->type == OBJ_STRING) {\n mixStringObjectDigest(digest,o);\n } else if (o->type == OBJ_LIST) {\n listTypeIterator *li = listTypeInitIterator(o,0,LIST_TAIL);\n listTypeEntry entry;\n while(listTypeNext(li,&entry)) {\n robj *eleobj = listTypeGet(&entry);\n mixStringObjectDigest(digest,eleobj);\n decrRefCount(eleobj);\n }\n listTypeReleaseIterator(li);\n } else if (o->type == OBJ_SET) {\n setTypeIterator *si = setTypeInitIterator(o);\n sds sdsele;\n while((sdsele = setTypeNextObject(si)) != NULL) {\n xorDigest(digest,sdsele,sdslen(sdsele));\n sdsfree(sdsele);\n }\n setTypeReleaseIterator(si);\n } else if (o->type == OBJ_ZSET) {\n unsigned char eledigest[20];", " if (o->encoding == OBJ_ENCODING_LISTPACK) {\n unsigned char *zl = o->ptr;\n unsigned char *eptr, *sptr;\n unsigned char *vstr;\n unsigned int vlen;\n long long vll;\n double score;", " eptr = lpSeek(zl,0);\n serverAssert(eptr != NULL);\n sptr = lpNext(zl,eptr);\n serverAssert(sptr != NULL);", " while (eptr != NULL) {\n vstr = lpGetValue(eptr,&vlen,&vll);\n score = zzlGetScore(sptr);", " memset(eledigest,0,20);\n if (vstr != NULL) {\n mixDigest(eledigest,vstr,vlen);\n } else {\n ll2string(buf,sizeof(buf),vll);\n mixDigest(eledigest,buf,strlen(buf));\n }", " snprintf(buf,sizeof(buf),\"%.17g\",score);\n mixDigest(eledigest,buf,strlen(buf));\n xorDigest(digest,eledigest,20);\n zzlNext(zl,&eptr,&sptr);\n }\n } else if (o->encoding == OBJ_ENCODING_SKIPLIST) {\n zset *zs = o->ptr;\n dictIterator *di = dictGetIterator(zs->dict);\n dictEntry *de;", " while((de = dictNext(di)) != NULL) {\n sds sdsele = dictGetKey(de);\n double *score = dictGetVal(de);", " snprintf(buf,sizeof(buf),\"%.17g\",*score);\n memset(eledigest,0,20);\n mixDigest(eledigest,sdsele,sdslen(sdsele));\n mixDigest(eledigest,buf,strlen(buf));\n xorDigest(digest,eledigest,20);\n }\n dictReleaseIterator(di);\n } else {\n serverPanic(\"Unknown sorted set encoding\");\n }\n } else if (o->type == OBJ_HASH) {\n hashTypeIterator *hi = hashTypeInitIterator(o);\n while (hashTypeNext(hi) != C_ERR) {\n unsigned char eledigest[20];\n sds sdsele;", " memset(eledigest,0,20);\n sdsele = hashTypeCurrentObjectNewSds(hi,OBJ_HASH_KEY);\n mixDigest(eledigest,sdsele,sdslen(sdsele));\n sdsfree(sdsele);\n sdsele = hashTypeCurrentObjectNewSds(hi,OBJ_HASH_VALUE);\n mixDigest(eledigest,sdsele,sdslen(sdsele));\n sdsfree(sdsele);\n xorDigest(digest,eledigest,20);\n }\n hashTypeReleaseIterator(hi);\n } else if (o->type == OBJ_STREAM) {\n streamIterator si;\n streamIteratorStart(&si,o->ptr,NULL,NULL,0);\n streamID id;\n int64_t numfields;", " while(streamIteratorGetID(&si,&id,&numfields)) {\n sds itemid = sdscatfmt(sdsempty(),\"%U.%U\",id.ms,id.seq);\n mixDigest(digest,itemid,sdslen(itemid));\n sdsfree(itemid);", " while(numfields--) {\n unsigned char *field, *value;\n int64_t field_len, value_len;\n streamIteratorGetField(&si,&field,&value,\n &field_len,&value_len);\n mixDigest(digest,field,field_len);\n mixDigest(digest,value,value_len);\n }\n }\n streamIteratorStop(&si);\n } else if (o->type == OBJ_MODULE) {\n RedisModuleDigest md = {{0},{0},keyobj,db->id};\n moduleValue *mv = o->ptr;\n moduleType *mt = mv->type;\n moduleInitDigestContext(md);\n if (mt->digest) {\n mt->digest(&md,mv->value);\n xorDigest(digest,md.x,sizeof(md.x));\n }\n } else {\n serverPanic(\"Unknown object type\");\n }\n /* If the key has an expire, add it to the mix */\n if (expiretime != -1) xorDigest(digest,\"!!expire!!\",10);\n}", "/* Compute the dataset digest. Since keys, sets elements, hashes elements\n * are not ordered, we use a trick: every aggregate digest is the xor\n * of the digests of their elements. This way the order will not change\n * the result. For list instead we use a feedback entering the output digest\n * as input in order to ensure that a different ordered list will result in\n * a different digest. */\nvoid computeDatasetDigest(unsigned char *final) {\n unsigned char digest[20];\n dictIterator *di = NULL;\n dictEntry *de;\n int j;\n uint32_t aux;", " memset(final,0,20); /* Start with a clean result */", " for (j = 0; j < server.dbnum; j++) {\n redisDb *db = server.db+j;", " if (dictSize(db->dict) == 0) continue;\n di = dictGetSafeIterator(db->dict);", " /* hash the DB id, so the same dataset moved in a different\n * DB will lead to a different digest */\n aux = htonl(j);\n mixDigest(final,&aux,sizeof(aux));", " /* Iterate this DB writing every entry */\n while((de = dictNext(di)) != NULL) {\n sds key;\n robj *keyobj, *o;", " memset(digest,0,20); /* This key-val digest */\n key = dictGetKey(de);\n keyobj = createStringObject(key,sdslen(key));", " mixDigest(digest,key,sdslen(key));", " o = dictGetVal(de);\n xorObjectDigest(db,keyobj,digest,o);", " /* We can finally xor the key-val digest to the final digest */\n xorDigest(final,digest,20);\n decrRefCount(keyobj);\n }\n dictReleaseIterator(di);\n }\n}", "#ifdef USE_JEMALLOC\nvoid mallctl_int(client *c, robj **argv, int argc) {\n int ret;\n /* start with the biggest size (int64), and if that fails, try smaller sizes (int32, bool) */\n int64_t old = 0, val;\n if (argc > 1) {\n long long ll;\n if (getLongLongFromObjectOrReply(c, argv[1], &ll, NULL) != C_OK)\n return;\n val = ll;\n }\n size_t sz = sizeof(old);\n while (sz > 0) {\n if ((ret=je_mallctl(argv[0]->ptr, &old, &sz, argc > 1? &val: NULL, argc > 1?sz: 0))) {\n if (ret == EPERM && argc > 1) {\n /* if this option is write only, try just writing to it. */\n if (!(ret=je_mallctl(argv[0]->ptr, NULL, 0, &val, sz))) {\n addReply(c, shared.ok);\n return;\n }\n }\n if (ret==EINVAL) {\n /* size might be wrong, try a smaller one */\n sz /= 2;\n#if BYTE_ORDER == BIG_ENDIAN\n val <<= 8*sz;\n#endif\n continue;\n }\n addReplyErrorFormat(c,\"%s\", strerror(ret));\n return;\n } else {\n#if BYTE_ORDER == BIG_ENDIAN\n old >>= 64 - 8*sz;\n#endif\n addReplyLongLong(c, old);\n return;\n }\n }\n addReplyErrorFormat(c,\"%s\", strerror(EINVAL));\n}", "void mallctl_string(client *c, robj **argv, int argc) {\n int rret, wret;\n char *old;\n size_t sz = sizeof(old);\n /* for strings, it seems we need to first get the old value, before overriding it. */\n if ((rret=je_mallctl(argv[0]->ptr, &old, &sz, NULL, 0))) {\n /* return error unless this option is write only. */\n if (!(rret == EPERM && argc > 1)) {\n addReplyErrorFormat(c,\"%s\", strerror(rret));\n return;\n }\n }\n if(argc > 1) {\n char *val = argv[1]->ptr;\n char **valref = &val;\n if ((!strcmp(val,\"VOID\")))\n valref = NULL, sz = 0;\n wret = je_mallctl(argv[0]->ptr, NULL, 0, valref, sz);\n }\n if (!rret)\n addReplyBulkCString(c, old);\n else if (wret)\n addReplyErrorFormat(c,\"%s\", strerror(wret));\n else\n addReply(c, shared.ok);\n}\n#endif", "void debugCommand(client *c) {\n if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,\"help\")) {\n const char *help[] = {\n\"AOF-FLUSH-SLEEP <microsec>\",\n\" Server will sleep before flushing the AOF, this is used for testing.\",\n\"ASSERT\",\n\" Crash by assertion failed.\",\n\"CHANGE-REPL-ID\",\n\" Change the replication IDs of the instance.\",\n\" Dangerous: should be used only for testing the replication subsystem.\",\n\"CONFIG-REWRITE-FORCE-ALL\",\n\" Like CONFIG REWRITE but writes all configuration options, including\",\n\" keywords not listed in original configuration file or default values.\",\n\"CRASH-AND-RECOVER [<milliseconds>]\",\n\" Hard crash and restart after a <milliseconds> delay (default 0).\",\n\"DIGEST\",\n\" Output a hex signature representing the current DB content.\",\n\"DIGEST-VALUE <key> [<key> ...]\",\n\" Output a hex signature of the values of all the specified keys.\",\n\"ERROR <string>\",\n\" Return a Redis protocol error with <string> as message. Useful for clients\",\n\" unit tests to simulate Redis errors.\",\n\"LEAK <string>\",\n\" Create a memory leak of the input string.\",\n\"LOG <message>\",\n\" Write <message> to the server log.\",\n\"HTSTATS <dbid>\",\n\" Return hash table statistics of the specified Redis database.\",\n\"HTSTATS-KEY <key>\",\n\" Like HTSTATS but for the hash table stored at <key>'s value.\",\n\"LOADAOF\",\n\" Flush the AOF buffers on disk and reload the AOF in memory.\",\n\"REPLICATE <string>\",\n\" Replicates the provided string to replicas, allowing data divergence.\",\n#ifdef USE_JEMALLOC\n\"MALLCTL <key> [<val>]\",\n\" Get or set a malloc tuning integer.\",\n\"MALLCTL-STR <key> [<val>]\",\n\" Get or set a malloc tuning string.\",\n#endif\n\"OBJECT <key>\",\n\" Show low level info about `key` and associated value.\",\n\"DROP-CLUSTER-PACKET-FILTER <packet-type>\",\n\" Drop all packets that match the filtered type. Set to -1 allow all packets.\",\n\"OOM\",\n\" Crash the server simulating an out-of-memory error.\",\n\"PANIC\",\n\" Crash the server simulating a panic.\",\n\"POPULATE <count> [<prefix>] [<size>]\",\n\" Create <count> string keys named key:<num>. If <prefix> is specified then\",\n\" it is used instead of the 'key' prefix. These are not propagated to\",\n\" replicas. Cluster slots are not respected so keys not belonging to the\",\n\" current node can be created in cluster mode.\",\n\"PROTOCOL <type>\",\n\" Reply with a test value of the specified type. <type> can be: string,\",\n\" integer, double, bignum, null, array, set, map, attrib, push, verbatim,\",\n\" true, false.\",\n\"RELOAD [option ...]\",\n\" Save the RDB on disk and reload it back to memory. Valid <option> values:\",\n\" * MERGE: conflicting keys will be loaded from RDB.\",\n\" * NOFLUSH: the existing database will not be removed before load, but\",\n\" conflicting keys will generate an exception and kill the server.\",\n\" * NOSAVE: the database will be loaded from an existing RDB file.\",\n\" Examples:\",\n\" * DEBUG RELOAD: verify that the server is able to persist, flush and reload\",\n\" the database.\",\n\" * DEBUG RELOAD NOSAVE: replace the current database with the contents of an\",\n\" existing RDB file.\",\n\" * DEBUG RELOAD NOSAVE NOFLUSH MERGE: add the contents of an existing RDB\",\n\" file to the database.\",\n\"RESTART [<milliseconds>]\",\n\" Graceful restart: save config, db, restart after a <milliseconds> delay (default 0).\",\n\"SDSLEN <key>\",\n\" Show low level SDS string info representing `key` and value.\",\n\"SEGFAULT\",\n\" Crash the server with sigsegv.\",\n\"SET-ACTIVE-EXPIRE <0|1>\",\n\" Setting it to 0 disables expiring keys in background when they are not\",\n\" accessed (otherwise the Redis behavior). Setting it to 1 reenables back the\",\n\" default.\",\n\"QUICKLIST-PACKED-THRESHOLD <size>\",\n\" Sets the threshold for elements to be inserted as plain vs packed nodes\",\n\" Default value is 1GB, allows values up to 4GB. Setting to 0 restores to default.\",\n\"SET-SKIP-CHECKSUM-VALIDATION <0|1>\",\n\" Enables or disables checksum checks for RDB files and RESTORE's payload.\",\n\"SLEEP <seconds>\",\n\" Stop the server for <seconds>. Decimals allowed.\",\n\"STRINGMATCH-TEST\",\n\" Run a fuzz tester against the stringmatchlen() function.\",\n\"STRUCTSIZE\",\n\" Return the size of different Redis core C structures.\",\n\"LISTPACK <key>\",\n\" Show low level info about the listpack encoding of <key>.\",\n\"QUICKLIST <key> [<0|1>]\",\n\" Show low level info about the quicklist encoding of <key>.\",\n\" The optional argument (0 by default) sets the level of detail\",\n\"CLIENT-EVICTION\",\n\" Show low level client eviction pools info (maxmemory-clients).\",\n\"PAUSE-CRON <0|1>\",\n\" Stop periodic cron job processing.\",\n\"REPLYBUFFER PEAK-RESET-TIME <NEVER||RESET|time>\",\n\" Sets the time (in milliseconds) to wait between client reply buffer peak resets.\",\n\" In case NEVER is provided the last observed peak will never be reset\",\n\" In case RESET is provided the peak reset time will be restored to the default value\",\n\"REPLYBUFFER RESIZING <0|1>\",\n\" Enable or disable the reply buffer resize cron job\",\nNULL\n };\n addReplyHelp(c, help);\n } else if (!strcasecmp(c->argv[1]->ptr,\"segfault\")) {\n /* Compiler gives warnings about writing to a random address\n * e.g \"*((char*)-1) = 'x';\". As a workaround, we map a read-only area\n * and try to write there to trigger segmentation fault. */\n char* p = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANON, -1, 0);\n *p = 'x';\n } else if (!strcasecmp(c->argv[1]->ptr,\"panic\")) {\n serverPanic(\"DEBUG PANIC called at Unix time %lld\", (long long)time(NULL));\n } else if (!strcasecmp(c->argv[1]->ptr,\"restart\") ||\n !strcasecmp(c->argv[1]->ptr,\"crash-and-recover\"))\n {\n long long delay = 0;\n if (c->argc >= 3) {\n if (getLongLongFromObjectOrReply(c, c->argv[2], &delay, NULL)\n != C_OK) return;\n if (delay < 0) delay = 0;\n }\n int flags = !strcasecmp(c->argv[1]->ptr,\"restart\") ?\n (RESTART_SERVER_GRACEFULLY|RESTART_SERVER_CONFIG_REWRITE) :\n RESTART_SERVER_NONE;\n restartServer(flags,delay);\n addReplyError(c,\"failed to restart the server. Check server logs.\");\n } else if (!strcasecmp(c->argv[1]->ptr,\"oom\")) {\n void *ptr = zmalloc(ULONG_MAX); /* Should trigger an out of memory. */\n zfree(ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"assert\")) {\n serverAssertWithInfo(c,c->argv[0],1 == 2);\n } else if (!strcasecmp(c->argv[1]->ptr,\"log\") && c->argc == 3) {\n serverLog(LL_WARNING, \"DEBUG LOG: %s\", (char*)c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"leak\") && c->argc == 3) {\n sdsdup(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"reload\")) {\n int flush = 1, save = 1;\n int flags = RDBFLAGS_NONE;", " /* Parse the additional options that modify the RELOAD\n * behavior. */\n for (int j = 2; j < c->argc; j++) {\n char *opt = c->argv[j]->ptr;\n if (!strcasecmp(opt,\"MERGE\")) {\n flags |= RDBFLAGS_ALLOW_DUP;\n } else if (!strcasecmp(opt,\"NOFLUSH\")) {\n flush = 0;\n } else if (!strcasecmp(opt,\"NOSAVE\")) {\n save = 0;\n } else {\n addReplyError(c,\"DEBUG RELOAD only supports the \"\n \"MERGE, NOFLUSH and NOSAVE options.\");\n return;\n }\n }", " /* The default behavior is to save the RDB file before loading\n * it back. */\n if (save) {\n rdbSaveInfo rsi, *rsiptr;\n rsiptr = rdbPopulateSaveInfo(&rsi);\n if (rdbSave(SLAVE_REQ_NONE,server.rdb_filename,rsiptr) != C_OK) {\n addReplyErrorObject(c,shared.err);\n return;\n }\n }", " /* The default behavior is to remove the current dataset from\n * memory before loading the RDB file, however when MERGE is\n * used together with NOFLUSH, we are able to merge two datasets. */\n if (flush) emptyData(-1,EMPTYDB_NO_FLAGS,NULL);", " protectClient(c);\n int ret = rdbLoad(server.rdb_filename,NULL,flags);\n unprotectClient(c);\n if (ret != RDB_OK) {\n addReplyError(c,\"Error trying to load the RDB dump, check server logs.\");\n return;\n }\n serverLog(LL_WARNING,\"DB reloaded by DEBUG RELOAD\");\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"loadaof\")) {\n if (server.aof_state != AOF_OFF) flushAppendOnlyFile(1);\n emptyData(-1,EMPTYDB_NO_FLAGS,NULL);\n protectClient(c);\n if (server.aof_manifest) aofManifestFree(server.aof_manifest);\n aofLoadManifestFromDisk();\n aofDelHistoryFiles();\n int ret = loadAppendOnlyFiles(server.aof_manifest);\n if (ret != AOF_OK && ret != AOF_EMPTY)\n exit(1);\n unprotectClient(c);\n server.dirty = 0; /* Prevent AOF / replication */\n serverLog(LL_WARNING,\"Append Only File loaded by DEBUG LOADAOF\");\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"drop-cluster-packet-filter\") && c->argc == 3) {\n long packet_type;\n if (getLongFromObjectOrReply(c, c->argv[2], &packet_type, NULL) != C_OK)\n return;\n server.cluster_drop_packet_filter = packet_type;\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"object\") && c->argc == 3) {\n dictEntry *de;\n robj *val;\n char *strenc;", " if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) {\n addReplyErrorObject(c,shared.nokeyerr);\n return;\n }\n val = dictGetVal(de);\n strenc = strEncoding(val->encoding);", " char extra[138] = {0};\n if (val->encoding == OBJ_ENCODING_QUICKLIST) {\n char *nextra = extra;\n int remaining = sizeof(extra);\n quicklist *ql = val->ptr;\n /* Add number of quicklist nodes */\n int used = snprintf(nextra, remaining, \" ql_nodes:%lu\", ql->len);\n nextra += used;\n remaining -= used;\n /* Add average quicklist fill factor */\n double avg = (double)ql->count/ql->len;\n used = snprintf(nextra, remaining, \" ql_avg_node:%.2f\", avg);\n nextra += used;\n remaining -= used;\n /* Add quicklist fill level / max listpack size */\n used = snprintf(nextra, remaining, \" ql_listpack_max:%d\", ql->fill);\n nextra += used;\n remaining -= used;\n /* Add isCompressed? */\n int compressed = ql->compress != 0;\n used = snprintf(nextra, remaining, \" ql_compressed:%d\", compressed);\n nextra += used;\n remaining -= used;\n /* Add total uncompressed size */\n unsigned long sz = 0;\n for (quicklistNode *node = ql->head; node; node = node->next) {\n sz += node->sz;\n }\n used = snprintf(nextra, remaining, \" ql_uncompressed_size:%lu\", sz);\n nextra += used;\n remaining -= used;\n }", " addReplyStatusFormat(c,\n \"Value at:%p refcount:%d \"\n \"encoding:%s serializedlength:%zu \"\n \"lru:%d lru_seconds_idle:%llu%s\",\n (void*)val, val->refcount,\n strenc, rdbSavedObjectLen(val, c->argv[2], c->db->id),\n val->lru, estimateObjectIdleTime(val)/1000, extra);\n } else if (!strcasecmp(c->argv[1]->ptr,\"sdslen\") && c->argc == 3) {\n dictEntry *de;\n robj *val;\n sds key;", " if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) {\n addReplyErrorObject(c,shared.nokeyerr);\n return;\n }\n val = dictGetVal(de);\n key = dictGetKey(de);", " if (val->type != OBJ_STRING || !sdsEncodedObject(val)) {\n addReplyError(c,\"Not an sds encoded string.\");\n } else {\n addReplyStatusFormat(c,\n \"key_sds_len:%lld, key_sds_avail:%lld, key_zmalloc: %lld, \"\n \"val_sds_len:%lld, val_sds_avail:%lld, val_zmalloc: %lld\",\n (long long) sdslen(key),\n (long long) sdsavail(key),\n (long long) sdsZmallocSize(key),\n (long long) sdslen(val->ptr),\n (long long) sdsavail(val->ptr),\n (long long) getStringObjectSdsUsedMemory(val));\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"listpack\") && c->argc == 3) {\n robj *o;", " if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.nokeyerr))\n == NULL) return;", " if (o->encoding != OBJ_ENCODING_LISTPACK) {\n addReplyError(c,\"Not a listpack encoded object.\");\n } else {\n lpRepr(o->ptr);\n addReplyStatus(c,\"Listpack structure printed on stdout\");\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"quicklist\") && (c->argc == 3 || c->argc == 4)) {\n robj *o;", " if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.nokeyerr))\n == NULL) return;", " int full = 0;\n if (c->argc == 4)\n full = atoi(c->argv[3]->ptr);\n if (o->encoding != OBJ_ENCODING_QUICKLIST) {\n addReplyError(c,\"Not a quicklist encoded object.\");\n } else {\n quicklistRepr(o->ptr, full);\n addReplyStatus(c,\"Quicklist structure printed on stdout\");\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"populate\") &&\n c->argc >= 3 && c->argc <= 5) {\n long keys, j;\n robj *key, *val;\n char buf[128];", " if (getPositiveLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != C_OK)\n return;", " dictExpand(c->db->dict,keys);\n long valsize = 0;\n if ( c->argc == 5 && getPositiveLongFromObjectOrReply(c, c->argv[4], &valsize, NULL) != C_OK ) \n return;", " for (j = 0; j < keys; j++) {\n snprintf(buf,sizeof(buf),\"%s:%lu\",\n (c->argc == 3) ? \"key\" : (char*)c->argv[3]->ptr, j);\n key = createStringObject(buf,strlen(buf));\n if (lookupKeyWrite(c->db,key) != NULL) {\n decrRefCount(key);\n continue;\n }\n snprintf(buf,sizeof(buf),\"value:%lu\",j);\n if (valsize==0)\n val = createStringObject(buf,strlen(buf));\n else {\n int buflen = strlen(buf);\n val = createStringObject(NULL,valsize);\n memcpy(val->ptr, buf, valsize<=buflen? valsize: buflen);\n }\n dbAdd(c->db,key,val);\n signalModifiedKey(c,c->db,key);\n decrRefCount(key);\n }\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"digest\") && c->argc == 2) {\n /* DEBUG DIGEST (form without keys specified) */\n unsigned char digest[20];\n sds d = sdsempty();", " computeDatasetDigest(digest);\n for (int i = 0; i < 20; i++) d = sdscatprintf(d, \"%02x\",digest[i]);\n addReplyStatus(c,d);\n sdsfree(d);\n } else if (!strcasecmp(c->argv[1]->ptr,\"digest-value\") && c->argc >= 2) {\n /* DEBUG DIGEST-VALUE key key key ... key. */\n addReplyArrayLen(c,c->argc-2);\n for (int j = 2; j < c->argc; j++) {\n unsigned char digest[20];\n memset(digest,0,20); /* Start with a clean result */", " /* We don't use lookupKey because a debug command should\n * work on logically expired keys */\n dictEntry *de;\n robj *o = ((de = dictFind(c->db->dict,c->argv[j]->ptr)) == NULL) ? NULL : dictGetVal(de);\n if (o) xorObjectDigest(c->db,c->argv[j],digest,o);", " sds d = sdsempty();\n for (int i = 0; i < 20; i++) d = sdscatprintf(d, \"%02x\",digest[i]);\n addReplyStatus(c,d);\n sdsfree(d);\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"protocol\") && c->argc == 3) {\n /* DEBUG PROTOCOL [string|integer|double|bignum|null|array|set|map|\n * attrib|push|verbatim|true|false] */\n char *name = c->argv[2]->ptr;\n if (!strcasecmp(name,\"string\")) {\n addReplyBulkCString(c,\"Hello World\");\n } else if (!strcasecmp(name,\"integer\")) {\n addReplyLongLong(c,12345);\n } else if (!strcasecmp(name,\"double\")) {\n addReplyDouble(c,3.141);\n } else if (!strcasecmp(name,\"bignum\")) {\n addReplyBigNum(c,\"1234567999999999999999999999999999999\",37);\n } else if (!strcasecmp(name,\"null\")) {\n addReplyNull(c);\n } else if (!strcasecmp(name,\"array\")) {\n addReplyArrayLen(c,3);\n for (int j = 0; j < 3; j++) addReplyLongLong(c,j);\n } else if (!strcasecmp(name,\"set\")) {\n addReplySetLen(c,3);\n for (int j = 0; j < 3; j++) addReplyLongLong(c,j);\n } else if (!strcasecmp(name,\"map\")) {\n addReplyMapLen(c,3);\n for (int j = 0; j < 3; j++) {\n addReplyLongLong(c,j);\n addReplyBool(c, j == 1);\n }\n } else if (!strcasecmp(name,\"attrib\")) {\n if (c->resp >= 3) {\n addReplyAttributeLen(c,1);\n addReplyBulkCString(c,\"key-popularity\");\n addReplyArrayLen(c,2);\n addReplyBulkCString(c,\"key:123\");\n addReplyLongLong(c,90);\n }\n /* Attributes are not real replies, so a well formed reply should\n * also have a normal reply type after the attribute. */\n addReplyBulkCString(c,\"Some real reply following the attribute\");\n } else if (!strcasecmp(name,\"push\")) {\n if (c->resp < 3) {\n addReplyError(c,\"RESP2 is not supported by this command\");\n return;\n\t }\n addReplyPushLen(c,2);\n addReplyBulkCString(c,\"server-cpu-usage\");\n addReplyLongLong(c,42);\n /* Push replies are not synchronous replies, so we emit also a\n * normal reply in order for blocking clients just discarding the\n * push reply, to actually consume the reply and continue. */\n addReplyBulkCString(c,\"Some real reply following the push reply\");\n } else if (!strcasecmp(name,\"true\")) {\n addReplyBool(c,1);\n } else if (!strcasecmp(name,\"false\")) {\n addReplyBool(c,0);\n } else if (!strcasecmp(name,\"verbatim\")) {\n addReplyVerbatim(c,\"This is a verbatim\\nstring\",25,\"txt\");\n } else {\n addReplyError(c,\"Wrong protocol type name. Please use one of the following: string|integer|double|bignum|null|array|set|map|attrib|push|verbatim|true|false\");\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"sleep\") && c->argc == 3) {\n double dtime = strtod(c->argv[2]->ptr,NULL);\n long long utime = dtime*1000000;\n struct timespec tv;", " tv.tv_sec = utime / 1000000;\n tv.tv_nsec = (utime % 1000000) * 1000;\n nanosleep(&tv, NULL);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"set-active-expire\") &&\n c->argc == 3)\n {\n server.active_expire_enabled = atoi(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"quicklist-packed-threshold\") &&\n c->argc == 3)\n {\n int memerr;\n unsigned long long sz = memtoull((const char *)c->argv[2]->ptr, &memerr);\n if (memerr || !quicklistisSetPackedThreshold(sz)) {\n addReplyError(c, \"argument must be a memory value bigger than 1 and smaller than 4gb\");\n } else {\n addReply(c,shared.ok);\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"set-skip-checksum-validation\") &&\n c->argc == 3)\n {\n server.skip_checksum_validation = atoi(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"aof-flush-sleep\") &&\n c->argc == 3)\n {\n server.aof_flush_sleep = atoi(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"replicate\") && c->argc >= 3) {\n replicationFeedSlaves(server.slaves, -1,\n c->argv + 2, c->argc - 2);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"error\") && c->argc == 3) {\n sds errstr = sdsnewlen(\"-\",1);", " errstr = sdscatsds(errstr,c->argv[2]->ptr);\n errstr = sdsmapchars(errstr,\"\\n\\r\",\" \",2); /* no newlines in errors. */\n errstr = sdscatlen(errstr,\"\\r\\n\",2);\n addReplySds(c,errstr);\n } else if (!strcasecmp(c->argv[1]->ptr,\"structsize\") && c->argc == 2) {\n sds sizes = sdsempty();\n sizes = sdscatprintf(sizes,\"bits:%d \",(sizeof(void*) == 8)?64:32);\n sizes = sdscatprintf(sizes,\"robj:%d \",(int)sizeof(robj));\n sizes = sdscatprintf(sizes,\"dictentry:%d \",(int)sizeof(dictEntry));\n sizes = sdscatprintf(sizes,\"sdshdr5:%d \",(int)sizeof(struct sdshdr5));\n sizes = sdscatprintf(sizes,\"sdshdr8:%d \",(int)sizeof(struct sdshdr8));\n sizes = sdscatprintf(sizes,\"sdshdr16:%d \",(int)sizeof(struct sdshdr16));\n sizes = sdscatprintf(sizes,\"sdshdr32:%d \",(int)sizeof(struct sdshdr32));\n sizes = sdscatprintf(sizes,\"sdshdr64:%d \",(int)sizeof(struct sdshdr64));\n addReplyBulkSds(c,sizes);\n } else if (!strcasecmp(c->argv[1]->ptr,\"htstats\") && c->argc == 3) {\n long dbid;\n sds stats = sdsempty();\n char buf[4096];", " if (getLongFromObjectOrReply(c, c->argv[2], &dbid, NULL) != C_OK) {\n sdsfree(stats);\n return;\n }\n if (dbid < 0 || dbid >= server.dbnum) {\n sdsfree(stats);\n addReplyError(c,\"Out of range database\");\n return;\n }", " stats = sdscatprintf(stats,\"[Dictionary HT]\\n\");\n dictGetStats(buf,sizeof(buf),server.db[dbid].dict);\n stats = sdscat(stats,buf);", " stats = sdscatprintf(stats,\"[Expires HT]\\n\");\n dictGetStats(buf,sizeof(buf),server.db[dbid].expires);\n stats = sdscat(stats,buf);", " addReplyVerbatim(c,stats,sdslen(stats),\"txt\");\n sdsfree(stats);\n } else if (!strcasecmp(c->argv[1]->ptr,\"htstats-key\") && c->argc == 3) {\n robj *o;\n dict *ht = NULL;", " if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.nokeyerr))\n == NULL) return;", " /* Get the hash table reference from the object, if possible. */\n switch (o->encoding) {\n case OBJ_ENCODING_SKIPLIST:\n {\n zset *zs = o->ptr;\n ht = zs->dict;\n }\n break;\n case OBJ_ENCODING_HT:\n ht = o->ptr;\n break;\n }", " if (ht == NULL) {\n addReplyError(c,\"The value stored at the specified key is not \"\n \"represented using an hash table\");\n } else {\n char buf[4096];\n dictGetStats(buf,sizeof(buf),ht);\n addReplyVerbatim(c,buf,strlen(buf),\"txt\");\n }\n } else if (!strcasecmp(c->argv[1]->ptr,\"change-repl-id\") && c->argc == 2) {\n serverLog(LL_WARNING,\"Changing replication IDs after receiving DEBUG change-repl-id\");\n changeReplicationId();\n clearReplicationId2();\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"stringmatch-test\") && c->argc == 2)\n {\n stringmatchlen_fuzz_test();\n addReplyStatus(c,\"Apparently Redis did not crash: test passed\");\n } else if (!strcasecmp(c->argv[1]->ptr,\"set-disable-deny-scripts\") && c->argc == 3)\n {\n server.script_disable_deny_script = atoi(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"config-rewrite-force-all\") && c->argc == 2)\n {\n if (rewriteConfig(server.configfile, 1) == -1)\n addReplyErrorFormat(c, \"CONFIG-REWRITE-FORCE-ALL failed: %s\", strerror(errno));\n else\n addReply(c, shared.ok);\n } else if(!strcasecmp(c->argv[1]->ptr,\"client-eviction\") && c->argc == 2) {\n sds bucket_info = sdsempty();\n for (int j = 0; j < CLIENT_MEM_USAGE_BUCKETS; j++) {\n if (j == 0)\n bucket_info = sdscatprintf(bucket_info, \"bucket 0\");\n else\n bucket_info = sdscatprintf(bucket_info, \"bucket %10zu\", (size_t)1<<(j-1+CLIENT_MEM_USAGE_BUCKET_MIN_LOG));\n if (j == CLIENT_MEM_USAGE_BUCKETS-1)\n bucket_info = sdscatprintf(bucket_info, \"+ : \");\n else\n bucket_info = sdscatprintf(bucket_info, \" - %10zu: \", ((size_t)1<<(j+CLIENT_MEM_USAGE_BUCKET_MIN_LOG))-1);\n bucket_info = sdscatprintf(bucket_info, \"tot-mem: %10zu, clients: %lu\\n\",\n server.client_mem_usage_buckets[j].mem_usage_sum,\n server.client_mem_usage_buckets[j].clients->len);\n }\n addReplyVerbatim(c,bucket_info,sdslen(bucket_info),\"txt\");\n sdsfree(bucket_info);\n#ifdef USE_JEMALLOC\n } else if(!strcasecmp(c->argv[1]->ptr,\"mallctl\") && c->argc >= 3) {\n mallctl_int(c, c->argv+2, c->argc-2);\n return;\n } else if(!strcasecmp(c->argv[1]->ptr,\"mallctl-str\") && c->argc >= 3) {\n mallctl_string(c, c->argv+2, c->argc-2);\n return;\n#endif\n } else if (!strcasecmp(c->argv[1]->ptr,\"pause-cron\") && c->argc == 3)\n {\n server.pause_cron = atoi(c->argv[2]->ptr);\n addReply(c,shared.ok);\n } else if (!strcasecmp(c->argv[1]->ptr,\"replybuffer\") && c->argc == 4 ) {\n if(!strcasecmp(c->argv[2]->ptr, \"peak-reset-time\")) {\n if (!strcasecmp(c->argv[3]->ptr, \"never\")) {\n server.reply_buffer_peak_reset_time = -1;\n } else if(!strcasecmp(c->argv[3]->ptr, \"reset\")) {\n server.reply_buffer_peak_reset_time = REPLY_BUFFER_DEFAULT_PEAK_RESET_TIME;\n } else {\n if (getLongFromObjectOrReply(c, c->argv[3], &server.reply_buffer_peak_reset_time, NULL) != C_OK)\n return;\n }\n } else if(!strcasecmp(c->argv[2]->ptr,\"resizing\")) {\n server.reply_buffer_resizing_enabled = atoi(c->argv[3]->ptr);\n } else {\n addReplySubcommandSyntaxError(c);\n return;\n }\n addReply(c, shared.ok);\n } else {\n addReplySubcommandSyntaxError(c);\n return;\n }\n}", "/* =========================== Crash handling ============================== */", "void _serverAssert(const char *estr, const char *file, int line) {\n bugReportStart();\n serverLog(LL_WARNING,\"=== ASSERTION FAILED ===\");\n serverLog(LL_WARNING,\"==> %s:%d '%s' is not true\",file,line,estr);", " if (server.crashlog_enabled) {\n#ifdef HAVE_BACKTRACE\n logStackTrace(NULL, 1);\n#endif\n printCrashReport();\n }", " // remove the signal handler so on abort() we will output the crash report.\n removeSignalHandlers();\n bugReportEnd(0, 0);\n}", "void _serverAssertPrintClientInfo(const client *c) {\n int j;\n char conninfo[CONN_INFO_LEN];", " bugReportStart();\n serverLog(LL_WARNING,\"=== ASSERTION FAILED CLIENT CONTEXT ===\");\n serverLog(LL_WARNING,\"client->flags = %llu\", (unsigned long long) c->flags);\n serverLog(LL_WARNING,\"client->conn = %s\", connGetInfo(c->conn, conninfo, sizeof(conninfo)));\n serverLog(LL_WARNING,\"client->argc = %d\", c->argc);\n for (j=0; j < c->argc; j++) {\n char buf[128];\n char *arg;", " if (c->argv[j]->type == OBJ_STRING && sdsEncodedObject(c->argv[j])) {\n arg = (char*) c->argv[j]->ptr;\n } else {\n snprintf(buf,sizeof(buf),\"Object type: %u, encoding: %u\",\n c->argv[j]->type, c->argv[j]->encoding);\n arg = buf;\n }\n serverLog(LL_WARNING,\"client->argv[%d] = \\\"%s\\\" (refcount: %d)\",\n j, arg, c->argv[j]->refcount);\n }\n}", "void serverLogObjectDebugInfo(const robj *o) {\n serverLog(LL_WARNING,\"Object type: %u\", o->type);\n serverLog(LL_WARNING,\"Object encoding: %u\", o->encoding);\n serverLog(LL_WARNING,\"Object refcount: %d\", o->refcount);\n#if UNSAFE_CRASH_REPORT\n /* This code is now disabled. o->ptr may be unreliable to print. in some\n * cases a ziplist could have already been freed by realloc, but not yet\n * updated to o->ptr. in other cases the call to ziplistLen may need to\n * iterate on all the items in the list (and possibly crash again).\n * For some cases it may be ok to crash here again, but these could cause\n * invalid memory access which will bother valgrind and also possibly cause\n * random memory portion to be \"leaked\" into the logfile. */\n if (o->type == OBJ_STRING && sdsEncodedObject(o)) {\n serverLog(LL_WARNING,\"Object raw string len: %zu\", sdslen(o->ptr));\n if (sdslen(o->ptr) < 4096) {\n sds repr = sdscatrepr(sdsempty(),o->ptr,sdslen(o->ptr));\n serverLog(LL_WARNING,\"Object raw string content: %s\", repr);\n sdsfree(repr);\n }\n } else if (o->type == OBJ_LIST) {\n serverLog(LL_WARNING,\"List length: %d\", (int) listTypeLength(o));\n } else if (o->type == OBJ_SET) {\n serverLog(LL_WARNING,\"Set size: %d\", (int) setTypeSize(o));\n } else if (o->type == OBJ_HASH) {\n serverLog(LL_WARNING,\"Hash size: %d\", (int) hashTypeLength(o));\n } else if (o->type == OBJ_ZSET) {\n serverLog(LL_WARNING,\"Sorted set size: %d\", (int) zsetLength(o));\n if (o->encoding == OBJ_ENCODING_SKIPLIST)\n serverLog(LL_WARNING,\"Skiplist level: %d\", (int) ((const zset*)o->ptr)->zsl->level);\n } else if (o->type == OBJ_STREAM) {\n serverLog(LL_WARNING,\"Stream size: %d\", (int) streamLength(o));\n }\n#endif\n}", "void _serverAssertPrintObject(const robj *o) {\n bugReportStart();\n serverLog(LL_WARNING,\"=== ASSERTION FAILED OBJECT CONTEXT ===\");\n serverLogObjectDebugInfo(o);\n}", "void _serverAssertWithInfo(const client *c, const robj *o, const char *estr, const char *file, int line) {\n if (c) _serverAssertPrintClientInfo(c);\n if (o) _serverAssertPrintObject(o);\n _serverAssert(estr,file,line);\n}", "void _serverPanic(const char *file, int line, const char *msg, ...) {\n va_list ap;\n va_start(ap,msg);\n char fmtmsg[256];\n vsnprintf(fmtmsg,sizeof(fmtmsg),msg,ap);\n va_end(ap);", " bugReportStart();\n serverLog(LL_WARNING,\"------------------------------------------------\");\n serverLog(LL_WARNING,\"!!! Software Failure. Press left mouse button to continue\");\n serverLog(LL_WARNING,\"Guru Meditation: %s #%s:%d\",fmtmsg,file,line);", " if (server.crashlog_enabled) {\n#ifdef HAVE_BACKTRACE\n logStackTrace(NULL, 1);\n#endif\n printCrashReport();\n }", " // remove the signal handler so on abort() we will output the crash report.\n removeSignalHandlers();\n bugReportEnd(0, 0);\n}", "void bugReportStart(void) {\n pthread_mutex_lock(&bug_report_start_mutex);\n if (bug_report_start == 0) {\n serverLogRaw(LL_WARNING|LL_RAW,\n \"\\n\\n=== REDIS BUG REPORT START: Cut & paste starting from here ===\\n\");\n bug_report_start = 1;\n }\n pthread_mutex_unlock(&bug_report_start_mutex);\n}", "#ifdef HAVE_BACKTRACE", "\n/* Returns the current eip and set it to the given new value (if its not NULL) */\nstatic void* getAndSetMcontextEip(ucontext_t *uc, void *eip) {", "#define NOT_SUPPORTED() do {\\\n UNUSED(uc);\\", " UNUSED(eip);\\", " return NULL;\\", "} while(0)\n#define GET_SET_RETURN(target_var, new_val) do {\\\n void *old_val = (void*)target_var; \\\n if (new_val) { \\\n void **temp = (void**)&target_var; \\\n *temp = new_val; \\\n } \\\n return old_val; \\", "} while(0)\n#if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)\n /* OSX < 10.6 */\n #if defined(__x86_64__)", " GET_SET_RETURN(uc->uc_mcontext->__ss.__rip, eip);", " #elif defined(__i386__)", " GET_SET_RETURN(uc->uc_mcontext->__ss.__eip, eip);", " #else", " GET_SET_RETURN(uc->uc_mcontext->__ss.__srr0, eip);", " #endif\n#elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)\n /* OSX >= 10.6 */\n #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)", " GET_SET_RETURN(uc->uc_mcontext->__ss.__rip, eip);", " #elif defined(__i386__)", " GET_SET_RETURN(uc->uc_mcontext->__ss.__eip, eip);", " #else\n /* OSX ARM64 */", " void *old_val = (void*)arm_thread_state64_get_pc(uc->uc_mcontext->__ss);\n if (eip) {\n arm_thread_state64_set_pc_fptr(uc->uc_mcontext->__ss, eip);\n }\n return old_val;", " #endif\n#elif defined(__linux__)\n /* Linux */\n #if defined(__i386__) || ((defined(__X86_64__) || defined(__x86_64__)) && defined(__ILP32__))", " GET_SET_RETURN(uc->uc_mcontext.gregs[14], eip);", " #elif defined(__X86_64__) || defined(__x86_64__)", " GET_SET_RETURN(uc->uc_mcontext.gregs[16], eip);", " #elif defined(__ia64__) /* Linux IA64 */", " GET_SET_RETURN(uc->uc_mcontext.sc_ip, eip);", " #elif defined(__arm__) /* Linux ARM */", " GET_SET_RETURN(uc->uc_mcontext.arm_pc, eip);", " #elif defined(__aarch64__) /* Linux AArch64 */", " GET_SET_RETURN(uc->uc_mcontext.pc, eip);", " #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__FreeBSD__)\n /* FreeBSD */\n #if defined(__i386__)", " GET_SET_RETURN(uc->uc_mcontext.mc_eip, eip);", " #elif defined(__x86_64__)", " GET_SET_RETURN(uc->uc_mcontext.mc_rip, eip);", " #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__OpenBSD__)\n /* OpenBSD */\n #if defined(__i386__)", " GET_SET_RETURN(uc->sc_eip, eip);", " #elif defined(__x86_64__)", " GET_SET_RETURN(uc->sc_rip, eip);", " #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__NetBSD__)\n #if defined(__i386__)", " GET_SET_RETURN(uc->uc_mcontext.__gregs[_REG_EIP], eip);", " #elif defined(__x86_64__)", " GET_SET_RETURN(uc->uc_mcontext.__gregs[_REG_RIP], eip);", " #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__DragonFly__)", " GET_SET_RETURN(uc->uc_mcontext.mc_rip, eip);", "#else\n NOT_SUPPORTED();\n#endif\n#undef NOT_SUPPORTED\n}", "REDIS_NO_SANITIZE(\"address\")\nvoid logStackContent(void **sp) {\n int i;\n for (i = 15; i >= 0; i--) {\n unsigned long addr = (unsigned long) sp+i;\n unsigned long val = (unsigned long) sp[i];", " if (sizeof(long) == 4)\n serverLog(LL_WARNING, \"(%08lx) -> %08lx\", addr, val);\n else\n serverLog(LL_WARNING, \"(%016lx) -> %016lx\", addr, val);\n }\n}", "/* Log dump of processor registers */\nvoid logRegisters(ucontext_t *uc) {\n serverLog(LL_WARNING|LL_RAW, \"\\n------ REGISTERS ------\\n\");\n#define NOT_SUPPORTED() do {\\\n UNUSED(uc);\\\n serverLog(LL_WARNING,\\\n \" Dumping of registers not supported for this OS/arch\");\\\n} while(0)", "/* OSX */\n#if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)\n /* OSX AMD64 */\n #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCS :%016lx FS:%016lx GS:%016lx\",\n (unsigned long) uc->uc_mcontext->__ss.__rax,\n (unsigned long) uc->uc_mcontext->__ss.__rbx,\n (unsigned long) uc->uc_mcontext->__ss.__rcx,\n (unsigned long) uc->uc_mcontext->__ss.__rdx,\n (unsigned long) uc->uc_mcontext->__ss.__rdi,\n (unsigned long) uc->uc_mcontext->__ss.__rsi,\n (unsigned long) uc->uc_mcontext->__ss.__rbp,\n (unsigned long) uc->uc_mcontext->__ss.__rsp,\n (unsigned long) uc->uc_mcontext->__ss.__r8,\n (unsigned long) uc->uc_mcontext->__ss.__r9,\n (unsigned long) uc->uc_mcontext->__ss.__r10,\n (unsigned long) uc->uc_mcontext->__ss.__r11,\n (unsigned long) uc->uc_mcontext->__ss.__r12,\n (unsigned long) uc->uc_mcontext->__ss.__r13,\n (unsigned long) uc->uc_mcontext->__ss.__r14,\n (unsigned long) uc->uc_mcontext->__ss.__r15,\n (unsigned long) uc->uc_mcontext->__ss.__rip,\n (unsigned long) uc->uc_mcontext->__ss.__rflags,\n (unsigned long) uc->uc_mcontext->__ss.__cs,\n (unsigned long) uc->uc_mcontext->__ss.__fs,\n (unsigned long) uc->uc_mcontext->__ss.__gs\n );\n logStackContent((void**)uc->uc_mcontext->__ss.__rsp);\n #elif defined(__i386__)\n /* OSX x86 */\n serverLog(LL_WARNING,\n \"\\n\"\n \"EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\\n\"\n \"EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\\n\"\n \"SS:%08lx EFL:%08lx EIP:%08lx CS :%08lx\\n\"\n \"DS:%08lx ES:%08lx FS :%08lx GS :%08lx\",\n (unsigned long) uc->uc_mcontext->__ss.__eax,\n (unsigned long) uc->uc_mcontext->__ss.__ebx,\n (unsigned long) uc->uc_mcontext->__ss.__ecx,\n (unsigned long) uc->uc_mcontext->__ss.__edx,\n (unsigned long) uc->uc_mcontext->__ss.__edi,\n (unsigned long) uc->uc_mcontext->__ss.__esi,\n (unsigned long) uc->uc_mcontext->__ss.__ebp,\n (unsigned long) uc->uc_mcontext->__ss.__esp,\n (unsigned long) uc->uc_mcontext->__ss.__ss,\n (unsigned long) uc->uc_mcontext->__ss.__eflags,\n (unsigned long) uc->uc_mcontext->__ss.__eip,\n (unsigned long) uc->uc_mcontext->__ss.__cs,\n (unsigned long) uc->uc_mcontext->__ss.__ds,\n (unsigned long) uc->uc_mcontext->__ss.__es,\n (unsigned long) uc->uc_mcontext->__ss.__fs,\n (unsigned long) uc->uc_mcontext->__ss.__gs\n );\n logStackContent((void**)uc->uc_mcontext->__ss.__esp);\n #else\n /* OSX ARM64 */\n serverLog(LL_WARNING,\n \"\\n\"\n \"x0:%016lx x1:%016lx x2:%016lx x3:%016lx\\n\"\n \"x4:%016lx x5:%016lx x6:%016lx x7:%016lx\\n\"\n \"x8:%016lx x9:%016lx x10:%016lx x11:%016lx\\n\"\n \"x12:%016lx x13:%016lx x14:%016lx x15:%016lx\\n\"\n \"x16:%016lx x17:%016lx x18:%016lx x19:%016lx\\n\"\n \"x20:%016lx x21:%016lx x22:%016lx x23:%016lx\\n\"\n \"x24:%016lx x25:%016lx x26:%016lx x27:%016lx\\n\"\n \"x28:%016lx fp:%016lx lr:%016lx\\n\"\n \"sp:%016lx pc:%016lx cpsr:%08lx\\n\",\n (unsigned long) uc->uc_mcontext->__ss.__x[0],\n (unsigned long) uc->uc_mcontext->__ss.__x[1],\n (unsigned long) uc->uc_mcontext->__ss.__x[2],\n (unsigned long) uc->uc_mcontext->__ss.__x[3],\n (unsigned long) uc->uc_mcontext->__ss.__x[4],\n (unsigned long) uc->uc_mcontext->__ss.__x[5],\n (unsigned long) uc->uc_mcontext->__ss.__x[6],\n (unsigned long) uc->uc_mcontext->__ss.__x[7],\n (unsigned long) uc->uc_mcontext->__ss.__x[8],\n (unsigned long) uc->uc_mcontext->__ss.__x[9],\n (unsigned long) uc->uc_mcontext->__ss.__x[10],\n (unsigned long) uc->uc_mcontext->__ss.__x[11],\n (unsigned long) uc->uc_mcontext->__ss.__x[12],\n (unsigned long) uc->uc_mcontext->__ss.__x[13],\n (unsigned long) uc->uc_mcontext->__ss.__x[14],\n (unsigned long) uc->uc_mcontext->__ss.__x[15],\n (unsigned long) uc->uc_mcontext->__ss.__x[16],\n (unsigned long) uc->uc_mcontext->__ss.__x[17],\n (unsigned long) uc->uc_mcontext->__ss.__x[18],\n (unsigned long) uc->uc_mcontext->__ss.__x[19],\n (unsigned long) uc->uc_mcontext->__ss.__x[20],\n (unsigned long) uc->uc_mcontext->__ss.__x[21],\n (unsigned long) uc->uc_mcontext->__ss.__x[22],\n (unsigned long) uc->uc_mcontext->__ss.__x[23],\n (unsigned long) uc->uc_mcontext->__ss.__x[24],\n (unsigned long) uc->uc_mcontext->__ss.__x[25],\n (unsigned long) uc->uc_mcontext->__ss.__x[26],\n (unsigned long) uc->uc_mcontext->__ss.__x[27],\n (unsigned long) uc->uc_mcontext->__ss.__x[28],\n (unsigned long) arm_thread_state64_get_fp(uc->uc_mcontext->__ss),\n (unsigned long) arm_thread_state64_get_lr(uc->uc_mcontext->__ss),\n (unsigned long) arm_thread_state64_get_sp(uc->uc_mcontext->__ss),\n (unsigned long) arm_thread_state64_get_pc(uc->uc_mcontext->__ss),\n (unsigned long) uc->uc_mcontext->__ss.__cpsr\n );\n logStackContent((void**) arm_thread_state64_get_sp(uc->uc_mcontext->__ss));\n #endif\n/* Linux */\n#elif defined(__linux__)\n /* Linux x86 */\n #if defined(__i386__) || ((defined(__X86_64__) || defined(__x86_64__)) && defined(__ILP32__))\n serverLog(LL_WARNING,\n \"\\n\"\n \"EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\\n\"\n \"EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\\n\"\n \"SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\\n\"\n \"DS :%08lx ES :%08lx FS :%08lx GS:%08lx\",\n (unsigned long) uc->uc_mcontext.gregs[11],\n (unsigned long) uc->uc_mcontext.gregs[8],\n (unsigned long) uc->uc_mcontext.gregs[10],\n (unsigned long) uc->uc_mcontext.gregs[9],\n (unsigned long) uc->uc_mcontext.gregs[4],\n (unsigned long) uc->uc_mcontext.gregs[5],\n (unsigned long) uc->uc_mcontext.gregs[6],\n (unsigned long) uc->uc_mcontext.gregs[7],\n (unsigned long) uc->uc_mcontext.gregs[18],\n (unsigned long) uc->uc_mcontext.gregs[17],\n (unsigned long) uc->uc_mcontext.gregs[14],\n (unsigned long) uc->uc_mcontext.gregs[15],\n (unsigned long) uc->uc_mcontext.gregs[3],\n (unsigned long) uc->uc_mcontext.gregs[2],\n (unsigned long) uc->uc_mcontext.gregs[1],\n (unsigned long) uc->uc_mcontext.gregs[0]\n );\n logStackContent((void**)uc->uc_mcontext.gregs[7]);\n #elif defined(__X86_64__) || defined(__x86_64__)\n /* Linux AMD64 */\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCSGSFS:%016lx\",\n (unsigned long) uc->uc_mcontext.gregs[13],\n (unsigned long) uc->uc_mcontext.gregs[11],\n (unsigned long) uc->uc_mcontext.gregs[14],\n (unsigned long) uc->uc_mcontext.gregs[12],\n (unsigned long) uc->uc_mcontext.gregs[8],\n (unsigned long) uc->uc_mcontext.gregs[9],\n (unsigned long) uc->uc_mcontext.gregs[10],\n (unsigned long) uc->uc_mcontext.gregs[15],\n (unsigned long) uc->uc_mcontext.gregs[0],\n (unsigned long) uc->uc_mcontext.gregs[1],\n (unsigned long) uc->uc_mcontext.gregs[2],\n (unsigned long) uc->uc_mcontext.gregs[3],\n (unsigned long) uc->uc_mcontext.gregs[4],\n (unsigned long) uc->uc_mcontext.gregs[5],\n (unsigned long) uc->uc_mcontext.gregs[6],\n (unsigned long) uc->uc_mcontext.gregs[7],\n (unsigned long) uc->uc_mcontext.gregs[16],\n (unsigned long) uc->uc_mcontext.gregs[17],\n (unsigned long) uc->uc_mcontext.gregs[18]\n );\n logStackContent((void**)uc->uc_mcontext.gregs[15]);\n #elif defined(__aarch64__) /* Linux AArch64 */\n serverLog(LL_WARNING,\n\t \"\\n\"\n\t \"X18:%016lx X19:%016lx\\nX20:%016lx X21:%016lx\\n\"\n\t \"X22:%016lx X23:%016lx\\nX24:%016lx X25:%016lx\\n\"\n\t \"X26:%016lx X27:%016lx\\nX28:%016lx X29:%016lx\\n\"\n\t \"X30:%016lx\\n\"\n\t \"pc:%016lx sp:%016lx\\npstate:%016lx fault_address:%016lx\\n\",\n\t (unsigned long) uc->uc_mcontext.regs[18],\n\t (unsigned long) uc->uc_mcontext.regs[19],\n\t (unsigned long) uc->uc_mcontext.regs[20],\n\t (unsigned long) uc->uc_mcontext.regs[21],\n\t (unsigned long) uc->uc_mcontext.regs[22],\n\t (unsigned long) uc->uc_mcontext.regs[23],\n\t (unsigned long) uc->uc_mcontext.regs[24],\n\t (unsigned long) uc->uc_mcontext.regs[25],\n\t (unsigned long) uc->uc_mcontext.regs[26],\n\t (unsigned long) uc->uc_mcontext.regs[27],\n\t (unsigned long) uc->uc_mcontext.regs[28],\n\t (unsigned long) uc->uc_mcontext.regs[29],\n\t (unsigned long) uc->uc_mcontext.regs[30],\n\t (unsigned long) uc->uc_mcontext.pc,\n\t (unsigned long) uc->uc_mcontext.sp,\n\t (unsigned long) uc->uc_mcontext.pstate,\n\t (unsigned long) uc->uc_mcontext.fault_address\n\t\t );\n\t logStackContent((void**)uc->uc_mcontext.sp);\n #elif defined(__arm__) /* Linux ARM */\n serverLog(LL_WARNING,\n\t \"\\n\"\n\t \"R10:%016lx R9 :%016lx\\nR8 :%016lx R7 :%016lx\\n\"\n\t \"R6 :%016lx R5 :%016lx\\nR4 :%016lx R3 :%016lx\\n\"\n\t \"R2 :%016lx R1 :%016lx\\nR0 :%016lx EC :%016lx\\n\"\n\t \"fp: %016lx ip:%016lx\\n\"\n\t \"pc:%016lx sp:%016lx\\ncpsr:%016lx fault_address:%016lx\\n\",\n\t (unsigned long) uc->uc_mcontext.arm_r10,\n\t (unsigned long) uc->uc_mcontext.arm_r9,\n\t (unsigned long) uc->uc_mcontext.arm_r8,\n\t (unsigned long) uc->uc_mcontext.arm_r7,\n\t (unsigned long) uc->uc_mcontext.arm_r6,\n\t (unsigned long) uc->uc_mcontext.arm_r5,\n\t (unsigned long) uc->uc_mcontext.arm_r4,\n\t (unsigned long) uc->uc_mcontext.arm_r3,\n\t (unsigned long) uc->uc_mcontext.arm_r2,\n\t (unsigned long) uc->uc_mcontext.arm_r1,\n\t (unsigned long) uc->uc_mcontext.arm_r0,\n\t (unsigned long) uc->uc_mcontext.error_code,\n\t (unsigned long) uc->uc_mcontext.arm_fp,\n\t (unsigned long) uc->uc_mcontext.arm_ip,\n\t (unsigned long) uc->uc_mcontext.arm_pc,\n\t (unsigned long) uc->uc_mcontext.arm_sp,\n\t (unsigned long) uc->uc_mcontext.arm_cpsr,\n\t (unsigned long) uc->uc_mcontext.fault_address\n\t\t );\n\t logStackContent((void**)uc->uc_mcontext.arm_sp);\n #else\n\tNOT_SUPPORTED();\n #endif\n#elif defined(__FreeBSD__)\n #if defined(__x86_64__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCSGSFS:%016lx\",\n (unsigned long) uc->uc_mcontext.mc_rax,\n (unsigned long) uc->uc_mcontext.mc_rbx,\n (unsigned long) uc->uc_mcontext.mc_rcx,\n (unsigned long) uc->uc_mcontext.mc_rdx,\n (unsigned long) uc->uc_mcontext.mc_rdi,\n (unsigned long) uc->uc_mcontext.mc_rsi,\n (unsigned long) uc->uc_mcontext.mc_rbp,\n (unsigned long) uc->uc_mcontext.mc_rsp,\n (unsigned long) uc->uc_mcontext.mc_r8,\n (unsigned long) uc->uc_mcontext.mc_r9,\n (unsigned long) uc->uc_mcontext.mc_r10,\n (unsigned long) uc->uc_mcontext.mc_r11,\n (unsigned long) uc->uc_mcontext.mc_r12,\n (unsigned long) uc->uc_mcontext.mc_r13,\n (unsigned long) uc->uc_mcontext.mc_r14,\n (unsigned long) uc->uc_mcontext.mc_r15,\n (unsigned long) uc->uc_mcontext.mc_rip,\n (unsigned long) uc->uc_mcontext.mc_rflags,\n (unsigned long) uc->uc_mcontext.mc_cs\n );\n logStackContent((void**)uc->uc_mcontext.mc_rsp);\n #elif defined(__i386__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\\n\"\n \"EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\\n\"\n \"SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\\n\"\n \"DS :%08lx ES :%08lx FS :%08lx GS:%08lx\",\n (unsigned long) uc->uc_mcontext.mc_eax,\n (unsigned long) uc->uc_mcontext.mc_ebx,\n (unsigned long) uc->uc_mcontext.mc_ebx,\n (unsigned long) uc->uc_mcontext.mc_edx,\n (unsigned long) uc->uc_mcontext.mc_edi,\n (unsigned long) uc->uc_mcontext.mc_esi,\n (unsigned long) uc->uc_mcontext.mc_ebp,\n (unsigned long) uc->uc_mcontext.mc_esp,\n (unsigned long) uc->uc_mcontext.mc_ss,\n (unsigned long) uc->uc_mcontext.mc_eflags,\n (unsigned long) uc->uc_mcontext.mc_eip,\n (unsigned long) uc->uc_mcontext.mc_cs,\n (unsigned long) uc->uc_mcontext.mc_es,\n (unsigned long) uc->uc_mcontext.mc_fs,\n (unsigned long) uc->uc_mcontext.mc_gs\n );\n logStackContent((void**)uc->uc_mcontext.mc_esp);\n #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__OpenBSD__)\n #if defined(__x86_64__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCSGSFS:%016lx\",\n (unsigned long) uc->sc_rax,\n (unsigned long) uc->sc_rbx,\n (unsigned long) uc->sc_rcx,\n (unsigned long) uc->sc_rdx,\n (unsigned long) uc->sc_rdi,\n (unsigned long) uc->sc_rsi,\n (unsigned long) uc->sc_rbp,\n (unsigned long) uc->sc_rsp,\n (unsigned long) uc->sc_r8,\n (unsigned long) uc->sc_r9,\n (unsigned long) uc->sc_r10,\n (unsigned long) uc->sc_r11,\n (unsigned long) uc->sc_r12,\n (unsigned long) uc->sc_r13,\n (unsigned long) uc->sc_r14,\n (unsigned long) uc->sc_r15,\n (unsigned long) uc->sc_rip,\n (unsigned long) uc->sc_rflags,\n (unsigned long) uc->sc_cs\n );\n logStackContent((void**)uc->sc_rsp);\n #elif defined(__i386__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\\n\"\n \"EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\\n\"\n \"SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\\n\"\n \"DS :%08lx ES :%08lx FS :%08lx GS:%08lx\",\n (unsigned long) uc->sc_eax,\n (unsigned long) uc->sc_ebx,\n (unsigned long) uc->sc_ebx,\n (unsigned long) uc->sc_edx,\n (unsigned long) uc->sc_edi,\n (unsigned long) uc->sc_esi,\n (unsigned long) uc->sc_ebp,\n (unsigned long) uc->sc_esp,\n (unsigned long) uc->sc_ss,\n (unsigned long) uc->sc_eflags,\n (unsigned long) uc->sc_eip,\n (unsigned long) uc->sc_cs,\n (unsigned long) uc->sc_es,\n (unsigned long) uc->sc_fs,\n (unsigned long) uc->sc_gs\n );\n logStackContent((void**)uc->sc_esp);\n #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__NetBSD__)\n #if defined(__x86_64__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCSGSFS:%016lx\",\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RAX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RBX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RCX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RDX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RDI],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RSI],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RBP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RSP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R8],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R9],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R10],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R11],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R12],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R13],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R14],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_R15],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RIP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_RFLAGS],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_CS]\n );\n logStackContent((void**)uc->uc_mcontext.__gregs[_REG_RSP]);\n #elif defined(__i386__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\\n\"\n \"EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\\n\"\n \"SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\\n\"\n \"DS :%08lx ES :%08lx FS :%08lx GS:%08lx\",\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EAX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EBX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EDX],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EDI],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_ESI],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EBP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_ESP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_SS],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EFLAGS],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_EIP],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_CS],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_ES],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_FS],\n (unsigned long) uc->uc_mcontext.__gregs[_REG_GS]\n );\n #else\n NOT_SUPPORTED();\n #endif\n#elif defined(__DragonFly__)\n serverLog(LL_WARNING,\n \"\\n\"\n \"RAX:%016lx RBX:%016lx\\nRCX:%016lx RDX:%016lx\\n\"\n \"RDI:%016lx RSI:%016lx\\nRBP:%016lx RSP:%016lx\\n\"\n \"R8 :%016lx R9 :%016lx\\nR10:%016lx R11:%016lx\\n\"\n \"R12:%016lx R13:%016lx\\nR14:%016lx R15:%016lx\\n\"\n \"RIP:%016lx EFL:%016lx\\nCSGSFS:%016lx\",\n (unsigned long) uc->uc_mcontext.mc_rax,\n (unsigned long) uc->uc_mcontext.mc_rbx,\n (unsigned long) uc->uc_mcontext.mc_rcx,\n (unsigned long) uc->uc_mcontext.mc_rdx,\n (unsigned long) uc->uc_mcontext.mc_rdi,\n (unsigned long) uc->uc_mcontext.mc_rsi,\n (unsigned long) uc->uc_mcontext.mc_rbp,\n (unsigned long) uc->uc_mcontext.mc_rsp,\n (unsigned long) uc->uc_mcontext.mc_r8,\n (unsigned long) uc->uc_mcontext.mc_r9,\n (unsigned long) uc->uc_mcontext.mc_r10,\n (unsigned long) uc->uc_mcontext.mc_r11,\n (unsigned long) uc->uc_mcontext.mc_r12,\n (unsigned long) uc->uc_mcontext.mc_r13,\n (unsigned long) uc->uc_mcontext.mc_r14,\n (unsigned long) uc->uc_mcontext.mc_r15,\n (unsigned long) uc->uc_mcontext.mc_rip,\n (unsigned long) uc->uc_mcontext.mc_rflags,\n (unsigned long) uc->uc_mcontext.mc_cs\n );\n logStackContent((void**)uc->uc_mcontext.mc_rsp);\n#else\n NOT_SUPPORTED();\n#endif\n#undef NOT_SUPPORTED\n}", "#endif /* HAVE_BACKTRACE */", "/* Return a file descriptor to write directly to the Redis log with the\n * write(2) syscall, that can be used in critical sections of the code\n * where the rest of Redis can't be trusted (for example during the memory\n * test) or when an API call requires a raw fd.\n *\n * Close it with closeDirectLogFiledes(). */\nint openDirectLogFiledes(void) {\n int log_to_stdout = server.logfile[0] == '\\0';\n int fd = log_to_stdout ?\n STDOUT_FILENO :\n open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644);\n return fd;\n}", "/* Used to close what closeDirectLogFiledes() returns. */\nvoid closeDirectLogFiledes(int fd) {\n int log_to_stdout = server.logfile[0] == '\\0';\n if (!log_to_stdout) close(fd);\n}", "#ifdef HAVE_BACKTRACE", "/* Logs the stack trace using the backtrace() call. This function is designed\n * to be called from signal handlers safely.\n * The eip argument is optional (can take NULL).\n * The uplevel argument indicates how many of the calling functions to skip.\n */\nvoid logStackTrace(void *eip, int uplevel) {\n void *trace[100];\n int trace_size = 0, fd = openDirectLogFiledes();\n char *msg;\n uplevel++; /* skip this function */", " if (fd == -1) return; /* If we can't log there is anything to do. */", " /* Get the stack trace first! */\n trace_size = backtrace(trace, 100);", " msg = \"\\n------ STACK TRACE ------\\n\";\n if (write(fd,msg,strlen(msg)) == -1) {/* Avoid warning. */};", " if (eip) {\n /* Write EIP to the log file*/\n msg = \"EIP:\\n\";\n if (write(fd,msg,strlen(msg)) == -1) {/* Avoid warning. */};\n backtrace_symbols_fd(&eip, 1, fd);\n }", " /* Write symbols to log file */\n msg = \"\\nBacktrace:\\n\";\n if (write(fd,msg,strlen(msg)) == -1) {/* Avoid warning. */};\n backtrace_symbols_fd(trace+uplevel, trace_size-uplevel, fd);", " /* Cleanup */\n closeDirectLogFiledes(fd);\n}", "#endif /* HAVE_BACKTRACE */", "/* Log global server info */\nvoid logServerInfo(void) {\n sds infostring, clients;\n serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ INFO OUTPUT ------\\n\");\n int all = 0, everything = 0;\n robj *argv[1];\n argv[0] = createStringObject(\"all\", strlen(\"all\"));\n dict *section_dict = genInfoSectionDict(argv, 1, NULL, &all, &everything);\n infostring = genRedisInfoString(section_dict, all, everything);\n serverLogRaw(LL_WARNING|LL_RAW, infostring);\n serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ CLIENT LIST OUTPUT ------\\n\");\n clients = getAllClientsInfoString(-1);\n serverLogRaw(LL_WARNING|LL_RAW, clients);\n sdsfree(infostring);\n sdsfree(clients);\n releaseInfoSectionDict(section_dict);\n decrRefCount(argv[0]);\n}", "/* Log certain config values, which can be used for debuggin */\nvoid logConfigDebugInfo(void) {\n sds configstring;\n configstring = getConfigDebugInfo();\n serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ CONFIG DEBUG OUTPUT ------\\n\");\n serverLogRaw(LL_WARNING|LL_RAW, configstring);\n sdsfree(configstring);\n}", "/* Log modules info. Something we wanna do last since we fear it may crash. */\nvoid logModulesInfo(void) {\n serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ MODULES INFO OUTPUT ------\\n\");\n sds infostring = modulesCollectInfo(sdsempty(), NULL, 1, 0);\n serverLogRaw(LL_WARNING|LL_RAW, infostring);\n sdsfree(infostring);\n}", "/* Log information about the \"current\" client, that is, the client that is\n * currently being served by Redis. May be NULL if Redis is not serving a\n * client right now. */\nvoid logCurrentClient(void) {\n if (server.current_client == NULL) return;", " client *cc = server.current_client;\n sds client;\n int j;", " serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ CURRENT CLIENT INFO ------\\n\");\n client = catClientInfoString(sdsempty(),cc);\n serverLog(LL_WARNING|LL_RAW,\"%s\\n\", client);\n sdsfree(client);\n for (j = 0; j < cc->argc; j++) {\n robj *decoded;\n decoded = getDecodedObject(cc->argv[j]);\n sds repr = sdscatrepr(sdsempty(),decoded->ptr, min(sdslen(decoded->ptr), 128));\n serverLog(LL_WARNING|LL_RAW,\"argv[%d]: '%s'\\n\", j, (char*)repr);\n sdsfree(repr);\n decrRefCount(decoded);\n }\n /* Check if the first argument, usually a key, is found inside the\n * selected DB, and if so print info about the associated object. */\n if (cc->argc > 1) {\n robj *val, *key;\n dictEntry *de;", " key = getDecodedObject(cc->argv[1]);\n de = dictFind(cc->db->dict, key->ptr);\n if (de) {\n val = dictGetVal(de);\n serverLog(LL_WARNING,\"key '%s' found in DB containing the following object:\", (char*)key->ptr);\n serverLogObjectDebugInfo(val);\n }\n decrRefCount(key);\n }\n}", "#if defined(HAVE_PROC_MAPS)", "#define MEMTEST_MAX_REGIONS 128", "/* A non destructive memory test executed during segfault. */\nint memtest_test_linux_anonymous_maps(void) {\n FILE *fp;\n char line[1024];\n char logbuf[1024];\n size_t start_addr, end_addr, size;\n size_t start_vect[MEMTEST_MAX_REGIONS];\n size_t size_vect[MEMTEST_MAX_REGIONS];\n int regions = 0, j;", " int fd = openDirectLogFiledes();\n if (!fd) return 0;", " fp = fopen(\"/proc/self/maps\",\"r\");\n if (!fp) {\n closeDirectLogFiledes(fd);\n return 0;\n }\n while(fgets(line,sizeof(line),fp) != NULL) {\n char *start, *end, *p = line;", " start = p;\n p = strchr(p,'-');\n if (!p) continue;\n *p++ = '\\0';\n end = p;\n p = strchr(p,' ');\n if (!p) continue;\n *p++ = '\\0';\n if (strstr(p,\"stack\") ||\n strstr(p,\"vdso\") ||\n strstr(p,\"vsyscall\")) continue;\n if (!strstr(p,\"00:00\")) continue;\n if (!strstr(p,\"rw\")) continue;", " start_addr = strtoul(start,NULL,16);\n end_addr = strtoul(end,NULL,16);\n size = end_addr-start_addr;", " start_vect[regions] = start_addr;\n size_vect[regions] = size;\n snprintf(logbuf,sizeof(logbuf),\n \"*** Preparing to test memory region %lx (%lu bytes)\\n\",\n (unsigned long) start_vect[regions],\n (unsigned long) size_vect[regions]);\n if (write(fd,logbuf,strlen(logbuf)) == -1) { /* Nothing to do. */ }\n regions++;\n }", " int errors = 0;\n for (j = 0; j < regions; j++) {\n if (write(fd,\".\",1) == -1) { /* Nothing to do. */ }\n errors += memtest_preserving_test((void*)start_vect[j],size_vect[j],1);\n if (write(fd, errors ? \"E\" : \"O\",1) == -1) { /* Nothing to do. */ }\n }\n if (write(fd,\"\\n\",1) == -1) { /* Nothing to do. */ }", " /* NOTE: It is very important to close the file descriptor only now\n * because closing it before may result into unmapping of some memory\n * region that we are testing. */\n fclose(fp);\n closeDirectLogFiledes(fd);\n return errors;\n}\n#endif /* HAVE_PROC_MAPS */", "static void killMainThread(void) {\n int err;\n if (pthread_self() != server.main_thread_id && pthread_cancel(server.main_thread_id) == 0) {\n if ((err = pthread_join(server.main_thread_id,NULL)) != 0) {\n serverLog(LL_WARNING, \"main thread can not be joined: %s\", strerror(err));\n } else {\n serverLog(LL_WARNING, \"main thread terminated\");\n }\n }\n}", "/* Kill the running threads (other than current) in an unclean way. This function\n * should be used only when it's critical to stop the threads for some reason.\n * Currently Redis does this only on crash (for instance on SIGSEGV) in order\n * to perform a fast memory check without other threads messing with memory. */\nvoid killThreads(void) {\n killMainThread();\n bioKillThreads();\n killIOThreads();\n}", "void doFastMemoryTest(void) {\n#if defined(HAVE_PROC_MAPS)\n if (server.memcheck_enabled) {\n /* Test memory */\n serverLogRaw(LL_WARNING|LL_RAW, \"\\n------ FAST MEMORY TEST ------\\n\");\n killThreads();\n if (memtest_test_linux_anonymous_maps()) {\n serverLogRaw(LL_WARNING|LL_RAW,\n \"!!! MEMORY ERROR DETECTED! Check your memory ASAP !!!\\n\");\n } else {\n serverLogRaw(LL_WARNING|LL_RAW,\n \"Fast memory test PASSED, however your memory can still be broken. Please run a memory test for several hours if possible.\\n\");\n }\n }\n#endif /* HAVE_PROC_MAPS */\n}", "/* Scans the (assumed) x86 code starting at addr, for a max of `len`\n * bytes, searching for E8 (callq) opcodes, and dumping the symbols\n * and the call offset if they appear to be valid. */\nvoid dumpX86Calls(void *addr, size_t len) {\n size_t j;\n unsigned char *p = addr;\n Dl_info info;\n /* Hash table to best-effort avoid printing the same symbol\n * multiple times. */\n unsigned long ht[256] = {0};", " if (len < 5) return;\n for (j = 0; j < len-4; j++) {\n if (p[j] != 0xE8) continue; /* Not an E8 CALL opcode. */\n unsigned long target = (unsigned long)addr+j+5;\n uint32_t tmp;\n memcpy(&tmp, p+j+1, sizeof(tmp));\n target += tmp;\n if (dladdr((void*)target, &info) != 0 && info.dli_sname != NULL) {\n if (ht[target&0xff] != target) {\n printf(\"Function at 0x%lx is %s\\n\",target,info.dli_sname);\n ht[target&0xff] = target;\n }\n j += 4; /* Skip the 32 bit immediate. */\n }\n }\n}", "void dumpCodeAroundEIP(void *eip) {\n Dl_info info;\n if (dladdr(eip, &info) != 0) {\n serverLog(LL_WARNING|LL_RAW,\n \"\\n------ DUMPING CODE AROUND EIP ------\\n\"\n \"Symbol: %s (base: %p)\\n\"\n \"Module: %s (base %p)\\n\"\n \"$ xxd -r -p /tmp/dump.hex /tmp/dump.bin\\n\"\n \"$ objdump --adjust-vma=%p -D -b binary -m i386:x86-64 /tmp/dump.bin\\n\"\n \"------\\n\",\n info.dli_sname, info.dli_saddr, info.dli_fname, info.dli_fbase,\n info.dli_saddr);\n size_t len = (long)eip - (long)info.dli_saddr;\n unsigned long sz = sysconf(_SC_PAGESIZE);\n if (len < 1<<13) { /* we don't have functions over 8k (verified) */\n /* Find the address of the next page, which is our \"safety\"\n * limit when dumping. Then try to dump just 128 bytes more\n * than EIP if there is room, or stop sooner. */\n void *base = (void *)info.dli_saddr;\n unsigned long next = ((unsigned long)eip + sz) & ~(sz-1);\n unsigned long end = (unsigned long)eip + 128;\n if (end > next) end = next;\n len = end - (unsigned long)base;\n serverLogHexDump(LL_WARNING, \"dump of function\",\n base, len);\n dumpX86Calls(base, len);\n }\n }\n}\n", "void invalidFunctionWasCalled() {}", "typedef void (*invalidFunctionWasCalledType)();\n", "void sigsegvHandler(int sig, siginfo_t *info, void *secret) {\n UNUSED(secret);\n UNUSED(info);", " bugReportStart();\n serverLog(LL_WARNING,\n \"Redis %s crashed by signal: %d, si_code: %d\", REDIS_VERSION, sig, info->si_code);\n if (sig == SIGSEGV || sig == SIGBUS) {\n serverLog(LL_WARNING,\n \"Accessing address: %p\", (void*)info->si_addr);\n }\n if (info->si_code == SI_USER && info->si_pid != -1) {\n serverLog(LL_WARNING, \"Killed by PID: %ld, UID: %d\", (long) info->si_pid, info->si_uid);\n }", "#ifdef HAVE_BACKTRACE\n ucontext_t *uc = (ucontext_t*) secret;", " void *eip = getAndSetMcontextEip(uc, NULL);", " if (eip != NULL) {\n serverLog(LL_WARNING,\n \"Crashed running the instruction at: %p\", eip);\n }\n", " if (eip == info->si_addr) {\n /* When eip matches the bad address, it's an indication that we crashed when calling a non-mapped\n * function pointer. In that case the call to backtrace will crash trying to access that address and we\n * won't get a crash report logged. Set it to a valid point to avoid that crash. */", " /* This trick allow to avoid compiler warning */\n void *ptr;\n invalidFunctionWasCalledType *ptr_ptr = (invalidFunctionWasCalledType*)&ptr;\n *ptr_ptr = invalidFunctionWasCalled;\n getAndSetMcontextEip(uc, ptr);\n }", " logStackTrace(eip, 1);", " if (eip == info->si_addr) {\n /* Restore old eip */\n getAndSetMcontextEip(uc, eip);\n }", "\n logRegisters(uc);\n#endif", " printCrashReport();", "#ifdef HAVE_BACKTRACE\n if (eip != NULL)\n dumpCodeAroundEIP(eip);\n#endif", " bugReportEnd(1, sig);\n}", "void printCrashReport(void) {\n /* Log INFO and CLIENT LIST */\n logServerInfo();", " /* Log the current client */\n logCurrentClient();", " /* Log modules info. Something we wanna do last since we fear it may crash. */\n logModulesInfo();", " /* Log debug config information, which are some values\n * which may be useful for debugging crashes. */\n logConfigDebugInfo();", " /* Run memory test in case the crash was triggered by memory corruption. */\n doFastMemoryTest();\n}", "void bugReportEnd(int killViaSignal, int sig) {\n struct sigaction act;", " serverLogRaw(LL_WARNING|LL_RAW,\n\"\\n=== REDIS BUG REPORT END. Make sure to include from START to END. ===\\n\\n\"\n\" Please report the crash by opening an issue on github:\\n\\n\"\n\" http://github.com/redis/redis/issues\\n\\n\"\n\" If a Redis module was involved, please open in the module's repo instead.\\n\\n\"\n\" Suspect RAM error? Use redis-server --test-memory to verify it.\\n\\n\"\n\" Some other issues could be detected by redis-server --check-system\\n\"\n);", " /* free(messages); Don't call free() with possibly corrupted memory. */\n if (server.daemonize && server.supervised == 0 && server.pidfile) unlink(server.pidfile);", " if (!killViaSignal) {\n /* To avoid issues with valgrind, we may wanna exit rahter than generate a signal */\n if (server.use_exit_on_panic) {\n /* Using _exit to bypass false leak reports by gcc ASAN */\n fflush(stdout);\n _exit(1);\n }\n abort();\n }", " /* Make sure we exit with the right signal at the end. So for instance\n * the core will be dumped if enabled. */\n sigemptyset (&act.sa_mask);\n act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;\n act.sa_handler = SIG_DFL;\n sigaction (sig, &act, NULL);\n kill(getpid(),sig);\n}", "/* ==================== Logging functions for debugging ===================== */", "void serverLogHexDump(int level, char *descr, void *value, size_t len) {\n char buf[65], *b;\n unsigned char *v = value;\n char charset[] = \"0123456789abcdef\";", " serverLog(level,\"%s (hexdump of %zu bytes):\", descr, len);\n b = buf;\n while(len) {\n b[0] = charset[(*v)>>4];\n b[1] = charset[(*v)&0xf];\n b[2] = '\\0';\n b += 2;\n len--;\n v++;\n if (b-buf == 64 || len == 0) {\n serverLogRaw(level|LL_RAW,buf);\n b = buf;\n }\n }\n serverLogRaw(level|LL_RAW,\"\\n\");\n}", "/* =========================== Software Watchdog ============================ */\n#include <sys/time.h>", "void watchdogSignalHandler(int sig, siginfo_t *info, void *secret) {\n#ifdef HAVE_BACKTRACE\n ucontext_t *uc = (ucontext_t*) secret;\n#else\n (void)secret;\n#endif\n UNUSED(info);\n UNUSED(sig);", " serverLogFromHandler(LL_WARNING,\"\\n--- WATCHDOG TIMER EXPIRED ---\");\n#ifdef HAVE_BACKTRACE", " logStackTrace(getAndSetMcontextEip(uc, NULL), 1);", "#else\n serverLogFromHandler(LL_WARNING,\"Sorry: no support for backtrace().\");\n#endif\n serverLogFromHandler(LL_WARNING,\"--------\\n\");\n}", "/* Schedule a SIGALRM delivery after the specified period in milliseconds.\n * If a timer is already scheduled, this function will re-schedule it to the\n * specified time. If period is 0 the current timer is disabled. */\nvoid watchdogScheduleSignal(int period) {\n struct itimerval it;", " /* Will stop the timer if period is 0. */\n it.it_value.tv_sec = period/1000;\n it.it_value.tv_usec = (period%1000)*1000;\n /* Don't automatically restart. */\n it.it_interval.tv_sec = 0;\n it.it_interval.tv_usec = 0;\n setitimer(ITIMER_REAL, &it, NULL);\n}\nvoid applyWatchdogPeriod() {\n struct sigaction act;", " /* Disable watchdog when period is 0 */\n if (server.watchdog_period == 0) {\n watchdogScheduleSignal(0); /* Stop the current timer. */", " /* Set the signal handler to SIG_IGN, this will also remove pending\n * signals from the queue. */\n sigemptyset(&act.sa_mask);\n act.sa_flags = 0;\n act.sa_handler = SIG_IGN;\n sigaction(SIGALRM, &act, NULL);\n } else {\n /* Setup the signal handler. */\n sigemptyset(&act.sa_mask);\n act.sa_flags = SA_SIGINFO;\n act.sa_sigaction = watchdogSignalHandler;\n sigaction(SIGALRM, &act, NULL);", " /* If the configured period is smaller than twice the timer period, it is\n * too short for the software watchdog to work reliably. Fix it now\n * if needed. */\n int min_period = (1000/server.hz)*2;\n if (server.watchdog_period < min_period) server.watchdog_period = min_period;\n watchdogScheduleSignal(server.watchdog_period); /* Adjust the current timer. */\n }\n}", "/* Positive input is sleep time in microseconds. Negative input is fractions\n * of microseconds, i.e. -10 means 100 nanoseconds. */\nvoid debugDelay(int usec) {\n /* Since even the shortest sleep results in context switch and system call,\n * the way we achieve short sleeps is by statistically sleeping less often. */\n if (usec < 0) usec = (rand() % -usec) == 0 ? 1: 0;\n if (usec) usleep(usec);\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 ]
PreciseBugs
{"buggy_code_end_loc": [2083], "buggy_code_start_loc": [1126], "filenames": ["src/debug.c"], "fixing_code_end_loc": [2119], "fixing_code_start_loc": [1126], "message": "** DISPUTED ** A vulnerability, which was classified as problematic, was found in Redis. Affected is the function sigsegvHandler of the file debug.c of the component Crash Report. The manipulation leads to denial of service. The real existence of this vulnerability is still doubted at the moment. The name of the patch is 0bf90d944313919eb8e63d3588bf63a367f020a3. It is recommended to apply a patch to fix this issue. VDB-211962 is the identifier assigned to this vulnerability. NOTE: The vendor claims that this is not a DoS because it applies to the crash logging mechanism which is triggered after a crash has occurred.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redis:redis:*:*:*:*:*:*:*:*", "matchCriteriaId": "1A9E9EB4-7E92-4672-B9C7-35C22F5D6B50", "versionEndExcluding": "2022-09-29", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "** DISPUTED ** A vulnerability, which was classified as problematic, was found in Redis. Affected is the function sigsegvHandler of the file debug.c of the component Crash Report. The manipulation leads to denial of service. The real existence of this vulnerability is still doubted at the moment. The name of the patch is 0bf90d944313919eb8e63d3588bf63a367f020a3. It is recommended to apply a patch to fix this issue. VDB-211962 is the identifier assigned to this vulnerability. NOTE: The vendor claims that this is not a DoS because it applies to the crash logging mechanism which is triggered after a crash has occurred."}, {"lang": "es", "value": "** EN DISPUTA ** Se ha encontrado una vulnerabilidad, clasificada como problem\u00e1tica, en Redis. La funci\u00f3n afectada es sigsegvHandler del archivo debug.c del componente Crash Report. La manipulaci\u00f3n conlleva a una denegaci\u00f3n de servicio. El nombre del parche es 0bf90d944313919eb8e63d3588bf63a367f020a3. Es recomendado aplicar un parche para corregir este problema. VDB-211962 es el identificador asignado a esta vulnerabilidad. NOTA: El proveedor afirma que esto no es un DoS porque se aplica al mecanismo de registro de fallos que se activa despu\u00e9s de que se haya producido un fallo"}], "evaluatorComment": null, "id": "CVE-2022-3647", "lastModified": "2022-11-29T16:22:24.607", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 3.3, "baseSeverity": "LOW", "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:L", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 3.1, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:A/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}]}, "published": "2022-10-21T18:15:10.183", "references": [{"source": "cna@vuldb.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/redis/redis/commit/0bf90d944313919eb8e63d3588bf63a367f020a3"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.211962"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-404"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/redis/redis/commit/0bf90d944313919eb8e63d3588bf63a367f020a3"}, "type": "CWE-404"}
239
Determine whether the {function_name} code is vulnerable or not.
[ "# Security Policy", "The development team and community take all security issues seriously. **Please do not make public any uncovered flaws.**", "## Reporting a Vulnerability", "Thank you for improving the security of our code! Any assistance in removing security flaws will be acknowledged.", "**Please report security flaws by emailing the development team directly: security@codeigniter.com**.", "The lead maintainer will acknowledge your email within 48 hours, and will send a more detailed response within 48 hours indicating\nthe next steps in handling your report. After the initial reply to your report, the security team will endeavor to keep you informed of the\nprogress towards a fix and full announcement, and may ask for additional information or guidance.", "## Disclosure Policy", "When the security team receives a security bug report, they will assign it to a primary handler.\nThis person will coordinate the fix and release process, involving the following steps:", "- Confirm the problem and determine the affected versions.\n- Audit code to find any potential similar problems.\n- Prepare fixes for all releases still under maintenance. These fixes will be released as fast as possible.", "", "\n## Comments on this Policy", "If you have suggestions on how this process could be improved please submit a Pull Request." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [22, 818, 313, 129, 10], "buggy_code_start_loc": [22, 813, 304, 110, 10], "filenames": ["SECURITY.md", "system/Common.php", "tests/system/CommonFunctionsTest.php", "tests/system/HTTP/IncomingRequestTest.php", "user_guide_src/source/changelogs/v4.1.6.rst"], "fixing_code_end_loc": [24, 812, 346, 131, 16], "fixing_code_start_loc": [23, 812, 304, 110, 11], "message": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codeigniter:codeigniter:*:*:*:*:*:*:*:*", "matchCriteriaId": "5E18B755-8CBA-45C9-8759-5039BBAD4FC6", "versionEndExcluding": "4.1.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`."}, {"lang": "es", "value": "CodeIgniter es un framework web full-stack de PHP de c\u00f3digo abierto. Se encontr\u00f3 una deserializaci\u00f3n de datos no confiables en la funci\u00f3n \"old()\" en CodeIgniter4. Los atacantes remotos pueden inyectar objetos arbitrarios autocargables con esta vulnerabilidad, y posiblemente ejecutar c\u00f3digo PHP existente en el servidor. Tenemos conocimiento de una explotaci\u00f3n que funciona, que puede conllevar a una inyecci\u00f3n SQL. Se aconseja a usuarios que actualicen a la versi\u00f3n 4.1.6 o posterior. A los usuarios que no puedan actualizarse se les aconseja no usar la funci\u00f3n \"old()\" y form_helper ni \"RedirectResponse::withInput()\" y \"redirect()-&gt;withInput()\""}], "evaluatorComment": null, "id": "CVE-2022-21647", "lastModified": "2022-01-20T15:04:23.823", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.7, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-01-04T20:15:07.930", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-w6jr-wj64-mc9x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-502"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, "type": "CWE-502"}
240
Determine whether the {function_name} code is vulnerable or not.
[ "# Security Policy", "The development team and community take all security issues seriously. **Please do not make public any uncovered flaws.**", "## Reporting a Vulnerability", "Thank you for improving the security of our code! Any assistance in removing security flaws will be acknowledged.", "**Please report security flaws by emailing the development team directly: security@codeigniter.com**.", "The lead maintainer will acknowledge your email within 48 hours, and will send a more detailed response within 48 hours indicating\nthe next steps in handling your report. After the initial reply to your report, the security team will endeavor to keep you informed of the\nprogress towards a fix and full announcement, and may ask for additional information or guidance.", "## Disclosure Policy", "When the security team receives a security bug report, they will assign it to a primary handler.\nThis person will coordinate the fix and release process, involving the following steps:", "- Confirm the problem and determine the affected versions.\n- Audit code to find any potential similar problems.\n- Prepare fixes for all releases still under maintenance. These fixes will be released as fast as possible.", "- Publish security advisories at https://github.com/codeigniter4/CodeIgniter4/security/advisories", "\n## Comments on this Policy", "If you have suggestions on how this process could be improved please submit a Pull Request." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [22, 818, 313, 129, 10], "buggy_code_start_loc": [22, 813, 304, 110, 10], "filenames": ["SECURITY.md", "system/Common.php", "tests/system/CommonFunctionsTest.php", "tests/system/HTTP/IncomingRequestTest.php", "user_guide_src/source/changelogs/v4.1.6.rst"], "fixing_code_end_loc": [24, 812, 346, 131, 16], "fixing_code_start_loc": [23, 812, 304, 110, 11], "message": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codeigniter:codeigniter:*:*:*:*:*:*:*:*", "matchCriteriaId": "5E18B755-8CBA-45C9-8759-5039BBAD4FC6", "versionEndExcluding": "4.1.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`."}, {"lang": "es", "value": "CodeIgniter es un framework web full-stack de PHP de c\u00f3digo abierto. Se encontr\u00f3 una deserializaci\u00f3n de datos no confiables en la funci\u00f3n \"old()\" en CodeIgniter4. Los atacantes remotos pueden inyectar objetos arbitrarios autocargables con esta vulnerabilidad, y posiblemente ejecutar c\u00f3digo PHP existente en el servidor. Tenemos conocimiento de una explotaci\u00f3n que funciona, que puede conllevar a una inyecci\u00f3n SQL. Se aconseja a usuarios que actualicen a la versi\u00f3n 4.1.6 o posterior. A los usuarios que no puedan actualizarse se les aconseja no usar la funci\u00f3n \"old()\" y form_helper ni \"RedirectResponse::withInput()\" y \"redirect()-&gt;withInput()\""}], "evaluatorComment": null, "id": "CVE-2022-21647", "lastModified": "2022-01-20T15:04:23.823", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.7, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-01-04T20:15:07.930", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-w6jr-wj64-mc9x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-502"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, "type": "CWE-502"}
240
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * This file is part of CodeIgniter 4 framework.\n *\n * (c) CodeIgniter Foundation <admin@codeigniter.com>\n *\n * For the full copyright and license information, please view\n * the LICENSE file that was distributed with this source code.\n */", "use CodeIgniter\\Cache\\CacheInterface;\nuse CodeIgniter\\Config\\Factories;\nuse CodeIgniter\\Cookie\\Cookie;\nuse CodeIgniter\\Cookie\\CookieStore;\nuse CodeIgniter\\Cookie\\Exceptions\\CookieException;\nuse CodeIgniter\\Database\\BaseConnection;\nuse CodeIgniter\\Database\\ConnectionInterface;\nuse CodeIgniter\\Debug\\Timer;\nuse CodeIgniter\\Files\\Exceptions\\FileNotFoundException;\nuse CodeIgniter\\HTTP\\Exceptions\\HTTPException;\nuse CodeIgniter\\HTTP\\RedirectResponse;\nuse CodeIgniter\\HTTP\\RequestInterface;\nuse CodeIgniter\\HTTP\\ResponseInterface;\nuse CodeIgniter\\HTTP\\URI;\nuse CodeIgniter\\Model;\nuse CodeIgniter\\Session\\Session;\nuse CodeIgniter\\Test\\TestLogger;\nuse Config\\App;\nuse Config\\Database;\nuse Config\\Logger;\nuse Config\\Services;\nuse Config\\View;\nuse Laminas\\Escaper\\Escaper;", "// Services Convenience Functions", "if (! function_exists('app_timezone')) {\n /**\n * Returns the timezone the application has been set to display\n * dates in. This might be different than the timezone set\n * at the server level, as you often want to stores dates in UTC\n * and convert them on the fly for the user.\n */\n function app_timezone(): string\n {\n $config = config(App::class);", " return $config->appTimezone;\n }\n}", "if (! function_exists('cache')) {\n /**\n * A convenience method that provides access to the Cache\n * object. If no parameter is provided, will return the object,\n * otherwise, will attempt to return the cached value.\n *\n * Examples:\n * cache()->save('foo', 'bar');\n * $foo = cache('bar');\n *\n * @return CacheInterface|mixed\n */\n function cache(?string $key = null)\n {\n $cache = Services::cache();", " // No params - return cache object\n if ($key === null) {\n return $cache;\n }", " // Still here? Retrieve the value.\n return $cache->get($key);\n }\n}", "if (! function_exists('clean_path')) {\n /**\n * A convenience method to clean paths for\n * a nicer looking output. Useful for exception\n * handling, error logging, etc.\n */\n function clean_path(string $path): string\n {\n // Resolve relative paths\n $path = realpath($path) ?: $path;", " switch (true) {\n case strpos($path, APPPATH) === 0:\n return 'APPPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(APPPATH));", " case strpos($path, SYSTEMPATH) === 0:\n return 'SYSTEMPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(SYSTEMPATH));", " case strpos($path, FCPATH) === 0:\n return 'FCPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(FCPATH));", " case defined('VENDORPATH') && strpos($path, VENDORPATH) === 0:\n return 'VENDORPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(VENDORPATH));", " case strpos($path, ROOTPATH) === 0:\n return 'ROOTPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(ROOTPATH));", " default:\n return $path;\n }\n }\n}", "if (! function_exists('command')) {\n /**\n * Runs a single command.\n * Input expected in a single string as would\n * be used on the command line itself:\n *\n * > command('migrate:create SomeMigration');\n *\n * @return false|string\n */\n function command(string $command)\n {\n $runner = service('commands');\n $regexString = '([^\\s]+?)(?:\\s|(?<!\\\\\\\\)\"|(?<!\\\\\\\\)\\'|$)';\n $regexQuoted = '(?:\"([^\"\\\\\\\\]*(?:\\\\\\\\.[^\"\\\\\\\\]*)*)\"|\\'([^\\'\\\\\\\\]*(?:\\\\\\\\.[^\\'\\\\\\\\]*)*)\\')';", " $args = [];\n $length = strlen($command);\n $cursor = 0;", " /**\n * Adopted from Symfony's `StringInput::tokenize()` with few changes.\n *\n * @see https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Console/Input/StringInput.php\n */\n while ($cursor < $length) {\n if (preg_match('/\\s+/A', $command, $match, 0, $cursor)) {\n // nothing to do\n } elseif (preg_match('/' . $regexQuoted . '/A', $command, $match, 0, $cursor)) {\n $args[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));\n } elseif (preg_match('/' . $regexString . '/A', $command, $match, 0, $cursor)) {\n $args[] = stripcslashes($match[1]);\n } else {\n // @codeCoverageIgnoreStart\n throw new InvalidArgumentException(sprintf('Unable to parse input near \"... %s ...\".', substr($command, $cursor, 10)));\n // @codeCoverageIgnoreEnd\n }", " $cursor += strlen($match[0]);\n }", " $command = array_shift($args);\n $params = [];\n $optionValue = false;", " foreach ($args as $i => $arg) {\n if (mb_strpos($arg, '-') !== 0) {\n if ($optionValue) {\n // if this was an option value, it was already\n // included in the previous iteration\n $optionValue = false;\n } else {\n // add to segments if not starting with '-'\n // and not an option value\n $params[] = $arg;\n }", " continue;\n }", " $arg = ltrim($arg, '-');\n $value = null;", " if (isset($args[$i + 1]) && mb_strpos($args[$i + 1], '-') !== 0) {\n $value = $args[$i + 1];\n $optionValue = true;\n }", " $params[$arg] = $value;\n }", " ob_start();\n $runner->run($command, $params);", " return ob_get_clean();\n }\n}", "if (! function_exists('config')) {\n /**\n * More simple way of getting config instances from Factories\n *\n * @return mixed\n */\n function config(string $name, bool $getShared = true)\n {\n return Factories::config($name, ['getShared' => $getShared]);\n }\n}", "if (! function_exists('cookie')) {\n /**\n * Simpler way to create a new Cookie instance.\n *\n * @param string $name Name of the cookie\n * @param string $value Value of the cookie\n * @param array $options Array of options to be passed to the cookie\n *\n * @throws CookieException\n */\n function cookie(string $name, string $value = '', array $options = []): Cookie\n {\n return new Cookie($name, $value, $options);\n }\n}", "if (! function_exists('cookies')) {\n /**\n * Fetches the global `CookieStore` instance held by `Response`.\n *\n * @param Cookie[] $cookies If `getGlobal` is false, this is passed to CookieStore's constructor\n * @param bool $getGlobal If false, creates a new instance of CookieStore\n */\n function cookies(array $cookies = [], bool $getGlobal = true): CookieStore\n {\n if ($getGlobal) {\n return Services::response()->getCookieStore();\n }", " return new CookieStore($cookies);\n }\n}", "if (! function_exists('csrf_token')) {\n /**\n * Returns the CSRF token name.\n * Can be used in Views when building hidden inputs manually,\n * or used in javascript vars when using APIs.\n */\n function csrf_token(): string\n {\n return Services::security()->getTokenName();\n }\n}", "if (! function_exists('csrf_header')) {\n /**\n * Returns the CSRF header name.\n * Can be used in Views by adding it to the meta tag\n * or used in javascript to define a header name when using APIs.\n */\n function csrf_header(): string\n {\n return Services::security()->getHeaderName();\n }\n}", "if (! function_exists('csrf_hash')) {\n /**\n * Returns the current hash value for the CSRF protection.\n * Can be used in Views when building hidden inputs manually,\n * or used in javascript vars for API usage.\n */\n function csrf_hash(): string\n {\n return Services::security()->getHash();\n }\n}", "if (! function_exists('csrf_field')) {\n /**\n * Generates a hidden input field for use within manually generated forms.\n */\n function csrf_field(?string $id = null): string\n {\n return '<input type=\"hidden\"' . (! empty($id) ? ' id=\"' . esc($id, 'attr') . '\"' : '') . ' name=\"' . csrf_token() . '\" value=\"' . csrf_hash() . '\" />';\n }\n}", "if (! function_exists('csrf_meta')) {\n /**\n * Generates a meta tag for use within javascript calls.\n */\n function csrf_meta(?string $id = null): string\n {\n return '<meta' . (! empty($id) ? ' id=\"' . esc($id, 'attr') . '\"' : '') . ' name=\"' . csrf_header() . '\" content=\"' . csrf_hash() . '\" />';\n }\n}", "if (! function_exists('db_connect')) {\n /**\n * Grabs a database connection and returns it to the user.\n *\n * This is a convenience wrapper for \\Config\\Database::connect()\n * and supports the same parameters. Namely:\n *\n * When passing in $db, you may pass any of the following to connect:\n * - group name\n * - existing connection instance\n * - array of database configuration values\n *\n * If $getShared === false then a new connection instance will be provided,\n * otherwise it will all calls will return the same instance.\n *\n * @param array|ConnectionInterface|string|null $db\n *\n * @return BaseConnection\n */\n function db_connect($db = null, bool $getShared = true)\n {\n return Database::connect($db, $getShared);\n }\n}", "if (! function_exists('dd')) {\n /**\n * Prints a Kint debug report and exits.\n *\n * @param array ...$vars\n *\n * @codeCoverageIgnore Can't be tested ... exits\n */\n function dd(...$vars)\n {\n // @codeCoverageIgnoreStart\n Kint::$aliases[] = 'dd';\n Kint::dump(...$vars);", " exit;\n // @codeCoverageIgnoreEnd\n }\n}", "if (! function_exists('env')) {\n /**\n * Allows user to retrieve values from the environment\n * variables that have been set. Especially useful for\n * retrieving values set from the .env file for\n * use in config files.\n *\n * @param string|null $default\n *\n * @return mixed\n */\n function env(string $key, $default = null)\n {\n $value = $_ENV[$key] ?? $_SERVER[$key] ?? getenv($key);", " // Not found? Return the default value\n if ($value === false) {\n return $default;\n }", " // Handle any boolean values\n switch (strtolower($value)) {\n case 'true':\n return true;", " case 'false':\n return false;", " case 'empty':\n return '';", " case 'null':\n return null;\n }", " return $value;\n }\n}", "if (! function_exists('esc')) {\n /**\n * Performs simple auto-escaping of data for security reasons.\n * Might consider making this more complex at a later date.\n *\n * If $data is a string, then it simply escapes and returns it.\n * If $data is an array, then it loops over it, escaping each\n * 'value' of the key/value pairs.\n *\n * Valid context values: html, js, css, url, attr, raw\n *\n * @param array|string $data\n * @param string $encoding\n *\n * @throws InvalidArgumentException\n *\n * @return array|string\n */\n function esc($data, string $context = 'html', ?string $encoding = null)\n {\n if (is_array($data)) {\n foreach ($data as &$value) {\n $value = esc($value, $context);\n }\n }", " if (is_string($data)) {\n $context = strtolower($context);", " // Provide a way to NOT escape data since\n // this could be called automatically by\n // the View library.\n if (empty($context) || $context === 'raw') {\n return $data;\n }", " if (! in_array($context, ['html', 'js', 'css', 'url', 'attr'], true)) {\n throw new InvalidArgumentException('Invalid escape context provided.');\n }", " $method = $context === 'attr' ? 'escapeHtmlAttr' : 'escape' . ucfirst($context);", " static $escaper;\n if (! $escaper) {\n $escaper = new Escaper($encoding);\n }", " if ($encoding && $escaper->getEncoding() !== $encoding) {\n $escaper = new Escaper($encoding);\n }", " $data = $escaper->{$method}($data);\n }", " return $data;\n }\n}", "if (! function_exists('force_https')) {\n /**\n * Used to force a page to be accessed in via HTTPS.\n * Uses a standard redirect, plus will set the HSTS header\n * for modern browsers that support, which gives best\n * protection against man-in-the-middle attacks.\n *\n * @see https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security\n *\n * @param int $duration How long should the SSL header be set for? (in seconds)\n * Defaults to 1 year.\n * @param RequestInterface $request\n * @param ResponseInterface $response\n *\n * @throws HTTPException\n */\n function force_https(int $duration = 31536000, ?RequestInterface $request = null, ?ResponseInterface $response = null)\n {\n if ($request === null) {\n $request = Services::request(null, true);\n }\n if ($response === null) {\n $response = Services::response(null, true);\n }", " if ((ENVIRONMENT !== 'testing' && (is_cli() || $request->isSecure())) || (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'test')) {\n // @codeCoverageIgnoreStart\n return;\n // @codeCoverageIgnoreEnd\n }", " // If the session status is active, we should regenerate\n // the session ID for safety sake.\n if (ENVIRONMENT !== 'testing' && session_status() === PHP_SESSION_ACTIVE) {\n // @codeCoverageIgnoreStart\n Services::session(null, true)\n ->regenerate();\n // @codeCoverageIgnoreEnd\n }", " $baseURL = config(App::class)->baseURL;", " if (strpos($baseURL, 'https://') === 0) {\n $baseURL = substr($baseURL, strlen('https://'));\n } elseif (strpos($baseURL, 'http://') === 0) {\n $baseURL = substr($baseURL, strlen('http://'));\n }", " $uri = URI::createURIString(\n 'https',\n $baseURL,\n $request->getUri()->getPath(), // Absolute URIs should use a \"/\" for an empty path\n $request->getUri()->getQuery(),\n $request->getUri()->getFragment()\n );", " // Set an HSTS header\n $response->setHeader('Strict-Transport-Security', 'max-age=' . $duration);\n $response->redirect($uri);\n $response->sendHeaders();", " if (ENVIRONMENT !== 'testing') {\n // @codeCoverageIgnoreStart\n exit();\n // @codeCoverageIgnoreEnd\n }\n }\n}", "if (! function_exists('function_usable')) {\n /**\n * Function usable\n *\n * Executes a function_exists() check, and if the Suhosin PHP\n * extension is loaded - checks whether the function that is\n * checked might be disabled in there as well.\n *\n * This is useful as function_exists() will return FALSE for\n * functions disabled via the *disable_functions* php.ini\n * setting, but not for *suhosin.executor.func.blacklist* and\n * *suhosin.executor.disable_eval*. These settings will just\n * terminate script execution if a disabled function is executed.\n *\n * The above described behavior turned out to be a bug in Suhosin,\n * but even though a fix was committed for 0.9.34 on 2012-02-12,\n * that version is yet to be released. This function will therefore\n * be just temporary, but would probably be kept for a few years.\n *\n * @see http://www.hardened-php.net/suhosin/\n *\n * @param string $functionName Function to check for\n *\n * @return bool TRUE if the function exists and is safe to call,\n * FALSE otherwise.\n *\n * @codeCoverageIgnore This is too exotic\n */\n function function_usable(string $functionName): bool\n {\n static $_suhosin_func_blacklist;", " if (function_exists($functionName)) {\n if (! isset($_suhosin_func_blacklist)) {\n $_suhosin_func_blacklist = extension_loaded('suhosin') ? explode(',', trim(ini_get('suhosin.executor.func.blacklist'))) : [];\n }", " return ! in_array($functionName, $_suhosin_func_blacklist, true);\n }", " return false;\n }\n}", "if (! function_exists('helper')) {\n /**\n * Loads a helper file into memory. Supports namespaced helpers,\n * both in and out of the 'helpers' directory of a namespaced directory.\n *\n * Will load ALL helpers of the matching name, in the following order:\n * 1. app/Helpers\n * 2. {namespace}/Helpers\n * 3. system/Helpers\n *\n * @param array|string $filenames\n *\n * @throws FileNotFoundException\n */\n function helper($filenames)\n {\n static $loaded = [];", " $loader = Services::locator();", " if (! is_array($filenames)) {\n $filenames = [$filenames];\n }", " // Store a list of all files to include...\n $includes = [];", " foreach ($filenames as $filename) {\n // Store our system and application helper\n // versions so that we can control the load ordering.\n $systemHelper = null;\n $appHelper = null;\n $localIncludes = [];", " if (strpos($filename, '_helper') === false) {\n $filename .= '_helper';\n }", " // Check if this helper has already been loaded\n if (in_array($filename, $loaded, true)) {\n continue;\n }", " // If the file is namespaced, we'll just grab that\n // file and not search for any others\n if (strpos($filename, '\\\\') !== false) {\n $path = $loader->locateFile($filename, 'Helpers');", " if (empty($path)) {\n throw FileNotFoundException::forFileNotFound($filename);\n }", " $includes[] = $path;\n $loaded[] = $filename;\n } else {\n // No namespaces, so search in all available locations\n $paths = $loader->search('Helpers/' . $filename);", " foreach ($paths as $path) {\n if (strpos($path, APPPATH . 'Helpers' . DIRECTORY_SEPARATOR) === 0) {\n $appHelper = $path;\n } elseif (strpos($path, SYSTEMPATH . 'Helpers' . DIRECTORY_SEPARATOR) === 0) {\n $systemHelper = $path;\n } else {\n $localIncludes[] = $path;\n $loaded[] = $filename;\n }\n }", " // App-level helpers should override all others\n if (! empty($appHelper)) {\n $includes[] = $appHelper;\n $loaded[] = $filename;\n }", " // All namespaced files get added in next\n $includes = array_merge($includes, $localIncludes);", " // And the system default one should be added in last.\n if (! empty($systemHelper)) {\n $includes[] = $systemHelper;\n $loaded[] = $filename;\n }\n }\n }", " // Now actually include all of the files\n foreach ($includes as $path) {\n include_once $path;\n }\n }\n}", "if (! function_exists('is_cli')) {\n /**\n * Check if PHP was invoked from the command line.\n *\n * @codeCoverageIgnore Cannot be tested fully as PHPUnit always run in php-cli\n */\n function is_cli(): bool\n {\n if (in_array(PHP_SAPI, ['cli', 'phpdbg'], true)) {\n return true;\n }", " // PHP_SAPI could be 'cgi-fcgi', 'fpm-fcgi'.\n // See https://github.com/codeigniter4/CodeIgniter4/pull/5393\n return ! isset($_SERVER['REMOTE_ADDR']) && ! isset($_SERVER['REQUEST_METHOD']);\n }\n}", "if (! function_exists('is_really_writable')) {\n /**\n * Tests for file writability\n *\n * is_writable() returns TRUE on Windows servers when you really can't write to\n * the file, based on the read-only attribute. is_writable() is also unreliable\n * on Unix servers if safe_mode is on.\n *\n * @see https://bugs.php.net/bug.php?id=54709\n *\n * @throws Exception\n *\n * @codeCoverageIgnore Not practical to test, as travis runs on linux\n */\n function is_really_writable(string $file): bool\n {\n // If we're on a Unix server we call is_writable\n if (DIRECTORY_SEPARATOR === '/') {\n return is_writable($file);\n }", " /* For Windows servers and safe_mode \"on\" installations we'll actually\n * write a file then read it. Bah...\n */\n if (is_dir($file)) {\n $file = rtrim($file, '/') . '/' . bin2hex(random_bytes(16));\n if (($fp = @fopen($file, 'ab')) === false) {\n return false;\n }", " fclose($fp);\n @chmod($file, 0777);\n @unlink($file);", " return true;\n }", " if (! is_file($file) || ($fp = @fopen($file, 'ab')) === false) {\n return false;\n }", " fclose($fp);", " return true;\n }\n}", "if (! function_exists('lang')) {\n /**\n * A convenience method to translate a string or array of them and format\n * the result with the intl extension's MessageFormatter.\n *\n * @return string\n */\n function lang(string $line, array $args = [], ?string $locale = null)\n {\n $language = Services::language();", " // Get active locale\n $activeLocale = $language->getLocale();", " if ($locale && $locale !== $activeLocale) {\n $language->setLocale($locale);\n }", " $line = $language->getLine($line, $args);", " if ($locale && $locale !== $activeLocale) {\n // Reset to active locale\n $language->setLocale($activeLocale);\n }", " return $line;\n }\n}", "if (! function_exists('log_message')) {\n /**\n * A convenience/compatibility method for logging events through\n * the Log system.\n *\n * Allowed log levels are:\n * - emergency\n * - alert\n * - critical\n * - error\n * - warning\n * - notice\n * - info\n * - debug\n *\n * @return mixed\n */\n function log_message(string $level, string $message, array $context = [])\n {\n // When running tests, we want to always ensure that the\n // TestLogger is running, which provides utilities for\n // for asserting that logs were called in the test code.\n if (ENVIRONMENT === 'testing') {\n $logger = new TestLogger(new Logger());", " return $logger->log($level, $message, $context);\n }", " // @codeCoverageIgnoreStart\n return Services::logger(true)\n ->log($level, $message, $context);\n // @codeCoverageIgnoreEnd\n }\n}", "if (! function_exists('model')) {\n /**\n * More simple way of getting model instances from Factories\n *\n * @template T of Model\n *\n * @param class-string<T> $name\n *\n * @return T\n * @phpstan-return Model\n */\n function model(string $name, bool $getShared = true, ?ConnectionInterface &$conn = null)\n {\n return Factories::models($name, ['getShared' => $getShared], $conn);\n }\n}", "if (! function_exists('old')) {\n /**\n * Provides access to \"old input\" that was set in the session\n * during a redirect()->withInput().\n *\n * @param null $default\n * @param bool|string $escape\n *\n * @return mixed|null\n */\n function old(string $key, $default = null, $escape = 'html')\n {\n // Ensure the session is loaded\n if (session_status() === PHP_SESSION_NONE && ENVIRONMENT !== 'testing') {\n // @codeCoverageIgnoreStart\n session();\n // @codeCoverageIgnoreEnd\n }", " $request = Services::request();", " $value = $request->getOldInput($key);", " // Return the default value if nothing\n // found in the old input.\n if ($value === null) {\n return $default;\n }\n", " // If the result was serialized array or string, then unserialize it for use...\n if (is_string($value) && (strpos($value, 'a:') === 0 || strpos($value, 's:') === 0)) {\n $value = unserialize($value);\n }\n", " return $escape === false ? $value : esc($value, $escape);\n }\n}", "if (! function_exists('redirect')) {\n /**\n * Convenience method that works with the current global $request and\n * $router instances to redirect using named/reverse-routed routes\n * to determine the URL to go to.\n *\n * If more control is needed, you must use $response->redirect explicitly.\n *\n * @param string $route\n */\n function redirect(?string $route = null): RedirectResponse\n {\n $response = Services::redirectresponse(null, true);", " if (! empty($route)) {\n return $response->route($route);\n }", " return $response;\n }\n}", "if (! function_exists('remove_invisible_characters')) {\n /**\n * Remove Invisible Characters\n *\n * This prevents sandwiching null characters\n * between ascii characters, like Java\\0script.\n */\n function remove_invisible_characters(string $str, bool $urlEncoded = true): string\n {\n $nonDisplayables = [];", " // every control character except newline (dec 10),\n // carriage return (dec 13) and horizontal tab (dec 09)\n if ($urlEncoded) {\n $nonDisplayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15\n $nonDisplayables[] = '/%1[0-9a-f]/'; // url encoded 16-31\n }", " $nonDisplayables[] = '/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]+/S'; // 00-08, 11, 12, 14-31, 127", " do {\n $str = preg_replace($nonDisplayables, '', $str, -1, $count);\n } while ($count);", " return $str;\n }\n}", "if (! function_exists('route_to')) {\n /**\n * Given a controller/method string and any params,\n * will attempt to build the relative URL to the\n * matching route.\n *\n * NOTE: This requires the controller/method to\n * have a route defined in the routes Config file.\n *\n * @param mixed ...$params\n *\n * @return false|string\n */\n function route_to(string $method, ...$params)\n {\n return Services::routes()->reverseRoute($method, ...$params);\n }\n}", "if (! function_exists('session')) {\n /**\n * A convenience method for accessing the session instance,\n * or an item that has been set in the session.\n *\n * Examples:\n * session()->set('foo', 'bar');\n * $foo = session('bar');\n *\n * @param string $val\n *\n * @return mixed|Session|null\n */\n function session(?string $val = null)\n {\n $session = Services::session();", " // Returning a single item?\n if (is_string($val)) {\n return $session->get($val);\n }", " return $session;\n }\n}", "if (! function_exists('service')) {\n /**\n * Allows cleaner access to the Services Config file.\n * Always returns a SHARED instance of the class, so\n * calling the function multiple times should always\n * return the same instance.\n *\n * These are equal:\n * - $timer = service('timer')\n * - $timer = \\CodeIgniter\\Config\\Services::timer();\n *\n * @param mixed ...$params\n *\n * @return mixed\n */\n function service(string $name, ...$params)\n {\n return Services::$name(...$params);\n }\n}", "if (! function_exists('single_service')) {\n /**\n * Always returns a new instance of the class.\n *\n * @param mixed ...$params\n *\n * @return mixed\n */\n function single_service(string $name, ...$params)\n {\n $service = Services::serviceExists($name);", " if ($service === null) {\n // The service is not defined anywhere so just return.\n return null;\n }", " $method = new ReflectionMethod($service, $name);\n $count = $method->getNumberOfParameters();\n $mParam = $method->getParameters();\n $params = $params ?? [];", " if ($count === 1) {\n // This service needs only one argument, which is the shared\n // instance flag, so let's wrap up and pass false here.\n return $service::$name(false);\n }", " // Fill in the params with the defaults, but stop before the last\n for ($startIndex = count($params); $startIndex <= $count - 2; $startIndex++) {\n $params[$startIndex] = $mParam[$startIndex]->getDefaultValue();\n }", " // Ensure the last argument will not create a shared instance\n $params[$count - 1] = false;", " return $service::$name(...$params);\n }\n}", "if (! function_exists('slash_item')) {\n // Unlike CI3, this function is placed here because\n // it's not a config, or part of a config.\n /**\n * Fetch a config file item with slash appended (if not empty)\n *\n * @param string $item Config item name\n *\n * @return string|null The configuration item or NULL if\n * the item doesn't exist\n */\n function slash_item(string $item): ?string\n {\n $config = config(App::class);\n $configItem = $config->{$item};", " if (! isset($configItem) || empty(trim($configItem))) {\n return $configItem;\n }", " return rtrim($configItem, '/') . '/';\n }\n}", "if (! function_exists('stringify_attributes')) {\n /**\n * Stringify attributes for use in HTML tags.\n *\n * Helper function used to convert a string, array, or object\n * of attributes to a string.\n *\n * @param mixed $attributes string, array, object\n */\n function stringify_attributes($attributes, bool $js = false): string\n {\n $atts = '';", " if (empty($attributes)) {\n return $atts;\n }", " if (is_string($attributes)) {\n return ' ' . $attributes;\n }", " $attributes = (array) $attributes;", " foreach ($attributes as $key => $val) {\n $atts .= ($js) ? $key . '=' . esc($val, 'js') . ',' : ' ' . $key . '=\"' . esc($val) . '\"';\n }", " return rtrim($atts, ',');\n }\n}", "if (! function_exists('timer')) {\n /**\n * A convenience method for working with the timer.\n * If no parameter is passed, it will return the timer instance,\n * otherwise will start or stop the timer intelligently.\n *\n * @return mixed|Timer\n */\n function timer(?string $name = null)\n {\n $timer = Services::timer();", " if (empty($name)) {\n return $timer;\n }", " if ($timer->has($name)) {\n return $timer->stop($name);\n }", " return $timer->start($name);\n }\n}", "if (! function_exists('trace')) {\n /**\n * Provides a backtrace to the current execution point, from Kint.\n */\n function trace()\n {\n Kint::$aliases[] = 'trace';\n Kint::trace();\n }\n}", "if (! function_exists('view')) {\n /**\n * Grabs the current RendererInterface-compatible class\n * and tells it to render the specified view. Simply provides\n * a convenience method that can be used in Controllers,\n * libraries, and routed closures.\n *\n * NOTE: Does not provide any escaping of the data, so that must\n * all be handled manually by the developer.\n *\n * @param array $options Unused - reserved for third-party extensions.\n */\n function view(string $name, array $data = [], array $options = []): string\n {\n /**\n * @var CodeIgniter\\View\\View $renderer\n */\n $renderer = Services::renderer();", " $saveData = config(View::class)->saveData;", " if (array_key_exists('saveData', $options)) {\n $saveData = (bool) $options['saveData'];\n unset($options['saveData']);\n }", " return $renderer->setData($data, 'raw')->render($name, $options, $saveData);\n }\n}", "if (! function_exists('view_cell')) {\n /**\n * View cells are used within views to insert HTML chunks that are managed\n * by other classes.\n *\n * @param null $params\n *\n * @throws ReflectionException\n */\n function view_cell(string $library, $params = null, int $ttl = 0, ?string $cacheName = null): string\n {\n return Services::viewcell()\n ->render($library, $params, $ttl, $cacheName);\n }\n}", "/**\n * These helpers come from Laravel so will not be\n * re-tested and can be ignored safely.\n *\n * @see https://github.com/laravel/framework/blob/8.x/src/Illuminate/Support/helpers.php\n */\nif (! function_exists('class_basename')) {\n /**\n * Get the class \"basename\" of the given object / class.\n *\n * @param object|string $class\n *\n * @return string\n *\n * @codeCoverageIgnore\n */\n function class_basename($class)\n {\n $class = is_object($class) ? get_class($class) : $class;", " return basename(str_replace('\\\\', '/', $class));\n }\n}", "if (! function_exists('class_uses_recursive')) {\n /**\n * Returns all traits used by a class, its parent classes and trait of their traits.\n *\n * @param object|string $class\n *\n * @return array\n *\n * @codeCoverageIgnore\n */\n function class_uses_recursive($class)\n {\n if (is_object($class)) {\n $class = get_class($class);\n }", " $results = [];", " foreach (array_reverse(class_parents($class)) + [$class => $class] as $class) {\n $results += trait_uses_recursive($class);\n }", " return array_unique($results);\n }\n}", "if (! function_exists('trait_uses_recursive')) {\n /**\n * Returns all traits used by a trait and its traits.\n *\n * @param string $trait\n *\n * @return array\n *\n * @codeCoverageIgnore\n */\n function trait_uses_recursive($trait)\n {\n $traits = class_uses($trait) ?: [];", " foreach ($traits as $trait) {\n $traits += trait_uses_recursive($trait);\n }", " return $traits;\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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [22, 818, 313, 129, 10], "buggy_code_start_loc": [22, 813, 304, 110, 10], "filenames": ["SECURITY.md", "system/Common.php", "tests/system/CommonFunctionsTest.php", "tests/system/HTTP/IncomingRequestTest.php", "user_guide_src/source/changelogs/v4.1.6.rst"], "fixing_code_end_loc": [24, 812, 346, 131, 16], "fixing_code_start_loc": [23, 812, 304, 110, 11], "message": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codeigniter:codeigniter:*:*:*:*:*:*:*:*", "matchCriteriaId": "5E18B755-8CBA-45C9-8759-5039BBAD4FC6", "versionEndExcluding": "4.1.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`."}, {"lang": "es", "value": "CodeIgniter es un framework web full-stack de PHP de c\u00f3digo abierto. Se encontr\u00f3 una deserializaci\u00f3n de datos no confiables en la funci\u00f3n \"old()\" en CodeIgniter4. Los atacantes remotos pueden inyectar objetos arbitrarios autocargables con esta vulnerabilidad, y posiblemente ejecutar c\u00f3digo PHP existente en el servidor. Tenemos conocimiento de una explotaci\u00f3n que funciona, que puede conllevar a una inyecci\u00f3n SQL. Se aconseja a usuarios que actualicen a la versi\u00f3n 4.1.6 o posterior. A los usuarios que no puedan actualizarse se les aconseja no usar la funci\u00f3n \"old()\" y form_helper ni \"RedirectResponse::withInput()\" y \"redirect()-&gt;withInput()\""}], "evaluatorComment": null, "id": "CVE-2022-21647", "lastModified": "2022-01-20T15:04:23.823", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.7, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-01-04T20:15:07.930", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-w6jr-wj64-mc9x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-502"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, "type": "CWE-502"}
240
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * This file is part of CodeIgniter 4 framework.\n *\n * (c) CodeIgniter Foundation <admin@codeigniter.com>\n *\n * For the full copyright and license information, please view\n * the LICENSE file that was distributed with this source code.\n */", "use CodeIgniter\\Cache\\CacheInterface;\nuse CodeIgniter\\Config\\Factories;\nuse CodeIgniter\\Cookie\\Cookie;\nuse CodeIgniter\\Cookie\\CookieStore;\nuse CodeIgniter\\Cookie\\Exceptions\\CookieException;\nuse CodeIgniter\\Database\\BaseConnection;\nuse CodeIgniter\\Database\\ConnectionInterface;\nuse CodeIgniter\\Debug\\Timer;\nuse CodeIgniter\\Files\\Exceptions\\FileNotFoundException;\nuse CodeIgniter\\HTTP\\Exceptions\\HTTPException;\nuse CodeIgniter\\HTTP\\RedirectResponse;\nuse CodeIgniter\\HTTP\\RequestInterface;\nuse CodeIgniter\\HTTP\\ResponseInterface;\nuse CodeIgniter\\HTTP\\URI;\nuse CodeIgniter\\Model;\nuse CodeIgniter\\Session\\Session;\nuse CodeIgniter\\Test\\TestLogger;\nuse Config\\App;\nuse Config\\Database;\nuse Config\\Logger;\nuse Config\\Services;\nuse Config\\View;\nuse Laminas\\Escaper\\Escaper;", "// Services Convenience Functions", "if (! function_exists('app_timezone')) {\n /**\n * Returns the timezone the application has been set to display\n * dates in. This might be different than the timezone set\n * at the server level, as you often want to stores dates in UTC\n * and convert them on the fly for the user.\n */\n function app_timezone(): string\n {\n $config = config(App::class);", " return $config->appTimezone;\n }\n}", "if (! function_exists('cache')) {\n /**\n * A convenience method that provides access to the Cache\n * object. If no parameter is provided, will return the object,\n * otherwise, will attempt to return the cached value.\n *\n * Examples:\n * cache()->save('foo', 'bar');\n * $foo = cache('bar');\n *\n * @return CacheInterface|mixed\n */\n function cache(?string $key = null)\n {\n $cache = Services::cache();", " // No params - return cache object\n if ($key === null) {\n return $cache;\n }", " // Still here? Retrieve the value.\n return $cache->get($key);\n }\n}", "if (! function_exists('clean_path')) {\n /**\n * A convenience method to clean paths for\n * a nicer looking output. Useful for exception\n * handling, error logging, etc.\n */\n function clean_path(string $path): string\n {\n // Resolve relative paths\n $path = realpath($path) ?: $path;", " switch (true) {\n case strpos($path, APPPATH) === 0:\n return 'APPPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(APPPATH));", " case strpos($path, SYSTEMPATH) === 0:\n return 'SYSTEMPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(SYSTEMPATH));", " case strpos($path, FCPATH) === 0:\n return 'FCPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(FCPATH));", " case defined('VENDORPATH') && strpos($path, VENDORPATH) === 0:\n return 'VENDORPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(VENDORPATH));", " case strpos($path, ROOTPATH) === 0:\n return 'ROOTPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(ROOTPATH));", " default:\n return $path;\n }\n }\n}", "if (! function_exists('command')) {\n /**\n * Runs a single command.\n * Input expected in a single string as would\n * be used on the command line itself:\n *\n * > command('migrate:create SomeMigration');\n *\n * @return false|string\n */\n function command(string $command)\n {\n $runner = service('commands');\n $regexString = '([^\\s]+?)(?:\\s|(?<!\\\\\\\\)\"|(?<!\\\\\\\\)\\'|$)';\n $regexQuoted = '(?:\"([^\"\\\\\\\\]*(?:\\\\\\\\.[^\"\\\\\\\\]*)*)\"|\\'([^\\'\\\\\\\\]*(?:\\\\\\\\.[^\\'\\\\\\\\]*)*)\\')';", " $args = [];\n $length = strlen($command);\n $cursor = 0;", " /**\n * Adopted from Symfony's `StringInput::tokenize()` with few changes.\n *\n * @see https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Console/Input/StringInput.php\n */\n while ($cursor < $length) {\n if (preg_match('/\\s+/A', $command, $match, 0, $cursor)) {\n // nothing to do\n } elseif (preg_match('/' . $regexQuoted . '/A', $command, $match, 0, $cursor)) {\n $args[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));\n } elseif (preg_match('/' . $regexString . '/A', $command, $match, 0, $cursor)) {\n $args[] = stripcslashes($match[1]);\n } else {\n // @codeCoverageIgnoreStart\n throw new InvalidArgumentException(sprintf('Unable to parse input near \"... %s ...\".', substr($command, $cursor, 10)));\n // @codeCoverageIgnoreEnd\n }", " $cursor += strlen($match[0]);\n }", " $command = array_shift($args);\n $params = [];\n $optionValue = false;", " foreach ($args as $i => $arg) {\n if (mb_strpos($arg, '-') !== 0) {\n if ($optionValue) {\n // if this was an option value, it was already\n // included in the previous iteration\n $optionValue = false;\n } else {\n // add to segments if not starting with '-'\n // and not an option value\n $params[] = $arg;\n }", " continue;\n }", " $arg = ltrim($arg, '-');\n $value = null;", " if (isset($args[$i + 1]) && mb_strpos($args[$i + 1], '-') !== 0) {\n $value = $args[$i + 1];\n $optionValue = true;\n }", " $params[$arg] = $value;\n }", " ob_start();\n $runner->run($command, $params);", " return ob_get_clean();\n }\n}", "if (! function_exists('config')) {\n /**\n * More simple way of getting config instances from Factories\n *\n * @return mixed\n */\n function config(string $name, bool $getShared = true)\n {\n return Factories::config($name, ['getShared' => $getShared]);\n }\n}", "if (! function_exists('cookie')) {\n /**\n * Simpler way to create a new Cookie instance.\n *\n * @param string $name Name of the cookie\n * @param string $value Value of the cookie\n * @param array $options Array of options to be passed to the cookie\n *\n * @throws CookieException\n */\n function cookie(string $name, string $value = '', array $options = []): Cookie\n {\n return new Cookie($name, $value, $options);\n }\n}", "if (! function_exists('cookies')) {\n /**\n * Fetches the global `CookieStore` instance held by `Response`.\n *\n * @param Cookie[] $cookies If `getGlobal` is false, this is passed to CookieStore's constructor\n * @param bool $getGlobal If false, creates a new instance of CookieStore\n */\n function cookies(array $cookies = [], bool $getGlobal = true): CookieStore\n {\n if ($getGlobal) {\n return Services::response()->getCookieStore();\n }", " return new CookieStore($cookies);\n }\n}", "if (! function_exists('csrf_token')) {\n /**\n * Returns the CSRF token name.\n * Can be used in Views when building hidden inputs manually,\n * or used in javascript vars when using APIs.\n */\n function csrf_token(): string\n {\n return Services::security()->getTokenName();\n }\n}", "if (! function_exists('csrf_header')) {\n /**\n * Returns the CSRF header name.\n * Can be used in Views by adding it to the meta tag\n * or used in javascript to define a header name when using APIs.\n */\n function csrf_header(): string\n {\n return Services::security()->getHeaderName();\n }\n}", "if (! function_exists('csrf_hash')) {\n /**\n * Returns the current hash value for the CSRF protection.\n * Can be used in Views when building hidden inputs manually,\n * or used in javascript vars for API usage.\n */\n function csrf_hash(): string\n {\n return Services::security()->getHash();\n }\n}", "if (! function_exists('csrf_field')) {\n /**\n * Generates a hidden input field for use within manually generated forms.\n */\n function csrf_field(?string $id = null): string\n {\n return '<input type=\"hidden\"' . (! empty($id) ? ' id=\"' . esc($id, 'attr') . '\"' : '') . ' name=\"' . csrf_token() . '\" value=\"' . csrf_hash() . '\" />';\n }\n}", "if (! function_exists('csrf_meta')) {\n /**\n * Generates a meta tag for use within javascript calls.\n */\n function csrf_meta(?string $id = null): string\n {\n return '<meta' . (! empty($id) ? ' id=\"' . esc($id, 'attr') . '\"' : '') . ' name=\"' . csrf_header() . '\" content=\"' . csrf_hash() . '\" />';\n }\n}", "if (! function_exists('db_connect')) {\n /**\n * Grabs a database connection and returns it to the user.\n *\n * This is a convenience wrapper for \\Config\\Database::connect()\n * and supports the same parameters. Namely:\n *\n * When passing in $db, you may pass any of the following to connect:\n * - group name\n * - existing connection instance\n * - array of database configuration values\n *\n * If $getShared === false then a new connection instance will be provided,\n * otherwise it will all calls will return the same instance.\n *\n * @param array|ConnectionInterface|string|null $db\n *\n * @return BaseConnection\n */\n function db_connect($db = null, bool $getShared = true)\n {\n return Database::connect($db, $getShared);\n }\n}", "if (! function_exists('dd')) {\n /**\n * Prints a Kint debug report and exits.\n *\n * @param array ...$vars\n *\n * @codeCoverageIgnore Can't be tested ... exits\n */\n function dd(...$vars)\n {\n // @codeCoverageIgnoreStart\n Kint::$aliases[] = 'dd';\n Kint::dump(...$vars);", " exit;\n // @codeCoverageIgnoreEnd\n }\n}", "if (! function_exists('env')) {\n /**\n * Allows user to retrieve values from the environment\n * variables that have been set. Especially useful for\n * retrieving values set from the .env file for\n * use in config files.\n *\n * @param string|null $default\n *\n * @return mixed\n */\n function env(string $key, $default = null)\n {\n $value = $_ENV[$key] ?? $_SERVER[$key] ?? getenv($key);", " // Not found? Return the default value\n if ($value === false) {\n return $default;\n }", " // Handle any boolean values\n switch (strtolower($value)) {\n case 'true':\n return true;", " case 'false':\n return false;", " case 'empty':\n return '';", " case 'null':\n return null;\n }", " return $value;\n }\n}", "if (! function_exists('esc')) {\n /**\n * Performs simple auto-escaping of data for security reasons.\n * Might consider making this more complex at a later date.\n *\n * If $data is a string, then it simply escapes and returns it.\n * If $data is an array, then it loops over it, escaping each\n * 'value' of the key/value pairs.\n *\n * Valid context values: html, js, css, url, attr, raw\n *\n * @param array|string $data\n * @param string $encoding\n *\n * @throws InvalidArgumentException\n *\n * @return array|string\n */\n function esc($data, string $context = 'html', ?string $encoding = null)\n {\n if (is_array($data)) {\n foreach ($data as &$value) {\n $value = esc($value, $context);\n }\n }", " if (is_string($data)) {\n $context = strtolower($context);", " // Provide a way to NOT escape data since\n // this could be called automatically by\n // the View library.\n if (empty($context) || $context === 'raw') {\n return $data;\n }", " if (! in_array($context, ['html', 'js', 'css', 'url', 'attr'], true)) {\n throw new InvalidArgumentException('Invalid escape context provided.');\n }", " $method = $context === 'attr' ? 'escapeHtmlAttr' : 'escape' . ucfirst($context);", " static $escaper;\n if (! $escaper) {\n $escaper = new Escaper($encoding);\n }", " if ($encoding && $escaper->getEncoding() !== $encoding) {\n $escaper = new Escaper($encoding);\n }", " $data = $escaper->{$method}($data);\n }", " return $data;\n }\n}", "if (! function_exists('force_https')) {\n /**\n * Used to force a page to be accessed in via HTTPS.\n * Uses a standard redirect, plus will set the HSTS header\n * for modern browsers that support, which gives best\n * protection against man-in-the-middle attacks.\n *\n * @see https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security\n *\n * @param int $duration How long should the SSL header be set for? (in seconds)\n * Defaults to 1 year.\n * @param RequestInterface $request\n * @param ResponseInterface $response\n *\n * @throws HTTPException\n */\n function force_https(int $duration = 31536000, ?RequestInterface $request = null, ?ResponseInterface $response = null)\n {\n if ($request === null) {\n $request = Services::request(null, true);\n }\n if ($response === null) {\n $response = Services::response(null, true);\n }", " if ((ENVIRONMENT !== 'testing' && (is_cli() || $request->isSecure())) || (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'test')) {\n // @codeCoverageIgnoreStart\n return;\n // @codeCoverageIgnoreEnd\n }", " // If the session status is active, we should regenerate\n // the session ID for safety sake.\n if (ENVIRONMENT !== 'testing' && session_status() === PHP_SESSION_ACTIVE) {\n // @codeCoverageIgnoreStart\n Services::session(null, true)\n ->regenerate();\n // @codeCoverageIgnoreEnd\n }", " $baseURL = config(App::class)->baseURL;", " if (strpos($baseURL, 'https://') === 0) {\n $baseURL = substr($baseURL, strlen('https://'));\n } elseif (strpos($baseURL, 'http://') === 0) {\n $baseURL = substr($baseURL, strlen('http://'));\n }", " $uri = URI::createURIString(\n 'https',\n $baseURL,\n $request->getUri()->getPath(), // Absolute URIs should use a \"/\" for an empty path\n $request->getUri()->getQuery(),\n $request->getUri()->getFragment()\n );", " // Set an HSTS header\n $response->setHeader('Strict-Transport-Security', 'max-age=' . $duration);\n $response->redirect($uri);\n $response->sendHeaders();", " if (ENVIRONMENT !== 'testing') {\n // @codeCoverageIgnoreStart\n exit();\n // @codeCoverageIgnoreEnd\n }\n }\n}", "if (! function_exists('function_usable')) {\n /**\n * Function usable\n *\n * Executes a function_exists() check, and if the Suhosin PHP\n * extension is loaded - checks whether the function that is\n * checked might be disabled in there as well.\n *\n * This is useful as function_exists() will return FALSE for\n * functions disabled via the *disable_functions* php.ini\n * setting, but not for *suhosin.executor.func.blacklist* and\n * *suhosin.executor.disable_eval*. These settings will just\n * terminate script execution if a disabled function is executed.\n *\n * The above described behavior turned out to be a bug in Suhosin,\n * but even though a fix was committed for 0.9.34 on 2012-02-12,\n * that version is yet to be released. This function will therefore\n * be just temporary, but would probably be kept for a few years.\n *\n * @see http://www.hardened-php.net/suhosin/\n *\n * @param string $functionName Function to check for\n *\n * @return bool TRUE if the function exists and is safe to call,\n * FALSE otherwise.\n *\n * @codeCoverageIgnore This is too exotic\n */\n function function_usable(string $functionName): bool\n {\n static $_suhosin_func_blacklist;", " if (function_exists($functionName)) {\n if (! isset($_suhosin_func_blacklist)) {\n $_suhosin_func_blacklist = extension_loaded('suhosin') ? explode(',', trim(ini_get('suhosin.executor.func.blacklist'))) : [];\n }", " return ! in_array($functionName, $_suhosin_func_blacklist, true);\n }", " return false;\n }\n}", "if (! function_exists('helper')) {\n /**\n * Loads a helper file into memory. Supports namespaced helpers,\n * both in and out of the 'helpers' directory of a namespaced directory.\n *\n * Will load ALL helpers of the matching name, in the following order:\n * 1. app/Helpers\n * 2. {namespace}/Helpers\n * 3. system/Helpers\n *\n * @param array|string $filenames\n *\n * @throws FileNotFoundException\n */\n function helper($filenames)\n {\n static $loaded = [];", " $loader = Services::locator();", " if (! is_array($filenames)) {\n $filenames = [$filenames];\n }", " // Store a list of all files to include...\n $includes = [];", " foreach ($filenames as $filename) {\n // Store our system and application helper\n // versions so that we can control the load ordering.\n $systemHelper = null;\n $appHelper = null;\n $localIncludes = [];", " if (strpos($filename, '_helper') === false) {\n $filename .= '_helper';\n }", " // Check if this helper has already been loaded\n if (in_array($filename, $loaded, true)) {\n continue;\n }", " // If the file is namespaced, we'll just grab that\n // file and not search for any others\n if (strpos($filename, '\\\\') !== false) {\n $path = $loader->locateFile($filename, 'Helpers');", " if (empty($path)) {\n throw FileNotFoundException::forFileNotFound($filename);\n }", " $includes[] = $path;\n $loaded[] = $filename;\n } else {\n // No namespaces, so search in all available locations\n $paths = $loader->search('Helpers/' . $filename);", " foreach ($paths as $path) {\n if (strpos($path, APPPATH . 'Helpers' . DIRECTORY_SEPARATOR) === 0) {\n $appHelper = $path;\n } elseif (strpos($path, SYSTEMPATH . 'Helpers' . DIRECTORY_SEPARATOR) === 0) {\n $systemHelper = $path;\n } else {\n $localIncludes[] = $path;\n $loaded[] = $filename;\n }\n }", " // App-level helpers should override all others\n if (! empty($appHelper)) {\n $includes[] = $appHelper;\n $loaded[] = $filename;\n }", " // All namespaced files get added in next\n $includes = array_merge($includes, $localIncludes);", " // And the system default one should be added in last.\n if (! empty($systemHelper)) {\n $includes[] = $systemHelper;\n $loaded[] = $filename;\n }\n }\n }", " // Now actually include all of the files\n foreach ($includes as $path) {\n include_once $path;\n }\n }\n}", "if (! function_exists('is_cli')) {\n /**\n * Check if PHP was invoked from the command line.\n *\n * @codeCoverageIgnore Cannot be tested fully as PHPUnit always run in php-cli\n */\n function is_cli(): bool\n {\n if (in_array(PHP_SAPI, ['cli', 'phpdbg'], true)) {\n return true;\n }", " // PHP_SAPI could be 'cgi-fcgi', 'fpm-fcgi'.\n // See https://github.com/codeigniter4/CodeIgniter4/pull/5393\n return ! isset($_SERVER['REMOTE_ADDR']) && ! isset($_SERVER['REQUEST_METHOD']);\n }\n}", "if (! function_exists('is_really_writable')) {\n /**\n * Tests for file writability\n *\n * is_writable() returns TRUE on Windows servers when you really can't write to\n * the file, based on the read-only attribute. is_writable() is also unreliable\n * on Unix servers if safe_mode is on.\n *\n * @see https://bugs.php.net/bug.php?id=54709\n *\n * @throws Exception\n *\n * @codeCoverageIgnore Not practical to test, as travis runs on linux\n */\n function is_really_writable(string $file): bool\n {\n // If we're on a Unix server we call is_writable\n if (DIRECTORY_SEPARATOR === '/') {\n return is_writable($file);\n }", " /* For Windows servers and safe_mode \"on\" installations we'll actually\n * write a file then read it. Bah...\n */\n if (is_dir($file)) {\n $file = rtrim($file, '/') . '/' . bin2hex(random_bytes(16));\n if (($fp = @fopen($file, 'ab')) === false) {\n return false;\n }", " fclose($fp);\n @chmod($file, 0777);\n @unlink($file);", " return true;\n }", " if (! is_file($file) || ($fp = @fopen($file, 'ab')) === false) {\n return false;\n }", " fclose($fp);", " return true;\n }\n}", "if (! function_exists('lang')) {\n /**\n * A convenience method to translate a string or array of them and format\n * the result with the intl extension's MessageFormatter.\n *\n * @return string\n */\n function lang(string $line, array $args = [], ?string $locale = null)\n {\n $language = Services::language();", " // Get active locale\n $activeLocale = $language->getLocale();", " if ($locale && $locale !== $activeLocale) {\n $language->setLocale($locale);\n }", " $line = $language->getLine($line, $args);", " if ($locale && $locale !== $activeLocale) {\n // Reset to active locale\n $language->setLocale($activeLocale);\n }", " return $line;\n }\n}", "if (! function_exists('log_message')) {\n /**\n * A convenience/compatibility method for logging events through\n * the Log system.\n *\n * Allowed log levels are:\n * - emergency\n * - alert\n * - critical\n * - error\n * - warning\n * - notice\n * - info\n * - debug\n *\n * @return mixed\n */\n function log_message(string $level, string $message, array $context = [])\n {\n // When running tests, we want to always ensure that the\n // TestLogger is running, which provides utilities for\n // for asserting that logs were called in the test code.\n if (ENVIRONMENT === 'testing') {\n $logger = new TestLogger(new Logger());", " return $logger->log($level, $message, $context);\n }", " // @codeCoverageIgnoreStart\n return Services::logger(true)\n ->log($level, $message, $context);\n // @codeCoverageIgnoreEnd\n }\n}", "if (! function_exists('model')) {\n /**\n * More simple way of getting model instances from Factories\n *\n * @template T of Model\n *\n * @param class-string<T> $name\n *\n * @return T\n * @phpstan-return Model\n */\n function model(string $name, bool $getShared = true, ?ConnectionInterface &$conn = null)\n {\n return Factories::models($name, ['getShared' => $getShared], $conn);\n }\n}", "if (! function_exists('old')) {\n /**\n * Provides access to \"old input\" that was set in the session\n * during a redirect()->withInput().\n *\n * @param null $default\n * @param bool|string $escape\n *\n * @return mixed|null\n */\n function old(string $key, $default = null, $escape = 'html')\n {\n // Ensure the session is loaded\n if (session_status() === PHP_SESSION_NONE && ENVIRONMENT !== 'testing') {\n // @codeCoverageIgnoreStart\n session();\n // @codeCoverageIgnoreEnd\n }", " $request = Services::request();", " $value = $request->getOldInput($key);", " // Return the default value if nothing\n // found in the old input.\n if ($value === null) {\n return $default;\n }\n", "", " return $escape === false ? $value : esc($value, $escape);\n }\n}", "if (! function_exists('redirect')) {\n /**\n * Convenience method that works with the current global $request and\n * $router instances to redirect using named/reverse-routed routes\n * to determine the URL to go to.\n *\n * If more control is needed, you must use $response->redirect explicitly.\n *\n * @param string $route\n */\n function redirect(?string $route = null): RedirectResponse\n {\n $response = Services::redirectresponse(null, true);", " if (! empty($route)) {\n return $response->route($route);\n }", " return $response;\n }\n}", "if (! function_exists('remove_invisible_characters')) {\n /**\n * Remove Invisible Characters\n *\n * This prevents sandwiching null characters\n * between ascii characters, like Java\\0script.\n */\n function remove_invisible_characters(string $str, bool $urlEncoded = true): string\n {\n $nonDisplayables = [];", " // every control character except newline (dec 10),\n // carriage return (dec 13) and horizontal tab (dec 09)\n if ($urlEncoded) {\n $nonDisplayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15\n $nonDisplayables[] = '/%1[0-9a-f]/'; // url encoded 16-31\n }", " $nonDisplayables[] = '/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]+/S'; // 00-08, 11, 12, 14-31, 127", " do {\n $str = preg_replace($nonDisplayables, '', $str, -1, $count);\n } while ($count);", " return $str;\n }\n}", "if (! function_exists('route_to')) {\n /**\n * Given a controller/method string and any params,\n * will attempt to build the relative URL to the\n * matching route.\n *\n * NOTE: This requires the controller/method to\n * have a route defined in the routes Config file.\n *\n * @param mixed ...$params\n *\n * @return false|string\n */\n function route_to(string $method, ...$params)\n {\n return Services::routes()->reverseRoute($method, ...$params);\n }\n}", "if (! function_exists('session')) {\n /**\n * A convenience method for accessing the session instance,\n * or an item that has been set in the session.\n *\n * Examples:\n * session()->set('foo', 'bar');\n * $foo = session('bar');\n *\n * @param string $val\n *\n * @return mixed|Session|null\n */\n function session(?string $val = null)\n {\n $session = Services::session();", " // Returning a single item?\n if (is_string($val)) {\n return $session->get($val);\n }", " return $session;\n }\n}", "if (! function_exists('service')) {\n /**\n * Allows cleaner access to the Services Config file.\n * Always returns a SHARED instance of the class, so\n * calling the function multiple times should always\n * return the same instance.\n *\n * These are equal:\n * - $timer = service('timer')\n * - $timer = \\CodeIgniter\\Config\\Services::timer();\n *\n * @param mixed ...$params\n *\n * @return mixed\n */\n function service(string $name, ...$params)\n {\n return Services::$name(...$params);\n }\n}", "if (! function_exists('single_service')) {\n /**\n * Always returns a new instance of the class.\n *\n * @param mixed ...$params\n *\n * @return mixed\n */\n function single_service(string $name, ...$params)\n {\n $service = Services::serviceExists($name);", " if ($service === null) {\n // The service is not defined anywhere so just return.\n return null;\n }", " $method = new ReflectionMethod($service, $name);\n $count = $method->getNumberOfParameters();\n $mParam = $method->getParameters();\n $params = $params ?? [];", " if ($count === 1) {\n // This service needs only one argument, which is the shared\n // instance flag, so let's wrap up and pass false here.\n return $service::$name(false);\n }", " // Fill in the params with the defaults, but stop before the last\n for ($startIndex = count($params); $startIndex <= $count - 2; $startIndex++) {\n $params[$startIndex] = $mParam[$startIndex]->getDefaultValue();\n }", " // Ensure the last argument will not create a shared instance\n $params[$count - 1] = false;", " return $service::$name(...$params);\n }\n}", "if (! function_exists('slash_item')) {\n // Unlike CI3, this function is placed here because\n // it's not a config, or part of a config.\n /**\n * Fetch a config file item with slash appended (if not empty)\n *\n * @param string $item Config item name\n *\n * @return string|null The configuration item or NULL if\n * the item doesn't exist\n */\n function slash_item(string $item): ?string\n {\n $config = config(App::class);\n $configItem = $config->{$item};", " if (! isset($configItem) || empty(trim($configItem))) {\n return $configItem;\n }", " return rtrim($configItem, '/') . '/';\n }\n}", "if (! function_exists('stringify_attributes')) {\n /**\n * Stringify attributes for use in HTML tags.\n *\n * Helper function used to convert a string, array, or object\n * of attributes to a string.\n *\n * @param mixed $attributes string, array, object\n */\n function stringify_attributes($attributes, bool $js = false): string\n {\n $atts = '';", " if (empty($attributes)) {\n return $atts;\n }", " if (is_string($attributes)) {\n return ' ' . $attributes;\n }", " $attributes = (array) $attributes;", " foreach ($attributes as $key => $val) {\n $atts .= ($js) ? $key . '=' . esc($val, 'js') . ',' : ' ' . $key . '=\"' . esc($val) . '\"';\n }", " return rtrim($atts, ',');\n }\n}", "if (! function_exists('timer')) {\n /**\n * A convenience method for working with the timer.\n * If no parameter is passed, it will return the timer instance,\n * otherwise will start or stop the timer intelligently.\n *\n * @return mixed|Timer\n */\n function timer(?string $name = null)\n {\n $timer = Services::timer();", " if (empty($name)) {\n return $timer;\n }", " if ($timer->has($name)) {\n return $timer->stop($name);\n }", " return $timer->start($name);\n }\n}", "if (! function_exists('trace')) {\n /**\n * Provides a backtrace to the current execution point, from Kint.\n */\n function trace()\n {\n Kint::$aliases[] = 'trace';\n Kint::trace();\n }\n}", "if (! function_exists('view')) {\n /**\n * Grabs the current RendererInterface-compatible class\n * and tells it to render the specified view. Simply provides\n * a convenience method that can be used in Controllers,\n * libraries, and routed closures.\n *\n * NOTE: Does not provide any escaping of the data, so that must\n * all be handled manually by the developer.\n *\n * @param array $options Unused - reserved for third-party extensions.\n */\n function view(string $name, array $data = [], array $options = []): string\n {\n /**\n * @var CodeIgniter\\View\\View $renderer\n */\n $renderer = Services::renderer();", " $saveData = config(View::class)->saveData;", " if (array_key_exists('saveData', $options)) {\n $saveData = (bool) $options['saveData'];\n unset($options['saveData']);\n }", " return $renderer->setData($data, 'raw')->render($name, $options, $saveData);\n }\n}", "if (! function_exists('view_cell')) {\n /**\n * View cells are used within views to insert HTML chunks that are managed\n * by other classes.\n *\n * @param null $params\n *\n * @throws ReflectionException\n */\n function view_cell(string $library, $params = null, int $ttl = 0, ?string $cacheName = null): string\n {\n return Services::viewcell()\n ->render($library, $params, $ttl, $cacheName);\n }\n}", "/**\n * These helpers come from Laravel so will not be\n * re-tested and can be ignored safely.\n *\n * @see https://github.com/laravel/framework/blob/8.x/src/Illuminate/Support/helpers.php\n */\nif (! function_exists('class_basename')) {\n /**\n * Get the class \"basename\" of the given object / class.\n *\n * @param object|string $class\n *\n * @return string\n *\n * @codeCoverageIgnore\n */\n function class_basename($class)\n {\n $class = is_object($class) ? get_class($class) : $class;", " return basename(str_replace('\\\\', '/', $class));\n }\n}", "if (! function_exists('class_uses_recursive')) {\n /**\n * Returns all traits used by a class, its parent classes and trait of their traits.\n *\n * @param object|string $class\n *\n * @return array\n *\n * @codeCoverageIgnore\n */\n function class_uses_recursive($class)\n {\n if (is_object($class)) {\n $class = get_class($class);\n }", " $results = [];", " foreach (array_reverse(class_parents($class)) + [$class => $class] as $class) {\n $results += trait_uses_recursive($class);\n }", " return array_unique($results);\n }\n}", "if (! function_exists('trait_uses_recursive')) {\n /**\n * Returns all traits used by a trait and its traits.\n *\n * @param string $trait\n *\n * @return array\n *\n * @codeCoverageIgnore\n */\n function trait_uses_recursive($trait)\n {\n $traits = class_uses($trait) ?: [];", " foreach ($traits as $trait) {\n $traits += trait_uses_recursive($trait);\n }", " return $traits;\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 ]
PreciseBugs
{"buggy_code_end_loc": [22, 818, 313, 129, 10], "buggy_code_start_loc": [22, 813, 304, 110, 10], "filenames": ["SECURITY.md", "system/Common.php", "tests/system/CommonFunctionsTest.php", "tests/system/HTTP/IncomingRequestTest.php", "user_guide_src/source/changelogs/v4.1.6.rst"], "fixing_code_end_loc": [24, 812, 346, 131, 16], "fixing_code_start_loc": [23, 812, 304, 110, 11], "message": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codeigniter:codeigniter:*:*:*:*:*:*:*:*", "matchCriteriaId": "5E18B755-8CBA-45C9-8759-5039BBAD4FC6", "versionEndExcluding": "4.1.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`."}, {"lang": "es", "value": "CodeIgniter es un framework web full-stack de PHP de c\u00f3digo abierto. Se encontr\u00f3 una deserializaci\u00f3n de datos no confiables en la funci\u00f3n \"old()\" en CodeIgniter4. Los atacantes remotos pueden inyectar objetos arbitrarios autocargables con esta vulnerabilidad, y posiblemente ejecutar c\u00f3digo PHP existente en el servidor. Tenemos conocimiento de una explotaci\u00f3n que funciona, que puede conllevar a una inyecci\u00f3n SQL. Se aconseja a usuarios que actualicen a la versi\u00f3n 4.1.6 o posterior. A los usuarios que no puedan actualizarse se les aconseja no usar la funci\u00f3n \"old()\" y form_helper ni \"RedirectResponse::withInput()\" y \"redirect()-&gt;withInput()\""}], "evaluatorComment": null, "id": "CVE-2022-21647", "lastModified": "2022-01-20T15:04:23.823", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.7, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-01-04T20:15:07.930", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-w6jr-wj64-mc9x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-502"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, "type": "CWE-502"}
240
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * This file is part of CodeIgniter 4 framework.\n *\n * (c) CodeIgniter Foundation <admin@codeigniter.com>\n *\n * For the full copyright and license information, please view\n * the LICENSE file that was distributed with this source code.\n */", "namespace CodeIgniter;", "use CodeIgniter\\Config\\BaseService;\nuse CodeIgniter\\Config\\Services;\nuse CodeIgniter\\HTTP\\RedirectResponse;\nuse CodeIgniter\\HTTP\\Response;\nuse CodeIgniter\\HTTP\\URI;\nuse CodeIgniter\\HTTP\\UserAgent;\nuse CodeIgniter\\Router\\RouteCollection;\nuse CodeIgniter\\Session\\Handlers\\FileHandler;\nuse CodeIgniter\\Session\\Session;\nuse CodeIgniter\\Test\\CIUnitTestCase;\nuse CodeIgniter\\Test\\Mock\\MockIncomingRequest;\nuse CodeIgniter\\Test\\Mock\\MockSecurity;\nuse CodeIgniter\\Test\\Mock\\MockSession;\nuse CodeIgniter\\Test\\TestLogger;\nuse Config\\App;\nuse Config\\Logger;\nuse Config\\Modules;\nuse InvalidArgumentException;\nuse Kint;\nuse stdClass;\nuse Tests\\Support\\Models\\JobModel;", "/**\n * @backupGlobals enabled\n *\n * @internal\n */\nfinal class CommonFunctionsTest extends CIUnitTestCase\n{\n protected function setUp(): void\n {\n unset($_ENV['foo'], $_SERVER['foo']);\n Services::reset();", " parent::setUp();\n }", " public function testStringifyAttributes()\n {\n $this->assertSame(' class=\"foo\" id=\"bar\"', stringify_attributes(['class' => 'foo', 'id' => 'bar']));", " $atts = new stdClass();\n $atts->class = 'foo';\n $atts->id = 'bar';\n $this->assertSame(' class=\"foo\" id=\"bar\"', stringify_attributes($atts));", " $atts = new stdClass();\n $this->assertSame('', stringify_attributes($atts));", " $this->assertSame(' class=\"foo\" id=\"bar\"', stringify_attributes('class=\"foo\" id=\"bar\"'));", " $this->assertSame('', stringify_attributes([]));\n }", " public function testStringifyJsAttributes()\n {\n $this->assertSame('width=800,height=600', stringify_attributes(['width' => '800', 'height' => '600'], true));", " $atts = new stdClass();\n $atts->width = 800;\n $atts->height = 600;\n $this->assertSame('width=800,height=600', stringify_attributes($atts, true));\n }", " public function testEnvReturnsDefault()\n {\n $this->assertSame('baz', env('foo', 'baz'));\n }", " public function testEnvGetsFromSERVER()\n {\n $_SERVER['foo'] = 'bar';", " $this->assertSame('bar', env('foo', 'baz'));\n }", " public function testEnvGetsFromENV()\n {\n $_ENV['foo'] = 'bar';", " $this->assertSame('bar', env('foo', 'baz'));\n }", " public function testEnvBooleans()\n {\n $_ENV['p1'] = 'true';\n $_ENV['p2'] = 'false';\n $_ENV['p3'] = 'empty';\n $_ENV['p4'] = 'null';", " $this->assertTrue(env('p1'));\n $this->assertFalse(env('p2'));\n $this->assertEmpty(env('p3'));\n $this->assertNull(env('p4'));\n }", " public function testRedirectReturnsRedirectResponse()\n {\n $_SERVER['REQUEST_METHOD'] = 'GET';", " $response = $this->createMock(Response::class);\n $routes = new RouteCollection(\n Services::locator(),\n new Modules()\n );\n \\CodeIgniter\\Services::injectMock('response', $response);\n \\CodeIgniter\\Services::injectMock('routes', $routes);", " $routes->add('home/base', 'Controller::index', ['as' => 'base']);\n $response->method('redirect')->willReturnArgument(0);", " $this->assertInstanceOf(RedirectResponse::class, redirect('base'));\n }", " public function testRedirectDefault()\n {\n $this->assertInstanceOf(RedirectResponse::class, redirect());\n }", " public function testView()\n {\n $data = [\n 'testString' => 'bar',\n 'bar' => 'baz',\n ];\n $expected = '<h1>bar</h1>';\n $this->assertStringContainsString($expected, view('\\Tests\\Support\\View\\Views\\simple', $data));\n }", " public function testViewSavedData()\n {\n $data = [\n 'testString' => 'bar',\n 'bar' => 'baz',\n ];\n $expected = '<h1>bar</h1>';\n $this->assertStringContainsString($expected, view('\\Tests\\Support\\View\\Views\\simple', $data, ['saveData' => true]));\n $this->assertStringContainsString($expected, view('\\Tests\\Support\\View\\Views\\simple'));\n }", " public function testViewCell()\n {\n $expected = 'Hello';\n $this->assertSame($expected, view_cell('\\Tests\\Support\\View\\SampleClass::hello'));\n }", " public function testEscapeWithDifferentEncodings()\n {\n $this->assertSame('&lt;x', esc('<x', 'html', 'utf-8'));\n $this->assertSame('&lt;x', esc('<x', 'html', 'iso-8859-1'));\n $this->assertSame('&lt;x', esc('<x', 'html', 'windows-1251'));\n }", " public function testEscapeBadContext()\n {\n $this->expectException(InvalidArgumentException::class);\n esc(['width' => '800', 'height' => '600'], 'bogus');\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testSessionInstance()\n {\n $this->injectSessionMock();", " $this->assertInstanceOf(Session::class, session());\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testSessionVariable()\n {\n $this->injectSessionMock();", " $_SESSION['notbogus'] = 'Hi there';", " $this->assertSame('Hi there', session('notbogus'));\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testSessionVariableNotThere()\n {\n $this->injectSessionMock();", " $_SESSION['bogus'] = 'Hi there';\n $this->assertNull(session('notbogus'));\n }", " public function testRouteTo()\n {\n // prime the pump\n $routes = service('routes');\n $routes->add('path/(:any)/to/(:num)', 'myController::goto/$1/$2');", " $this->assertSame('/path/string/to/13', route_to('myController::goto', 'string', 13));\n }", " public function testInvisible()\n {\n $this->assertSame('Javascript', remove_invisible_characters(\"Java\\0script\"));\n }", " public function testInvisibleEncoded()\n {\n $this->assertSame('Javascript', remove_invisible_characters('Java%0cscript'));\n }", " public function testAppTimezone()\n {\n $this->assertSame('America/Chicago', app_timezone());\n }", " public function testCSRFToken()\n {\n Services::injectMock('security', new MockSecurity(new App()));", " $this->assertSame('csrf_test_name', csrf_token());\n }", " public function testCSRFHeader()\n {\n $this->assertSame('X-CSRF-TOKEN', csrf_header());\n }", " public function testHash()\n {\n $this->assertSame(32, strlen(csrf_hash()));\n }", " public function testCSRFField()\n {\n $this->assertStringContainsString('<input type=\"hidden\" ', csrf_field());\n }", " public function testCSRFMeta()\n {\n $this->assertStringContainsString('<meta name=\"X-CSRF-TOKEN\" ', csrf_meta());\n }", " public function testModelNotExists()\n {\n $this->assertNull(model(UnexsistenceClass::class));\n }", " public function testModelExistsBasename()\n {\n $this->assertInstanceOf(JobModel::class, model('JobModel'));\n }", " public function testModelExistsClassname()\n {\n $this->assertInstanceOf(JobModel::class, model(JobModel::class));\n }", " public function testModelExistsAbsoluteClassname()\n {\n $this->assertInstanceOf(JobModel::class, model('\\Tests\\Support\\Models\\JobModel'));\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testOldInput()\n {\n $this->injectSessionMock();\n // setup from RedirectResponseTest...\n $_SERVER['REQUEST_METHOD'] = 'GET';", " $this->config = new App();\n $this->config->baseURL = 'http://example.com/';", " $this->routes = new RouteCollection(Services::locator(), new Modules());\n Services::injectMock('routes', $this->routes);", " $this->request = new MockIncomingRequest($this->config, new URI('http://example.com'), null, new UserAgent());\n Services::injectMock('request', $this->request);", " // setup & ask for a redirect...\n $_SESSION = [];\n $_GET = ['foo' => 'bar'];\n $_POST = [\n 'bar' => 'baz',", " 'zibble' => serialize('fritz'),", " ];", " $response = new RedirectResponse(new App());\n $response->withInput();", " $this->assertSame('bar', old('foo')); // regular parameter\n $this->assertSame('doo', old('yabba dabba', 'doo')); // non-existing parameter", " $this->assertSame('fritz', old('zibble')); // serialized parameter", " }", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/1492\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testOldInputArray()\n {\n $this->injectSessionMock();\n // setup from RedirectResponseTest...\n $_SERVER['REQUEST_METHOD'] = 'GET';", " $this->config = new App();\n $this->config->baseURL = 'http://example.com/';", " $this->routes = new RouteCollection(Services::locator(), new Modules());\n Services::injectMock('routes', $this->routes);", " $this->request = new MockIncomingRequest($this->config, new URI('http://example.com'), null, new UserAgent());\n Services::injectMock('request', $this->request);", " $locations = [\n 'AB' => 'Alberta',\n 'BC' => 'British Columbia',\n 'SK' => 'Saskatchewan',\n ];", " // setup & ask for a redirect...\n $_SESSION = [];\n $_GET = [];\n $_POST = ['location' => $locations];", " $response = new RedirectResponse(new App());\n $response->withInput();", " $this->assertSame($locations, old('location'));\n }", " public function testReallyWritable()\n {\n // cannot test fully on *nix\n $this->assertTrue(is_really_writable(WRITEPATH));\n }", " public function testSlashItem()\n {\n $this->assertSame('/', slash_item('cookiePath')); // slash already there\n $this->assertSame('', slash_item('cookieDomain')); // empty, so untouched\n $this->assertSame('en/', slash_item('defaultLocale')); // slash appended\n }", " protected function injectSessionMock()\n {\n $defaults = [\n 'sessionDriver' => 'CodeIgniter\\Session\\Handlers\\FileHandler',\n 'sessionCookieName' => 'ci_session',\n 'sessionExpiration' => 7200,\n 'sessionSavePath' => null,\n 'sessionMatchIP' => false,\n 'sessionTimeToUpdate' => 300,\n 'sessionRegenerateDestroy' => false,\n 'cookieDomain' => '',\n 'cookiePrefix' => '',\n 'cookiePath' => '/',\n 'cookieSecure' => false,\n 'cookieSameSite' => 'Lax',\n ];", " $appConfig = new App();", " foreach ($defaults as $key => $config) {\n $appConfig->{$key} = $config;\n }", " $session = new MockSession(new FileHandler($appConfig, '127.0.0.1'), $appConfig);\n $session->setLogger(new TestLogger(new Logger()));\n BaseService::injectMock('session', $session);\n }", " // Make sure cookies are set by RedirectResponse this way\n // See https://github.com/codeigniter4/CodeIgniter4/issues/1393\n public function testRedirectResponseCookies1()\n {\n $loginTime = time();", " $routes = service('routes');\n $routes->add('user/login', 'Auth::verify', ['as' => 'login']);", " $answer1 = redirect()->route('login')\n ->setCookie('foo', 'onething', YEAR)\n ->setCookie('login_time', $loginTime, YEAR);", " $this->assertTrue($answer1->hasCookie('foo', 'onething'));\n $this->assertTrue($answer1->hasCookie('login_time'));\n }", " public function testTrace()\n {\n ob_start();\n trace();\n $content = ob_get_clean();", " $this->assertStringContainsString('Debug Backtrace', $content);\n }", " public function testViewNotSaveData()\n {\n $data = [\n 'testString' => 'bar',\n 'bar' => 'baz',\n ];\n $this->assertStringContainsString('<h1>bar</h1>', view('\\Tests\\Support\\View\\Views\\simples', $data, ['saveData' => false]));\n $this->assertStringContainsString('<h1>is_not</h1>', view('\\Tests\\Support\\View\\Views\\simples'));\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testForceHttpsNullRequestAndResponse()\n {\n $this->assertNull(Services::response()->header('Location'));", " force_https();", " $this->assertSame('https://example.com/', Services::response()->header('Location')->getValue());\n }", " /**\n * @dataProvider dirtyPathsProvider\n *\n * @param mixed $input\n * @param mixed $expected\n */\n public function testCleanPathActuallyCleaningThePaths($input, $expected)\n {\n $this->assertSame($expected, clean_path($input));\n }", " public function dirtyPathsProvider()\n {\n $ds = DIRECTORY_SEPARATOR;", " return [\n [\n ROOTPATH . 'spark',\n 'ROOTPATH' . $ds . 'spark',\n ],\n [\n APPPATH . 'Config' . $ds . 'App.php',\n 'APPPATH' . $ds . 'Config' . $ds . 'App.php',\n ],\n [\n SYSTEMPATH . 'CodeIgniter.php',\n 'SYSTEMPATH' . $ds . 'CodeIgniter.php',\n ],\n [\n VENDORPATH . 'autoload.php',\n 'VENDORPATH' . $ds . 'autoload.php',\n ],\n [\n FCPATH . 'index.php',\n 'FCPATH' . $ds . 'index.php',\n ],\n ];\n }", " public function testIsCli()\n {\n $this->assertIsBool(is_cli());\n $this->assertTrue(is_cli());\n }", " public function testDWithCSP()\n {\n /** @var App $config */\n $config = config(App::class);\n $CSPEnabled = $config->CSPEnabled;\n $cliDetection = Kint::$cli_detection;", " $config->CSPEnabled = true;\n Kint::$cli_detection = false;", " $this->expectOutputRegex('/<script {csp-script-nonce} class=\"kint-rich-script\">/u');\n d('string');", " // Restore settings\n $config->CSPEnabled = $CSPEnabled;\n Kint::$cli_detection = $cliDetection;\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testTraceWithCSP()\n {\n /** @var App $config */\n $config = config(App::class);\n $config->CSPEnabled = true;\n Kint::$cli_detection = false;", " $this->expectOutputRegex('/<style {csp-style-nonce} class=\"kint-rich-style\">/u');\n trace();\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, 0, 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 ]
PreciseBugs
{"buggy_code_end_loc": [22, 818, 313, 129, 10], "buggy_code_start_loc": [22, 813, 304, 110, 10], "filenames": ["SECURITY.md", "system/Common.php", "tests/system/CommonFunctionsTest.php", "tests/system/HTTP/IncomingRequestTest.php", "user_guide_src/source/changelogs/v4.1.6.rst"], "fixing_code_end_loc": [24, 812, 346, 131, 16], "fixing_code_start_loc": [23, 812, 304, 110, 11], "message": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codeigniter:codeigniter:*:*:*:*:*:*:*:*", "matchCriteriaId": "5E18B755-8CBA-45C9-8759-5039BBAD4FC6", "versionEndExcluding": "4.1.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`."}, {"lang": "es", "value": "CodeIgniter es un framework web full-stack de PHP de c\u00f3digo abierto. Se encontr\u00f3 una deserializaci\u00f3n de datos no confiables en la funci\u00f3n \"old()\" en CodeIgniter4. Los atacantes remotos pueden inyectar objetos arbitrarios autocargables con esta vulnerabilidad, y posiblemente ejecutar c\u00f3digo PHP existente en el servidor. Tenemos conocimiento de una explotaci\u00f3n que funciona, que puede conllevar a una inyecci\u00f3n SQL. Se aconseja a usuarios que actualicen a la versi\u00f3n 4.1.6 o posterior. A los usuarios que no puedan actualizarse se les aconseja no usar la funci\u00f3n \"old()\" y form_helper ni \"RedirectResponse::withInput()\" y \"redirect()-&gt;withInput()\""}], "evaluatorComment": null, "id": "CVE-2022-21647", "lastModified": "2022-01-20T15:04:23.823", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.7, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-01-04T20:15:07.930", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-w6jr-wj64-mc9x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-502"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, "type": "CWE-502"}
240
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * This file is part of CodeIgniter 4 framework.\n *\n * (c) CodeIgniter Foundation <admin@codeigniter.com>\n *\n * For the full copyright and license information, please view\n * the LICENSE file that was distributed with this source code.\n */", "namespace CodeIgniter;", "use CodeIgniter\\Config\\BaseService;\nuse CodeIgniter\\Config\\Services;\nuse CodeIgniter\\HTTP\\RedirectResponse;\nuse CodeIgniter\\HTTP\\Response;\nuse CodeIgniter\\HTTP\\URI;\nuse CodeIgniter\\HTTP\\UserAgent;\nuse CodeIgniter\\Router\\RouteCollection;\nuse CodeIgniter\\Session\\Handlers\\FileHandler;\nuse CodeIgniter\\Session\\Session;\nuse CodeIgniter\\Test\\CIUnitTestCase;\nuse CodeIgniter\\Test\\Mock\\MockIncomingRequest;\nuse CodeIgniter\\Test\\Mock\\MockSecurity;\nuse CodeIgniter\\Test\\Mock\\MockSession;\nuse CodeIgniter\\Test\\TestLogger;\nuse Config\\App;\nuse Config\\Logger;\nuse Config\\Modules;\nuse InvalidArgumentException;\nuse Kint;\nuse stdClass;\nuse Tests\\Support\\Models\\JobModel;", "/**\n * @backupGlobals enabled\n *\n * @internal\n */\nfinal class CommonFunctionsTest extends CIUnitTestCase\n{\n protected function setUp(): void\n {\n unset($_ENV['foo'], $_SERVER['foo']);\n Services::reset();", " parent::setUp();\n }", " public function testStringifyAttributes()\n {\n $this->assertSame(' class=\"foo\" id=\"bar\"', stringify_attributes(['class' => 'foo', 'id' => 'bar']));", " $atts = new stdClass();\n $atts->class = 'foo';\n $atts->id = 'bar';\n $this->assertSame(' class=\"foo\" id=\"bar\"', stringify_attributes($atts));", " $atts = new stdClass();\n $this->assertSame('', stringify_attributes($atts));", " $this->assertSame(' class=\"foo\" id=\"bar\"', stringify_attributes('class=\"foo\" id=\"bar\"'));", " $this->assertSame('', stringify_attributes([]));\n }", " public function testStringifyJsAttributes()\n {\n $this->assertSame('width=800,height=600', stringify_attributes(['width' => '800', 'height' => '600'], true));", " $atts = new stdClass();\n $atts->width = 800;\n $atts->height = 600;\n $this->assertSame('width=800,height=600', stringify_attributes($atts, true));\n }", " public function testEnvReturnsDefault()\n {\n $this->assertSame('baz', env('foo', 'baz'));\n }", " public function testEnvGetsFromSERVER()\n {\n $_SERVER['foo'] = 'bar';", " $this->assertSame('bar', env('foo', 'baz'));\n }", " public function testEnvGetsFromENV()\n {\n $_ENV['foo'] = 'bar';", " $this->assertSame('bar', env('foo', 'baz'));\n }", " public function testEnvBooleans()\n {\n $_ENV['p1'] = 'true';\n $_ENV['p2'] = 'false';\n $_ENV['p3'] = 'empty';\n $_ENV['p4'] = 'null';", " $this->assertTrue(env('p1'));\n $this->assertFalse(env('p2'));\n $this->assertEmpty(env('p3'));\n $this->assertNull(env('p4'));\n }", " public function testRedirectReturnsRedirectResponse()\n {\n $_SERVER['REQUEST_METHOD'] = 'GET';", " $response = $this->createMock(Response::class);\n $routes = new RouteCollection(\n Services::locator(),\n new Modules()\n );\n \\CodeIgniter\\Services::injectMock('response', $response);\n \\CodeIgniter\\Services::injectMock('routes', $routes);", " $routes->add('home/base', 'Controller::index', ['as' => 'base']);\n $response->method('redirect')->willReturnArgument(0);", " $this->assertInstanceOf(RedirectResponse::class, redirect('base'));\n }", " public function testRedirectDefault()\n {\n $this->assertInstanceOf(RedirectResponse::class, redirect());\n }", " public function testView()\n {\n $data = [\n 'testString' => 'bar',\n 'bar' => 'baz',\n ];\n $expected = '<h1>bar</h1>';\n $this->assertStringContainsString($expected, view('\\Tests\\Support\\View\\Views\\simple', $data));\n }", " public function testViewSavedData()\n {\n $data = [\n 'testString' => 'bar',\n 'bar' => 'baz',\n ];\n $expected = '<h1>bar</h1>';\n $this->assertStringContainsString($expected, view('\\Tests\\Support\\View\\Views\\simple', $data, ['saveData' => true]));\n $this->assertStringContainsString($expected, view('\\Tests\\Support\\View\\Views\\simple'));\n }", " public function testViewCell()\n {\n $expected = 'Hello';\n $this->assertSame($expected, view_cell('\\Tests\\Support\\View\\SampleClass::hello'));\n }", " public function testEscapeWithDifferentEncodings()\n {\n $this->assertSame('&lt;x', esc('<x', 'html', 'utf-8'));\n $this->assertSame('&lt;x', esc('<x', 'html', 'iso-8859-1'));\n $this->assertSame('&lt;x', esc('<x', 'html', 'windows-1251'));\n }", " public function testEscapeBadContext()\n {\n $this->expectException(InvalidArgumentException::class);\n esc(['width' => '800', 'height' => '600'], 'bogus');\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testSessionInstance()\n {\n $this->injectSessionMock();", " $this->assertInstanceOf(Session::class, session());\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testSessionVariable()\n {\n $this->injectSessionMock();", " $_SESSION['notbogus'] = 'Hi there';", " $this->assertSame('Hi there', session('notbogus'));\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testSessionVariableNotThere()\n {\n $this->injectSessionMock();", " $_SESSION['bogus'] = 'Hi there';\n $this->assertNull(session('notbogus'));\n }", " public function testRouteTo()\n {\n // prime the pump\n $routes = service('routes');\n $routes->add('path/(:any)/to/(:num)', 'myController::goto/$1/$2');", " $this->assertSame('/path/string/to/13', route_to('myController::goto', 'string', 13));\n }", " public function testInvisible()\n {\n $this->assertSame('Javascript', remove_invisible_characters(\"Java\\0script\"));\n }", " public function testInvisibleEncoded()\n {\n $this->assertSame('Javascript', remove_invisible_characters('Java%0cscript'));\n }", " public function testAppTimezone()\n {\n $this->assertSame('America/Chicago', app_timezone());\n }", " public function testCSRFToken()\n {\n Services::injectMock('security', new MockSecurity(new App()));", " $this->assertSame('csrf_test_name', csrf_token());\n }", " public function testCSRFHeader()\n {\n $this->assertSame('X-CSRF-TOKEN', csrf_header());\n }", " public function testHash()\n {\n $this->assertSame(32, strlen(csrf_hash()));\n }", " public function testCSRFField()\n {\n $this->assertStringContainsString('<input type=\"hidden\" ', csrf_field());\n }", " public function testCSRFMeta()\n {\n $this->assertStringContainsString('<meta name=\"X-CSRF-TOKEN\" ', csrf_meta());\n }", " public function testModelNotExists()\n {\n $this->assertNull(model(UnexsistenceClass::class));\n }", " public function testModelExistsBasename()\n {\n $this->assertInstanceOf(JobModel::class, model('JobModel'));\n }", " public function testModelExistsClassname()\n {\n $this->assertInstanceOf(JobModel::class, model(JobModel::class));\n }", " public function testModelExistsAbsoluteClassname()\n {\n $this->assertInstanceOf(JobModel::class, model('\\Tests\\Support\\Models\\JobModel'));\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testOldInput()\n {\n $this->injectSessionMock();\n // setup from RedirectResponseTest...\n $_SERVER['REQUEST_METHOD'] = 'GET';", " $this->config = new App();\n $this->config->baseURL = 'http://example.com/';", " $this->routes = new RouteCollection(Services::locator(), new Modules());\n Services::injectMock('routes', $this->routes);", " $this->request = new MockIncomingRequest($this->config, new URI('http://example.com'), null, new UserAgent());\n Services::injectMock('request', $this->request);", " // setup & ask for a redirect...\n $_SESSION = [];\n $_GET = ['foo' => 'bar'];\n $_POST = [\n 'bar' => 'baz',", " 'zibble' => 'fritz',", " ];", " $response = new RedirectResponse(new App());\n $response->withInput();", " $this->assertSame('bar', old('foo')); // regular parameter\n $this->assertSame('doo', old('yabba dabba', 'doo')); // non-existing parameter", " $this->assertSame('fritz', old('zibble'));\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testOldInputSerializeData()\n {\n $this->injectSessionMock();\n // setup from RedirectResponseTest...\n $_SERVER['REQUEST_METHOD'] = 'GET';", " $this->config = new App();\n $this->config->baseURL = 'http://example.com/';", " $this->routes = new RouteCollection(Services::locator(), new Modules());\n Services::injectMock('routes', $this->routes);", " $this->request = new MockIncomingRequest($this->config, new URI('http://example.com'), null, new UserAgent());\n Services::injectMock('request', $this->request);", " // setup & ask for a redirect...\n $_SESSION = [];\n $_GET = [];\n $_POST = [\n 'zibble' => serialize('fritz'),\n ];", " $response = new RedirectResponse(new App());\n $response->withInput();", " // serialized parameters are only HTML-escaped.\n $this->assertSame('s:5:&quot;fritz&quot;;', old('zibble'));", " }", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/1492\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testOldInputArray()\n {\n $this->injectSessionMock();\n // setup from RedirectResponseTest...\n $_SERVER['REQUEST_METHOD'] = 'GET';", " $this->config = new App();\n $this->config->baseURL = 'http://example.com/';", " $this->routes = new RouteCollection(Services::locator(), new Modules());\n Services::injectMock('routes', $this->routes);", " $this->request = new MockIncomingRequest($this->config, new URI('http://example.com'), null, new UserAgent());\n Services::injectMock('request', $this->request);", " $locations = [\n 'AB' => 'Alberta',\n 'BC' => 'British Columbia',\n 'SK' => 'Saskatchewan',\n ];", " // setup & ask for a redirect...\n $_SESSION = [];\n $_GET = [];\n $_POST = ['location' => $locations];", " $response = new RedirectResponse(new App());\n $response->withInput();", " $this->assertSame($locations, old('location'));\n }", " public function testReallyWritable()\n {\n // cannot test fully on *nix\n $this->assertTrue(is_really_writable(WRITEPATH));\n }", " public function testSlashItem()\n {\n $this->assertSame('/', slash_item('cookiePath')); // slash already there\n $this->assertSame('', slash_item('cookieDomain')); // empty, so untouched\n $this->assertSame('en/', slash_item('defaultLocale')); // slash appended\n }", " protected function injectSessionMock()\n {\n $defaults = [\n 'sessionDriver' => 'CodeIgniter\\Session\\Handlers\\FileHandler',\n 'sessionCookieName' => 'ci_session',\n 'sessionExpiration' => 7200,\n 'sessionSavePath' => null,\n 'sessionMatchIP' => false,\n 'sessionTimeToUpdate' => 300,\n 'sessionRegenerateDestroy' => false,\n 'cookieDomain' => '',\n 'cookiePrefix' => '',\n 'cookiePath' => '/',\n 'cookieSecure' => false,\n 'cookieSameSite' => 'Lax',\n ];", " $appConfig = new App();", " foreach ($defaults as $key => $config) {\n $appConfig->{$key} = $config;\n }", " $session = new MockSession(new FileHandler($appConfig, '127.0.0.1'), $appConfig);\n $session->setLogger(new TestLogger(new Logger()));\n BaseService::injectMock('session', $session);\n }", " // Make sure cookies are set by RedirectResponse this way\n // See https://github.com/codeigniter4/CodeIgniter4/issues/1393\n public function testRedirectResponseCookies1()\n {\n $loginTime = time();", " $routes = service('routes');\n $routes->add('user/login', 'Auth::verify', ['as' => 'login']);", " $answer1 = redirect()->route('login')\n ->setCookie('foo', 'onething', YEAR)\n ->setCookie('login_time', $loginTime, YEAR);", " $this->assertTrue($answer1->hasCookie('foo', 'onething'));\n $this->assertTrue($answer1->hasCookie('login_time'));\n }", " public function testTrace()\n {\n ob_start();\n trace();\n $content = ob_get_clean();", " $this->assertStringContainsString('Debug Backtrace', $content);\n }", " public function testViewNotSaveData()\n {\n $data = [\n 'testString' => 'bar',\n 'bar' => 'baz',\n ];\n $this->assertStringContainsString('<h1>bar</h1>', view('\\Tests\\Support\\View\\Views\\simples', $data, ['saveData' => false]));\n $this->assertStringContainsString('<h1>is_not</h1>', view('\\Tests\\Support\\View\\Views\\simples'));\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testForceHttpsNullRequestAndResponse()\n {\n $this->assertNull(Services::response()->header('Location'));", " force_https();", " $this->assertSame('https://example.com/', Services::response()->header('Location')->getValue());\n }", " /**\n * @dataProvider dirtyPathsProvider\n *\n * @param mixed $input\n * @param mixed $expected\n */\n public function testCleanPathActuallyCleaningThePaths($input, $expected)\n {\n $this->assertSame($expected, clean_path($input));\n }", " public function dirtyPathsProvider()\n {\n $ds = DIRECTORY_SEPARATOR;", " return [\n [\n ROOTPATH . 'spark',\n 'ROOTPATH' . $ds . 'spark',\n ],\n [\n APPPATH . 'Config' . $ds . 'App.php',\n 'APPPATH' . $ds . 'Config' . $ds . 'App.php',\n ],\n [\n SYSTEMPATH . 'CodeIgniter.php',\n 'SYSTEMPATH' . $ds . 'CodeIgniter.php',\n ],\n [\n VENDORPATH . 'autoload.php',\n 'VENDORPATH' . $ds . 'autoload.php',\n ],\n [\n FCPATH . 'index.php',\n 'FCPATH' . $ds . 'index.php',\n ],\n ];\n }", " public function testIsCli()\n {\n $this->assertIsBool(is_cli());\n $this->assertTrue(is_cli());\n }", " public function testDWithCSP()\n {\n /** @var App $config */\n $config = config(App::class);\n $CSPEnabled = $config->CSPEnabled;\n $cliDetection = Kint::$cli_detection;", " $config->CSPEnabled = true;\n Kint::$cli_detection = false;", " $this->expectOutputRegex('/<script {csp-script-nonce} class=\"kint-rich-script\">/u');\n d('string');", " // Restore settings\n $config->CSPEnabled = $CSPEnabled;\n Kint::$cli_detection = $cliDetection;\n }", " /**\n * @runInSeparateProcess\n * @preserveGlobalState disabled\n */\n public function testTraceWithCSP()\n {\n /** @var App $config */\n $config = config(App::class);\n $config->CSPEnabled = true;\n Kint::$cli_detection = false;", " $this->expectOutputRegex('/<style {csp-style-nonce} class=\"kint-rich-style\">/u');\n trace();\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 ]
PreciseBugs
{"buggy_code_end_loc": [22, 818, 313, 129, 10], "buggy_code_start_loc": [22, 813, 304, 110, 10], "filenames": ["SECURITY.md", "system/Common.php", "tests/system/CommonFunctionsTest.php", "tests/system/HTTP/IncomingRequestTest.php", "user_guide_src/source/changelogs/v4.1.6.rst"], "fixing_code_end_loc": [24, 812, 346, 131, 16], "fixing_code_start_loc": [23, 812, 304, 110, 11], "message": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codeigniter:codeigniter:*:*:*:*:*:*:*:*", "matchCriteriaId": "5E18B755-8CBA-45C9-8759-5039BBAD4FC6", "versionEndExcluding": "4.1.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`."}, {"lang": "es", "value": "CodeIgniter es un framework web full-stack de PHP de c\u00f3digo abierto. Se encontr\u00f3 una deserializaci\u00f3n de datos no confiables en la funci\u00f3n \"old()\" en CodeIgniter4. Los atacantes remotos pueden inyectar objetos arbitrarios autocargables con esta vulnerabilidad, y posiblemente ejecutar c\u00f3digo PHP existente en el servidor. Tenemos conocimiento de una explotaci\u00f3n que funciona, que puede conllevar a una inyecci\u00f3n SQL. Se aconseja a usuarios que actualicen a la versi\u00f3n 4.1.6 o posterior. A los usuarios que no puedan actualizarse se les aconseja no usar la funci\u00f3n \"old()\" y form_helper ni \"RedirectResponse::withInput()\" y \"redirect()-&gt;withInput()\""}], "evaluatorComment": null, "id": "CVE-2022-21647", "lastModified": "2022-01-20T15:04:23.823", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.7, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-01-04T20:15:07.930", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-w6jr-wj64-mc9x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-502"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, "type": "CWE-502"}
240
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * This file is part of CodeIgniter 4 framework.\n *\n * (c) CodeIgniter Foundation <admin@codeigniter.com>\n *\n * For the full copyright and license information, please view\n * the LICENSE file that was distributed with this source code.\n */", "namespace CodeIgniter\\HTTP;", "use CodeIgniter\\HTTP\\Exceptions\\HTTPException;\nuse CodeIgniter\\HTTP\\Files\\UploadedFile;\nuse CodeIgniter\\Test\\CIUnitTestCase;\nuse Config\\App;", "/**\n * @backupGlobals enabled\n *\n * @internal\n */\nfinal class IncomingRequestTest extends CIUnitTestCase\n{\n /**\n * @var IncomingRequest\n */\n protected $request;", " protected function setUp(): void\n {\n parent::setUp();", " $this->request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $_POST = $_GET = $_SERVER = $_REQUEST = $_ENV = $_COOKIE = $_SESSION = [];\n }", " public function testCanGrabRequestVars()\n {\n $_REQUEST['TEST'] = 5;", " $this->assertSame('5', $this->request->getVar('TEST'));\n $this->assertNull($this->request->getVar('TESTY'));\n }", " public function testCanGrabGetVars()\n {\n $_GET['TEST'] = 5;", " $this->assertSame('5', $this->request->getGet('TEST'));\n $this->assertNull($this->request->getGet('TESTY'));\n }", " public function testCanGrabPostVars()\n {\n $_POST['TEST'] = 5;", " $this->assertSame('5', $this->request->getPost('TEST'));\n $this->assertNull($this->request->getPost('TESTY'));\n }", " public function testCanGrabPostBeforeGet()\n {\n $_POST['TEST'] = 5;\n $_GET['TEST'] = 3;", " $this->assertSame('5', $this->request->getPostGet('TEST'));\n $this->assertSame('3', $this->request->getGetPost('TEST'));\n }", " public function testNoOldInput()\n {\n $this->assertNull($this->request->getOldInput('name'));\n }", " public function testCanGetOldInput()\n {\n $_SESSION['_ci_old_input'] = [\n 'get' => ['one' => 'two'],\n 'post' => ['name' => 'foo'],\n ];", " $this->assertSame('foo', $this->request->getOldInput('name'));\n $this->assertSame('two', $this->request->getOldInput('one'));\n }", " public function testCanGetOldInputDotted()\n {\n $_SESSION['_ci_old_input'] = [\n 'get' => ['apple' => ['name' => 'two']],\n 'post' => ['banana' => ['name' => 'foo']],\n ];", " $this->assertSame('foo', $this->request->getOldInput('banana.name'));\n $this->assertSame('two', $this->request->getOldInput('apple.name'));\n }", " public function testMissingOldInput()\n {\n $_SESSION['_ci_old_input'] = [\n 'get' => ['apple' => ['name' => 'two']],\n 'post' => ['banana' => ['name' => 'foo']],\n ];", " $this->assertNull($this->request->getOldInput('pineapple.name'));\n }\n", " // Reference: https://github.com/codeigniter4/CodeIgniter4/issues/1492\n public function testCanGetOldInputArray()", " {\n $_SESSION['_ci_old_input'] = [\n 'get' => ['apple' => ['name' => 'two']],\n 'post' => ['banana' => ['name' => 'foo']],\n ];", " $this->assertSame(['name' => 'two'], $this->request->getOldInput('apple'));\n $this->assertSame(['name' => 'foo'], $this->request->getOldInput('banana'));\n }\n", " // Reference: https://github.com/codeigniter4/CodeIgniter4/issues/1492", " /**", " * @runInSeparateProcess\n * @preserveGlobalState disabled\n */", " public function testCanSerializeOldArray()", " {\n $locations = [\n 'AB' => 'Alberta',\n 'BC' => 'British Columbia',\n 'SK' => 'Saskatchewan',\n ];\n $session = service('session');\n $session->set(['_ci_old_input' => ['post' => ['location' => $locations]]]);", " $this->assertSame($locations, $this->request->getOldInput('location'));\n }", " public function testCanGrabServerVars()\n {\n $server = $this->getPrivateProperty($this->request, 'globals');\n $server['server']['TEST'] = 5;\n $this->setPrivateProperty($this->request, 'globals', $server);", " $this->assertSame('5', $this->request->getServer('TEST'));\n $this->assertNull($this->request->getServer('TESTY'));\n }", " public function testCanGrabEnvVars()\n {\n $server = $this->getPrivateProperty($this->request, 'globals');\n $server['env']['TEST'] = 5;\n $this->setPrivateProperty($this->request, 'globals', $server);", " $this->assertSame('5', $this->request->getEnv('TEST'));\n $this->assertNull($this->request->getEnv('TESTY'));\n }", " public function testCanGrabCookieVars()\n {\n $_COOKIE['TEST'] = 5;", " $this->assertSame('5', $this->request->getCookie('TEST'));\n $this->assertNull($this->request->getCookie('TESTY'));\n }", " public function testStoresDefaultLocale()\n {\n $config = new App();", " $this->assertSame($config->defaultLocale, $this->request->getDefaultLocale());\n $this->assertSame($config->defaultLocale, $this->request->getLocale());\n }", " public function testSetLocaleSaves()\n {\n $config = new App();\n $config->supportedLocales = ['en', 'es'];\n $config->defaultLocale = 'es';\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), null, new UserAgent());", " $request->setLocale('en');\n $this->assertSame('en', $request->getLocale());\n }", " public function testSetBadLocale()\n {\n $config = new App();\n $config->supportedLocales = ['en', 'es'];\n $config->defaultLocale = 'es';\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), null, new UserAgent());", " $request->setLocale('xx');\n $this->assertSame('es', $request->getLocale());\n }", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/2774\n */\n public function testNegotiatesLocale()\n {\n $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'fr-FR; q=1.0, en; q=0.5';", " $config = new App();\n $config->negotiateLocale = true;\n $config->supportedLocales = ['fr', 'en'];\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), null, new UserAgent());", " $this->assertSame($config->defaultLocale, $request->getDefaultLocale());\n $this->assertSame('fr', $request->getLocale());\n }", " public function testNegotiatesLocaleOnlyBroad()\n {\n $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'fr; q=1.0, en; q=0.5';", " $config = new App();\n $config->negotiateLocale = true;\n $config->supportedLocales = ['fr', 'en'];\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), null, new UserAgent());", " $this->assertSame($config->defaultLocale, $request->getDefaultLocale());\n $this->assertSame('fr', $request->getLocale());\n }", " // The negotiation tests below are not intended to exercise the HTTP\\Negotiate class -\n // that is up to the NegotiateTest. These are only to make sure that the requests\n // flow through to the negotiator", " public function testNegotiatesNot()\n {\n $this->request->setHeader('Accept-Charset', 'iso-8859-5, unicode-1-1;q=0.8');", " $this->expectException(HTTPException::class);\n $this->request->negotiate('something bogus', ['iso-8859-5', 'unicode-1-1']);\n }", " public function testNegotiatesCharset()\n {\n // $_SERVER['HTTP_ACCEPT_CHARSET'] = 'iso-8859-5, unicode-1-1;q=0.8';\n $this->request->setHeader('Accept-Charset', 'iso-8859-5, unicode-1-1;q=0.8');", " $this->assertSame(strtolower($this->request->config->charset), $this->request->negotiate('charset', ['iso-8859', 'unicode-1-2']));\n }", " public function testNegotiatesMedia()\n {\n $this->request->setHeader('Accept', 'text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c');\n $this->assertSame('text/html', $this->request->negotiate('media', ['text/html', 'text/x-c', 'text/x-dvi', 'text/plain']));\n }", " public function testNegotiatesEncoding()\n {\n $this->request->setHeader('Accept-Encoding', 'gzip;q=1.0, identity; q=0.4, compress;q=0.5');\n $this->assertSame('gzip', $this->request->negotiate('encoding', ['gzip', 'compress']));\n }", " public function testNegotiatesLanguage()\n {\n $this->request->setHeader('Accept-Language', 'da, en-gb;q=0.8, en;q=0.7');\n $this->assertSame('en', $this->request->negotiate('language', ['en', 'da']));\n }", " public function testCanGrabGetRawJSON()\n {\n $json = '{\"code\":1, \"message\":\"ok\"}';", " $expected = ['code' => 1, 'message' => 'ok'];", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $this->assertSame($expected, $request->getJSON(true));\n }", " public function testCanGetAVariableFromJson()\n {\n $jsonObj = [\n 'foo' => 'bar',\n 'baz' => ['fizz' => 'buzz'],\n ];\n $json = json_encode($jsonObj);", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $this->assertSame('bar', $request->getJsonVar('foo'));\n $this->assertNull($request->getJsonVar('notExists'));", " $jsonVar = $request->getJsonVar('baz');\n $this->assertIsObject($jsonVar);\n $this->assertSame('buzz', $jsonVar->fizz);\n $this->assertSame('buzz', $request->getJsonVar('baz.fizz'));\n }", " public function testGetJsonVarAsArray()\n {\n $jsonObj = [\n 'baz' => [\n 'fizz' => 'buzz',\n 'foo' => 'bar',\n ],\n ];\n $json = json_encode($jsonObj);", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $jsonVar = $request->getJsonVar('baz', true);\n $this->assertIsArray($jsonVar);\n $this->assertSame('buzz', $jsonVar['fizz']);\n $this->assertSame('bar', $jsonVar['foo']);\n }", " public function testGetJsonVarCanFilter()\n {\n $json = json_encode(['foo' => 'bar']);", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $this->assertFalse($request->getJsonVar('foo', false, FILTER_VALIDATE_INT));\n }", " public function testGetVarWorksWithJson()\n {\n $json = json_encode(['foo' => 'bar', 'fizz' => 'buzz']);", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $json, new UserAgent());\n $request->setHeader('Content-Type', 'application/json');", " $this->assertSame('bar', $request->getVar('foo'));\n $this->assertSame('buzz', $request->getVar('fizz'));\n $this->assertNull($request->getVar('notExists'));", " $multiple = $request->getVar(['foo', 'fizz']);\n $this->assertIsArray($multiple);\n $this->assertSame('bar', $multiple['foo']);\n $this->assertSame('buzz', $multiple['fizz']);", " $all = $request->getVar();\n $this->assertIsObject($all);\n $this->assertSame('bar', $all->foo);\n $this->assertSame('buzz', $all->fizz);\n }", " public function testGetVarWorksWithJsonAndGetParams()\n {\n $config = new App();\n $config->baseURL = 'http://example.com/';", " // GET method\n $_REQUEST['foo'] = 'bar';\n $_REQUEST['fizz'] = 'buzz';", " $request = new IncomingRequest($config, new URI('http://example.com/path?foo=bar&fizz=buzz'), 'php://input', new UserAgent());\n $request = $request->withMethod('GET');", " // JSON type\n $request->setHeader('Content-Type', 'application/json');", " $this->assertSame('bar', $request->getVar('foo'));\n $this->assertSame('buzz', $request->getVar('fizz'));", " $multiple = $request->getVar(['foo', 'fizz']);\n $this->assertIsArray($multiple);\n $this->assertSame('bar', $multiple['foo']);\n $this->assertSame('buzz', $multiple['fizz']);", " $all = $request->getVar();\n $this->assertIsArray($all);\n $this->assertSame('bar', $all['foo']);\n $this->assertSame('buzz', $all['fizz']);\n }", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/5391\n */\n public function testGetJsonVarReturnsNullFromNullBody()\n {\n $config = new App();\n $config->baseURL = 'http://example.com/';\n $json = null;\n $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $this->assertNull($request->getJsonVar('myKey'));\n }", " public function testgetJSONReturnsNullFromNullBody()\n {\n $config = new App();\n $config->baseURL = 'http://example.com/';\n $json = null;\n $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $this->assertNull($request->getJSON());\n }", " public function testCanGrabGetRawInput()\n {\n $rawstring = 'username=admin001&role=administrator&usepass=0';", " $expected = [\n 'username' => 'admin001',\n 'role' => 'administrator',\n 'usepass' => '0',\n ];", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $rawstring, new UserAgent());", " $this->assertSame($expected, $request->getRawInput());\n }", " public function testIsCLI()\n {\n // this should be the case in unit testing\n $this->assertTrue($this->request->isCLI());\n }", " public function testIsAJAX()\n {\n $this->request->appendHeader('X-Requested-With', 'XMLHttpRequest');\n $this->assertTrue($this->request->isAJAX());\n }", " public function testIsSecure()\n {\n $_SERVER['HTTPS'] = 'on';\n $this->assertTrue($this->request->isSecure());\n }", " public function testIsSecureFrontEnd()\n {\n $this->request->appendHeader('Front-End-Https', 'on');\n $this->assertTrue($this->request->isSecure());\n }", " public function testIsSecureForwarded()\n {\n $this->request->appendHeader('X-Forwarded-Proto', 'https');\n $this->assertTrue($this->request->isSecure());\n }", " public function testUserAgent()\n {\n $_SERVER['HTTP_USER_AGENT'] = 'Mozilla';", " $config = new App();\n $request = new IncomingRequest($config, new URI(), null, new UserAgent());", " $this->assertSame('Mozilla', $request->getUserAgent()->__toString());\n }", " public function testFileCollectionFactory()\n {\n $_FILES = [\n 'userfile' => [\n 'name' => 'someFile.txt',\n 'type' => 'text/plain',\n 'size' => '124',\n 'tmp_name' => '/tmp/myTempFile.txt',\n 'error' => 0,\n ],\n ];", " $files = $this->request->getFiles();\n $this->assertCount(1, $files);", " $file = array_shift($files);\n $this->assertInstanceOf(UploadedFile::class, $file);", " $this->assertSame('someFile.txt', $file->getName());\n $this->assertSame(124, $file->getSize());\n }", " public function testGetFileMultiple()\n {\n $_FILES = [\n 'userfile' => [\n 'name' => [\n 'someFile.txt',\n 'someFile2.txt',\n ],\n 'type' => [\n 'text/plain',\n 'text/plain',\n ],\n 'size' => [\n '124',\n '125',\n ],\n 'tmp_name' => [\n '/tmp/myTempFile.txt',\n '/tmp/myTempFile2.txt',\n ],\n 'error' => [\n 0,\n 0,\n ],\n ],\n ];", " $gotit = $this->request->getFileMultiple('userfile');\n $this->assertSame(124, $gotit[0]->getSize());\n $this->assertSame(125, $gotit[1]->getSize());\n }", " public function testGetFile()\n {\n $_FILES = [\n 'userfile' => [\n 'name' => 'someFile.txt',\n 'type' => 'text/plain',\n 'size' => '124',\n 'tmp_name' => '/tmp/myTempFile.txt',\n 'error' => 0,\n ],\n ];", " $gotit = $this->request->getFile('userfile');\n $this->assertSame(124, $gotit->getSize());\n }", " public function testSpoofing()\n {\n $this->request->setMethod('WINK');\n $this->assertSame('wink', $this->request->getMethod());\n }", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/2839\n */\n public function testGetPostEmpty()\n {\n $_POST['TEST'] = '5';\n $_GET['TEST'] = '3';\n $this->assertSame($_POST, $this->request->getPostGet());\n $this->assertSame($_GET, $this->request->getGetPost());\n }", " public function testWithFalseBody()\n {\n // Use `false` here to simulate file_get_contents returning a false value\n $request = new IncomingRequest(new App(), new URI(), false, new UserAgent());", " $this->assertNotFalse($request->getBody());\n $this->assertNull($request->getBody());\n }", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/3020\n */\n public function testGetPostIndexNotExists()\n {\n $_POST['TEST'] = 5;\n $_GET['TEST'] = 3;\n $this->assertNull($this->request->getPostGet('gc'));\n $this->assertNull($this->request->getGetPost('gc'));\n }", " public function providePathChecks()\n {\n return [\n 'not /index.php' => [\n '/test.php',\n '/',\n ],\n '/index.php' => [\n '/index.php',\n '/',\n ],\n ];\n }", " /**\n * @dataProvider providePathChecks\n *\n * @param mixed $path\n * @param mixed $detectPath\n */\n public function testExtensionPHP($path, $detectPath)\n {\n $config = new App();\n $config->baseURL = 'http://example.com/';", " $_SERVER['REQUEST_URI'] = $path;\n $_SERVER['SCRIPT_NAME'] = $path;\n $request = new IncomingRequest($config, new URI($path), null, new UserAgent());\n $this->assertSame($detectPath, $request->detectPath());\n }", " public function testGetPath()\n {\n $_SERVER['REQUEST_URI'] = '/index.php/fruits/banana';\n $_SERVER['SCRIPT_NAME'] = '/index.php';", " $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $this->assertSame('fruits/banana', $request->getPath());\n }", " public function testGetPathIsRelative()\n {\n $_SERVER['REQUEST_URI'] = '/sub/folder/index.php/fruits/banana';\n $_SERVER['SCRIPT_NAME'] = '/sub/folder/index.php';", " $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $this->assertSame('fruits/banana', $request->getPath());\n }", " public function testGetPathStoresDetectedValue()\n {\n $_SERVER['REQUEST_URI'] = '/fruits/banana';\n $_SERVER['SCRIPT_NAME'] = '/index.php';", " $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $_SERVER['REQUEST_URI'] = '/candy/snickers';", " $this->assertSame('fruits/banana', $request->getPath());\n }", " public function testGetPathIsRediscovered()\n {\n $_SERVER['REQUEST_URI'] = '/fruits/banana';\n $_SERVER['SCRIPT_NAME'] = '/index.php';", " $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $_SERVER['REQUEST_URI'] = '/candy/snickers';\n $request->detectPath();", " $this->assertSame('candy/snickers', $request->getPath());\n }", " public function testSetPath()\n {\n $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());\n $this->assertSame('', $request->getPath());", " $request->setPath('foobar');\n $this->assertSame('foobar', $request->getPath());\n }", " public function testSetPathUpdatesURI()\n {\n $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $request->setPath('apples');", " $this->assertSame('apples', $request->getUri()->getPath());\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, 0, 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 ]
PreciseBugs
{"buggy_code_end_loc": [22, 818, 313, 129, 10], "buggy_code_start_loc": [22, 813, 304, 110, 10], "filenames": ["SECURITY.md", "system/Common.php", "tests/system/CommonFunctionsTest.php", "tests/system/HTTP/IncomingRequestTest.php", "user_guide_src/source/changelogs/v4.1.6.rst"], "fixing_code_end_loc": [24, 812, 346, 131, 16], "fixing_code_start_loc": [23, 812, 304, 110, 11], "message": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codeigniter:codeigniter:*:*:*:*:*:*:*:*", "matchCriteriaId": "5E18B755-8CBA-45C9-8759-5039BBAD4FC6", "versionEndExcluding": "4.1.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`."}, {"lang": "es", "value": "CodeIgniter es un framework web full-stack de PHP de c\u00f3digo abierto. Se encontr\u00f3 una deserializaci\u00f3n de datos no confiables en la funci\u00f3n \"old()\" en CodeIgniter4. Los atacantes remotos pueden inyectar objetos arbitrarios autocargables con esta vulnerabilidad, y posiblemente ejecutar c\u00f3digo PHP existente en el servidor. Tenemos conocimiento de una explotaci\u00f3n que funciona, que puede conllevar a una inyecci\u00f3n SQL. Se aconseja a usuarios que actualicen a la versi\u00f3n 4.1.6 o posterior. A los usuarios que no puedan actualizarse se les aconseja no usar la funci\u00f3n \"old()\" y form_helper ni \"RedirectResponse::withInput()\" y \"redirect()-&gt;withInput()\""}], "evaluatorComment": null, "id": "CVE-2022-21647", "lastModified": "2022-01-20T15:04:23.823", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.7, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-01-04T20:15:07.930", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-w6jr-wj64-mc9x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-502"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, "type": "CWE-502"}
240
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * This file is part of CodeIgniter 4 framework.\n *\n * (c) CodeIgniter Foundation <admin@codeigniter.com>\n *\n * For the full copyright and license information, please view\n * the LICENSE file that was distributed with this source code.\n */", "namespace CodeIgniter\\HTTP;", "use CodeIgniter\\HTTP\\Exceptions\\HTTPException;\nuse CodeIgniter\\HTTP\\Files\\UploadedFile;\nuse CodeIgniter\\Test\\CIUnitTestCase;\nuse Config\\App;", "/**\n * @backupGlobals enabled\n *\n * @internal\n */\nfinal class IncomingRequestTest extends CIUnitTestCase\n{\n /**\n * @var IncomingRequest\n */\n protected $request;", " protected function setUp(): void\n {\n parent::setUp();", " $this->request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $_POST = $_GET = $_SERVER = $_REQUEST = $_ENV = $_COOKIE = $_SESSION = [];\n }", " public function testCanGrabRequestVars()\n {\n $_REQUEST['TEST'] = 5;", " $this->assertSame('5', $this->request->getVar('TEST'));\n $this->assertNull($this->request->getVar('TESTY'));\n }", " public function testCanGrabGetVars()\n {\n $_GET['TEST'] = 5;", " $this->assertSame('5', $this->request->getGet('TEST'));\n $this->assertNull($this->request->getGet('TESTY'));\n }", " public function testCanGrabPostVars()\n {\n $_POST['TEST'] = 5;", " $this->assertSame('5', $this->request->getPost('TEST'));\n $this->assertNull($this->request->getPost('TESTY'));\n }", " public function testCanGrabPostBeforeGet()\n {\n $_POST['TEST'] = 5;\n $_GET['TEST'] = 3;", " $this->assertSame('5', $this->request->getPostGet('TEST'));\n $this->assertSame('3', $this->request->getGetPost('TEST'));\n }", " public function testNoOldInput()\n {\n $this->assertNull($this->request->getOldInput('name'));\n }", " public function testCanGetOldInput()\n {\n $_SESSION['_ci_old_input'] = [\n 'get' => ['one' => 'two'],\n 'post' => ['name' => 'foo'],\n ];", " $this->assertSame('foo', $this->request->getOldInput('name'));\n $this->assertSame('two', $this->request->getOldInput('one'));\n }", " public function testCanGetOldInputDotted()\n {\n $_SESSION['_ci_old_input'] = [\n 'get' => ['apple' => ['name' => 'two']],\n 'post' => ['banana' => ['name' => 'foo']],\n ];", " $this->assertSame('foo', $this->request->getOldInput('banana.name'));\n $this->assertSame('two', $this->request->getOldInput('apple.name'));\n }", " public function testMissingOldInput()\n {\n $_SESSION['_ci_old_input'] = [\n 'get' => ['apple' => ['name' => 'two']],\n 'post' => ['banana' => ['name' => 'foo']],\n ];", " $this->assertNull($this->request->getOldInput('pineapple.name'));\n }\n", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/1492\n */\n public function testCanGetOldInputArrayWithSESSION()", " {\n $_SESSION['_ci_old_input'] = [\n 'get' => ['apple' => ['name' => 'two']],\n 'post' => ['banana' => ['name' => 'foo']],\n ];", " $this->assertSame(['name' => 'two'], $this->request->getOldInput('apple'));\n $this->assertSame(['name' => 'foo'], $this->request->getOldInput('banana'));\n }\n", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/1492\n *", " * @runInSeparateProcess\n * @preserveGlobalState disabled\n */", " public function testCanGetOldInputArrayWithSessionService()", " {\n $locations = [\n 'AB' => 'Alberta',\n 'BC' => 'British Columbia',\n 'SK' => 'Saskatchewan',\n ];\n $session = service('session');\n $session->set(['_ci_old_input' => ['post' => ['location' => $locations]]]);", " $this->assertSame($locations, $this->request->getOldInput('location'));\n }", " public function testCanGrabServerVars()\n {\n $server = $this->getPrivateProperty($this->request, 'globals');\n $server['server']['TEST'] = 5;\n $this->setPrivateProperty($this->request, 'globals', $server);", " $this->assertSame('5', $this->request->getServer('TEST'));\n $this->assertNull($this->request->getServer('TESTY'));\n }", " public function testCanGrabEnvVars()\n {\n $server = $this->getPrivateProperty($this->request, 'globals');\n $server['env']['TEST'] = 5;\n $this->setPrivateProperty($this->request, 'globals', $server);", " $this->assertSame('5', $this->request->getEnv('TEST'));\n $this->assertNull($this->request->getEnv('TESTY'));\n }", " public function testCanGrabCookieVars()\n {\n $_COOKIE['TEST'] = 5;", " $this->assertSame('5', $this->request->getCookie('TEST'));\n $this->assertNull($this->request->getCookie('TESTY'));\n }", " public function testStoresDefaultLocale()\n {\n $config = new App();", " $this->assertSame($config->defaultLocale, $this->request->getDefaultLocale());\n $this->assertSame($config->defaultLocale, $this->request->getLocale());\n }", " public function testSetLocaleSaves()\n {\n $config = new App();\n $config->supportedLocales = ['en', 'es'];\n $config->defaultLocale = 'es';\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), null, new UserAgent());", " $request->setLocale('en');\n $this->assertSame('en', $request->getLocale());\n }", " public function testSetBadLocale()\n {\n $config = new App();\n $config->supportedLocales = ['en', 'es'];\n $config->defaultLocale = 'es';\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), null, new UserAgent());", " $request->setLocale('xx');\n $this->assertSame('es', $request->getLocale());\n }", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/2774\n */\n public function testNegotiatesLocale()\n {\n $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'fr-FR; q=1.0, en; q=0.5';", " $config = new App();\n $config->negotiateLocale = true;\n $config->supportedLocales = ['fr', 'en'];\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), null, new UserAgent());", " $this->assertSame($config->defaultLocale, $request->getDefaultLocale());\n $this->assertSame('fr', $request->getLocale());\n }", " public function testNegotiatesLocaleOnlyBroad()\n {\n $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'fr; q=1.0, en; q=0.5';", " $config = new App();\n $config->negotiateLocale = true;\n $config->supportedLocales = ['fr', 'en'];\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), null, new UserAgent());", " $this->assertSame($config->defaultLocale, $request->getDefaultLocale());\n $this->assertSame('fr', $request->getLocale());\n }", " // The negotiation tests below are not intended to exercise the HTTP\\Negotiate class -\n // that is up to the NegotiateTest. These are only to make sure that the requests\n // flow through to the negotiator", " public function testNegotiatesNot()\n {\n $this->request->setHeader('Accept-Charset', 'iso-8859-5, unicode-1-1;q=0.8');", " $this->expectException(HTTPException::class);\n $this->request->negotiate('something bogus', ['iso-8859-5', 'unicode-1-1']);\n }", " public function testNegotiatesCharset()\n {\n // $_SERVER['HTTP_ACCEPT_CHARSET'] = 'iso-8859-5, unicode-1-1;q=0.8';\n $this->request->setHeader('Accept-Charset', 'iso-8859-5, unicode-1-1;q=0.8');", " $this->assertSame(strtolower($this->request->config->charset), $this->request->negotiate('charset', ['iso-8859', 'unicode-1-2']));\n }", " public function testNegotiatesMedia()\n {\n $this->request->setHeader('Accept', 'text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c');\n $this->assertSame('text/html', $this->request->negotiate('media', ['text/html', 'text/x-c', 'text/x-dvi', 'text/plain']));\n }", " public function testNegotiatesEncoding()\n {\n $this->request->setHeader('Accept-Encoding', 'gzip;q=1.0, identity; q=0.4, compress;q=0.5');\n $this->assertSame('gzip', $this->request->negotiate('encoding', ['gzip', 'compress']));\n }", " public function testNegotiatesLanguage()\n {\n $this->request->setHeader('Accept-Language', 'da, en-gb;q=0.8, en;q=0.7');\n $this->assertSame('en', $this->request->negotiate('language', ['en', 'da']));\n }", " public function testCanGrabGetRawJSON()\n {\n $json = '{\"code\":1, \"message\":\"ok\"}';", " $expected = ['code' => 1, 'message' => 'ok'];", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $this->assertSame($expected, $request->getJSON(true));\n }", " public function testCanGetAVariableFromJson()\n {\n $jsonObj = [\n 'foo' => 'bar',\n 'baz' => ['fizz' => 'buzz'],\n ];\n $json = json_encode($jsonObj);", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $this->assertSame('bar', $request->getJsonVar('foo'));\n $this->assertNull($request->getJsonVar('notExists'));", " $jsonVar = $request->getJsonVar('baz');\n $this->assertIsObject($jsonVar);\n $this->assertSame('buzz', $jsonVar->fizz);\n $this->assertSame('buzz', $request->getJsonVar('baz.fizz'));\n }", " public function testGetJsonVarAsArray()\n {\n $jsonObj = [\n 'baz' => [\n 'fizz' => 'buzz',\n 'foo' => 'bar',\n ],\n ];\n $json = json_encode($jsonObj);", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $jsonVar = $request->getJsonVar('baz', true);\n $this->assertIsArray($jsonVar);\n $this->assertSame('buzz', $jsonVar['fizz']);\n $this->assertSame('bar', $jsonVar['foo']);\n }", " public function testGetJsonVarCanFilter()\n {\n $json = json_encode(['foo' => 'bar']);", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $this->assertFalse($request->getJsonVar('foo', false, FILTER_VALIDATE_INT));\n }", " public function testGetVarWorksWithJson()\n {\n $json = json_encode(['foo' => 'bar', 'fizz' => 'buzz']);", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $json, new UserAgent());\n $request->setHeader('Content-Type', 'application/json');", " $this->assertSame('bar', $request->getVar('foo'));\n $this->assertSame('buzz', $request->getVar('fizz'));\n $this->assertNull($request->getVar('notExists'));", " $multiple = $request->getVar(['foo', 'fizz']);\n $this->assertIsArray($multiple);\n $this->assertSame('bar', $multiple['foo']);\n $this->assertSame('buzz', $multiple['fizz']);", " $all = $request->getVar();\n $this->assertIsObject($all);\n $this->assertSame('bar', $all->foo);\n $this->assertSame('buzz', $all->fizz);\n }", " public function testGetVarWorksWithJsonAndGetParams()\n {\n $config = new App();\n $config->baseURL = 'http://example.com/';", " // GET method\n $_REQUEST['foo'] = 'bar';\n $_REQUEST['fizz'] = 'buzz';", " $request = new IncomingRequest($config, new URI('http://example.com/path?foo=bar&fizz=buzz'), 'php://input', new UserAgent());\n $request = $request->withMethod('GET');", " // JSON type\n $request->setHeader('Content-Type', 'application/json');", " $this->assertSame('bar', $request->getVar('foo'));\n $this->assertSame('buzz', $request->getVar('fizz'));", " $multiple = $request->getVar(['foo', 'fizz']);\n $this->assertIsArray($multiple);\n $this->assertSame('bar', $multiple['foo']);\n $this->assertSame('buzz', $multiple['fizz']);", " $all = $request->getVar();\n $this->assertIsArray($all);\n $this->assertSame('bar', $all['foo']);\n $this->assertSame('buzz', $all['fizz']);\n }", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/5391\n */\n public function testGetJsonVarReturnsNullFromNullBody()\n {\n $config = new App();\n $config->baseURL = 'http://example.com/';\n $json = null;\n $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $this->assertNull($request->getJsonVar('myKey'));\n }", " public function testgetJSONReturnsNullFromNullBody()\n {\n $config = new App();\n $config->baseURL = 'http://example.com/';\n $json = null;\n $request = new IncomingRequest($config, new URI(), $json, new UserAgent());", " $this->assertNull($request->getJSON());\n }", " public function testCanGrabGetRawInput()\n {\n $rawstring = 'username=admin001&role=administrator&usepass=0';", " $expected = [\n 'username' => 'admin001',\n 'role' => 'administrator',\n 'usepass' => '0',\n ];", " $config = new App();\n $config->baseURL = 'http://example.com/';", " $request = new IncomingRequest($config, new URI(), $rawstring, new UserAgent());", " $this->assertSame($expected, $request->getRawInput());\n }", " public function testIsCLI()\n {\n // this should be the case in unit testing\n $this->assertTrue($this->request->isCLI());\n }", " public function testIsAJAX()\n {\n $this->request->appendHeader('X-Requested-With', 'XMLHttpRequest');\n $this->assertTrue($this->request->isAJAX());\n }", " public function testIsSecure()\n {\n $_SERVER['HTTPS'] = 'on';\n $this->assertTrue($this->request->isSecure());\n }", " public function testIsSecureFrontEnd()\n {\n $this->request->appendHeader('Front-End-Https', 'on');\n $this->assertTrue($this->request->isSecure());\n }", " public function testIsSecureForwarded()\n {\n $this->request->appendHeader('X-Forwarded-Proto', 'https');\n $this->assertTrue($this->request->isSecure());\n }", " public function testUserAgent()\n {\n $_SERVER['HTTP_USER_AGENT'] = 'Mozilla';", " $config = new App();\n $request = new IncomingRequest($config, new URI(), null, new UserAgent());", " $this->assertSame('Mozilla', $request->getUserAgent()->__toString());\n }", " public function testFileCollectionFactory()\n {\n $_FILES = [\n 'userfile' => [\n 'name' => 'someFile.txt',\n 'type' => 'text/plain',\n 'size' => '124',\n 'tmp_name' => '/tmp/myTempFile.txt',\n 'error' => 0,\n ],\n ];", " $files = $this->request->getFiles();\n $this->assertCount(1, $files);", " $file = array_shift($files);\n $this->assertInstanceOf(UploadedFile::class, $file);", " $this->assertSame('someFile.txt', $file->getName());\n $this->assertSame(124, $file->getSize());\n }", " public function testGetFileMultiple()\n {\n $_FILES = [\n 'userfile' => [\n 'name' => [\n 'someFile.txt',\n 'someFile2.txt',\n ],\n 'type' => [\n 'text/plain',\n 'text/plain',\n ],\n 'size' => [\n '124',\n '125',\n ],\n 'tmp_name' => [\n '/tmp/myTempFile.txt',\n '/tmp/myTempFile2.txt',\n ],\n 'error' => [\n 0,\n 0,\n ],\n ],\n ];", " $gotit = $this->request->getFileMultiple('userfile');\n $this->assertSame(124, $gotit[0]->getSize());\n $this->assertSame(125, $gotit[1]->getSize());\n }", " public function testGetFile()\n {\n $_FILES = [\n 'userfile' => [\n 'name' => 'someFile.txt',\n 'type' => 'text/plain',\n 'size' => '124',\n 'tmp_name' => '/tmp/myTempFile.txt',\n 'error' => 0,\n ],\n ];", " $gotit = $this->request->getFile('userfile');\n $this->assertSame(124, $gotit->getSize());\n }", " public function testSpoofing()\n {\n $this->request->setMethod('WINK');\n $this->assertSame('wink', $this->request->getMethod());\n }", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/2839\n */\n public function testGetPostEmpty()\n {\n $_POST['TEST'] = '5';\n $_GET['TEST'] = '3';\n $this->assertSame($_POST, $this->request->getPostGet());\n $this->assertSame($_GET, $this->request->getGetPost());\n }", " public function testWithFalseBody()\n {\n // Use `false` here to simulate file_get_contents returning a false value\n $request = new IncomingRequest(new App(), new URI(), false, new UserAgent());", " $this->assertNotFalse($request->getBody());\n $this->assertNull($request->getBody());\n }", " /**\n * @see https://github.com/codeigniter4/CodeIgniter4/issues/3020\n */\n public function testGetPostIndexNotExists()\n {\n $_POST['TEST'] = 5;\n $_GET['TEST'] = 3;\n $this->assertNull($this->request->getPostGet('gc'));\n $this->assertNull($this->request->getGetPost('gc'));\n }", " public function providePathChecks()\n {\n return [\n 'not /index.php' => [\n '/test.php',\n '/',\n ],\n '/index.php' => [\n '/index.php',\n '/',\n ],\n ];\n }", " /**\n * @dataProvider providePathChecks\n *\n * @param mixed $path\n * @param mixed $detectPath\n */\n public function testExtensionPHP($path, $detectPath)\n {\n $config = new App();\n $config->baseURL = 'http://example.com/';", " $_SERVER['REQUEST_URI'] = $path;\n $_SERVER['SCRIPT_NAME'] = $path;\n $request = new IncomingRequest($config, new URI($path), null, new UserAgent());\n $this->assertSame($detectPath, $request->detectPath());\n }", " public function testGetPath()\n {\n $_SERVER['REQUEST_URI'] = '/index.php/fruits/banana';\n $_SERVER['SCRIPT_NAME'] = '/index.php';", " $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $this->assertSame('fruits/banana', $request->getPath());\n }", " public function testGetPathIsRelative()\n {\n $_SERVER['REQUEST_URI'] = '/sub/folder/index.php/fruits/banana';\n $_SERVER['SCRIPT_NAME'] = '/sub/folder/index.php';", " $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $this->assertSame('fruits/banana', $request->getPath());\n }", " public function testGetPathStoresDetectedValue()\n {\n $_SERVER['REQUEST_URI'] = '/fruits/banana';\n $_SERVER['SCRIPT_NAME'] = '/index.php';", " $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $_SERVER['REQUEST_URI'] = '/candy/snickers';", " $this->assertSame('fruits/banana', $request->getPath());\n }", " public function testGetPathIsRediscovered()\n {\n $_SERVER['REQUEST_URI'] = '/fruits/banana';\n $_SERVER['SCRIPT_NAME'] = '/index.php';", " $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $_SERVER['REQUEST_URI'] = '/candy/snickers';\n $request->detectPath();", " $this->assertSame('candy/snickers', $request->getPath());\n }", " public function testSetPath()\n {\n $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());\n $this->assertSame('', $request->getPath());", " $request->setPath('foobar');\n $this->assertSame('foobar', $request->getPath());\n }", " public function testSetPathUpdatesURI()\n {\n $request = new IncomingRequest(new App(), new URI(), null, new UserAgent());", " $request->setPath('apples');", " $this->assertSame('apples', $request->getUri()->getPath());\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 ]
PreciseBugs
{"buggy_code_end_loc": [22, 818, 313, 129, 10], "buggy_code_start_loc": [22, 813, 304, 110, 10], "filenames": ["SECURITY.md", "system/Common.php", "tests/system/CommonFunctionsTest.php", "tests/system/HTTP/IncomingRequestTest.php", "user_guide_src/source/changelogs/v4.1.6.rst"], "fixing_code_end_loc": [24, 812, 346, 131, 16], "fixing_code_start_loc": [23, 812, 304, 110, 11], "message": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codeigniter:codeigniter:*:*:*:*:*:*:*:*", "matchCriteriaId": "5E18B755-8CBA-45C9-8759-5039BBAD4FC6", "versionEndExcluding": "4.1.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`."}, {"lang": "es", "value": "CodeIgniter es un framework web full-stack de PHP de c\u00f3digo abierto. Se encontr\u00f3 una deserializaci\u00f3n de datos no confiables en la funci\u00f3n \"old()\" en CodeIgniter4. Los atacantes remotos pueden inyectar objetos arbitrarios autocargables con esta vulnerabilidad, y posiblemente ejecutar c\u00f3digo PHP existente en el servidor. Tenemos conocimiento de una explotaci\u00f3n que funciona, que puede conllevar a una inyecci\u00f3n SQL. Se aconseja a usuarios que actualicen a la versi\u00f3n 4.1.6 o posterior. A los usuarios que no puedan actualizarse se les aconseja no usar la funci\u00f3n \"old()\" y form_helper ni \"RedirectResponse::withInput()\" y \"redirect()-&gt;withInput()\""}], "evaluatorComment": null, "id": "CVE-2022-21647", "lastModified": "2022-01-20T15:04:23.823", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.7, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-01-04T20:15:07.930", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-w6jr-wj64-mc9x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-502"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, "type": "CWE-502"}
240
Determine whether the {function_name} code is vulnerable or not.
[ "Version 4.1.6\n#############", "Release Date: Not released", "**4.1.6 release of CodeIgniter4**", ".. contents::\n :local:\n :depth: 2", "", "\nBREAKING\n********", "- Multiple table names will no longer be stored in ``BaseBuilder::$tableName`` - an empty string will be used instead.", ".. _changelog-v416-validation-changes:", "Validation changes\n==================", "- The previous version of the Validation can't handle an array item.\n Because of the bug fix, the validation results may be different,\n or raise a ``TypeError``.\n But the previous version's results are probably incorrect.\n- The Validation separated the validation process of multiple field\n like ``contacts.*.name`` and single field.\n When a single field has an array data, the previous version validates each element of the array.\n The validation rule gets an element of the array as the parameter.\n On the other hand, the current version passes the array to the validation rule as a whole.", "Enhancements\n************", "- Database pane on debug toolbar now displays location where Query was called from. Also displays full backtrace.\n- :ref:`Subqueries <query-builder-where-subquery>` in QueryBuilder can now be an instance of the BaseBuilder class.", "Changes\n*******", "- The process of sending cookies has been moved to the ``Response`` class. Now the ``Security`` and ``CookieStore`` class don't send cookies, set them to the Response.", "Deprecations\n************", "- ``Seeder::faker()`` and ``Seeder::$faker`` are deprecated.\n- ``BaseBuilder::cleanClone()`` is deprecated.", "Sending Cookies\n===============", "The process of sending cookies has been moved to the ``Response`` class.\nAnd the following methods are deprecated:", "- ``CookieStore::dispatch()``\n- ``CookieStore::setRawCookie()``\n- ``CookieStore::setCookie()``\n- ``Security::sendCookie()``\n- ``Security::doSendCookie()``", "Bugs Fixed\n**********" ]
[ 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": [22, 818, 313, 129, 10], "buggy_code_start_loc": [22, 813, 304, 110, 10], "filenames": ["SECURITY.md", "system/Common.php", "tests/system/CommonFunctionsTest.php", "tests/system/HTTP/IncomingRequestTest.php", "user_guide_src/source/changelogs/v4.1.6.rst"], "fixing_code_end_loc": [24, 812, 346, 131, 16], "fixing_code_start_loc": [23, 812, 304, 110, 11], "message": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codeigniter:codeigniter:*:*:*:*:*:*:*:*", "matchCriteriaId": "5E18B755-8CBA-45C9-8759-5039BBAD4FC6", "versionEndExcluding": "4.1.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`."}, {"lang": "es", "value": "CodeIgniter es un framework web full-stack de PHP de c\u00f3digo abierto. Se encontr\u00f3 una deserializaci\u00f3n de datos no confiables en la funci\u00f3n \"old()\" en CodeIgniter4. Los atacantes remotos pueden inyectar objetos arbitrarios autocargables con esta vulnerabilidad, y posiblemente ejecutar c\u00f3digo PHP existente en el servidor. Tenemos conocimiento de una explotaci\u00f3n que funciona, que puede conllevar a una inyecci\u00f3n SQL. Se aconseja a usuarios que actualicen a la versi\u00f3n 4.1.6 o posterior. A los usuarios que no puedan actualizarse se les aconseja no usar la funci\u00f3n \"old()\" y form_helper ni \"RedirectResponse::withInput()\" y \"redirect()-&gt;withInput()\""}], "evaluatorComment": null, "id": "CVE-2022-21647", "lastModified": "2022-01-20T15:04:23.823", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.7, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-01-04T20:15:07.930", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-w6jr-wj64-mc9x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-502"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, "type": "CWE-502"}
240
Determine whether the {function_name} code is vulnerable or not.
[ "Version 4.1.6\n#############", "Release Date: Not released", "**4.1.6 release of CodeIgniter4**", ".. contents::\n :local:\n :depth: 2", "\nSECURITY\n********", "- *Deserialization of Untrusted Data* found in the ``old()`` function was fixed. See the `Security advisory <https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-w6jr-wj64-mc9x>`_ for more information.", "\nBREAKING\n********", "- Multiple table names will no longer be stored in ``BaseBuilder::$tableName`` - an empty string will be used instead.", ".. _changelog-v416-validation-changes:", "Validation changes\n==================", "- The previous version of the Validation can't handle an array item.\n Because of the bug fix, the validation results may be different,\n or raise a ``TypeError``.\n But the previous version's results are probably incorrect.\n- The Validation separated the validation process of multiple field\n like ``contacts.*.name`` and single field.\n When a single field has an array data, the previous version validates each element of the array.\n The validation rule gets an element of the array as the parameter.\n On the other hand, the current version passes the array to the validation rule as a whole.", "Enhancements\n************", "- Database pane on debug toolbar now displays location where Query was called from. Also displays full backtrace.\n- :ref:`Subqueries <query-builder-where-subquery>` in QueryBuilder can now be an instance of the BaseBuilder class.", "Changes\n*******", "- The process of sending cookies has been moved to the ``Response`` class. Now the ``Security`` and ``CookieStore`` class don't send cookies, set them to the Response.", "Deprecations\n************", "- ``Seeder::faker()`` and ``Seeder::$faker`` are deprecated.\n- ``BaseBuilder::cleanClone()`` is deprecated.", "Sending Cookies\n===============", "The process of sending cookies has been moved to the ``Response`` class.\nAnd the following methods are deprecated:", "- ``CookieStore::dispatch()``\n- ``CookieStore::setRawCookie()``\n- ``CookieStore::setCookie()``\n- ``Security::sendCookie()``\n- ``Security::doSendCookie()``", "Bugs Fixed\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": [22, 818, 313, 129, 10], "buggy_code_start_loc": [22, 813, 304, 110, 10], "filenames": ["SECURITY.md", "system/Common.php", "tests/system/CommonFunctionsTest.php", "tests/system/HTTP/IncomingRequestTest.php", "user_guide_src/source/changelogs/v4.1.6.rst"], "fixing_code_end_loc": [24, 812, 346, 131, 16], "fixing_code_start_loc": [23, 812, 304, 110, 11], "message": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codeigniter:codeigniter:*:*:*:*:*:*:*:*", "matchCriteriaId": "5E18B755-8CBA-45C9-8759-5039BBAD4FC6", "versionEndExcluding": "4.1.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "CodeIgniter is an open source PHP full-stack web framework. Deserialization of Untrusted Data was found in the `old()` function in CodeIgniter4. Remote attackers may inject auto-loadable arbitrary objects with this vulnerability, and possibly execute existing PHP code on the server. We are aware of a working exploit, which can lead to SQL injection. Users are advised to upgrade to v4.1.6 or later. Users unable to upgrade as advised to not use the `old()` function and form_helper nor `RedirectResponse::withInput()` and `redirect()->withInput()`."}, {"lang": "es", "value": "CodeIgniter es un framework web full-stack de PHP de c\u00f3digo abierto. Se encontr\u00f3 una deserializaci\u00f3n de datos no confiables en la funci\u00f3n \"old()\" en CodeIgniter4. Los atacantes remotos pueden inyectar objetos arbitrarios autocargables con esta vulnerabilidad, y posiblemente ejecutar c\u00f3digo PHP existente en el servidor. Tenemos conocimiento de una explotaci\u00f3n que funciona, que puede conllevar a una inyecci\u00f3n SQL. Se aconseja a usuarios que actualicen a la versi\u00f3n 4.1.6 o posterior. A los usuarios que no puedan actualizarse se les aconseja no usar la funci\u00f3n \"old()\" y form_helper ni \"RedirectResponse::withInput()\" y \"redirect()-&gt;withInput()\""}], "evaluatorComment": null, "id": "CVE-2022-21647", "lastModified": "2022-01-20T15:04:23.823", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.7, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-01-04T20:15:07.930", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-w6jr-wj64-mc9x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-502"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/codeigniter4/CodeIgniter4/commit/ce95ed5765256e2f09f3513e7d42790e0d6948f5"}, "type": "CWE-502"}
240
Determine whether the {function_name} code is vulnerable or not.
[ "# -*- coding: utf-8 -*-\n# ____________\n# ___/ | \\_____________ _ _ ___\n# / ___/ | _ __ _ _| | ___ __ _ __| | \\\n# / \\___/ ______/ | '_ \\ || | |__/ _ \\/ _` / _` | \\\n# \\ ◯ | | .__/\\_, |____\\___/\\__,_\\__,_| /\n# \\_______\\ /_______|_| |__/________________________/\n# \\ /\n# \\/", "import os", "import flask\nimport jinja2\nfrom werkzeug.serving import WSGIRequestHandler", "from .blueprints import BLUEPRINTS\nfrom .config import get_default_config\nfrom .extensions import EXTENSIONS, THEMES\nfrom .filters import TEMPLATE_FILTERS\nfrom .globals import TEMPLATE_GLOBALS\nfrom .handlers import ERROR_HANDLERS\nfrom .helpers import JSONEncoder\nfrom .processors import CONTEXT_PROCESSORS", "\n#: flask app singleton?\nclass App:", " JINJA_TEMPLATE_GLOBALS = TEMPLATE_GLOBALS\n JINJA_TEMPLATE_FILTERS = TEMPLATE_FILTERS\n JINJA_CONTEXT_PROCESSORS = CONTEXT_PROCESSORS\n FLASK_ERROR_HANDLERS = ERROR_HANDLERS\n FLASK_BLUEPRINTS = BLUEPRINTS\n FLASK_EXTENSIONS = EXTENSIONS\n FLASK_THEMES = THEMES", "\n @classmethod\n def _configure_config(cls, app, develop):\n conf_obj = get_default_config(develop)\n app.config.from_object(conf_obj)", " @classmethod\n def _configure_blueprints(cls, app, path_prefix):\n for blueprint in cls.FLASK_BLUEPRINTS:\n url_prefix = path_prefix if not blueprint.url_prefix else None\n app.register_blueprint(blueprint, url_prefix=url_prefix)", " @classmethod\n def _configure_extensions(cls, app):\n for extension in cls.FLASK_EXTENSIONS:\n extension.init_app(app)", " @classmethod\n def _configure_themes(cls, app, path_prefix=\"\"):\n for theme in cls.FLASK_THEMES:\n theme.init_app(app, path_prefix)", " @classmethod\n def _configure_handlers(cls, app):\n \"\"\"\n Register error handlers.\n \"\"\"\n for exc, fn in cls.FLASK_ERROR_HANDLERS:\n app.register_error_handler(exc, fn)", " @classmethod\n def _configure_json_encoding(cls, app):\n app.json_encoder = JSONEncoder", " @classmethod\n def _configure_templating(cls, app):\n tempdir = app.config[\"PYLOAD_API\"].get_cachedir()\n cache_path = os.path.join(tempdir, \"jinja\")", " os.makedirs(cache_path, exist_ok=True)", " app.create_jinja_environment()\n", " # NOTE: enable autoescape for all file extensions (included .js)", " # maybe this will break .txt rendering, but we don't render this kind of files actually\n # that does not change 'default_for_string=False' (by default)\n app.jinja_env.autoescape = jinja2.select_autoescape(default=True)\n app.jinja_env.bytecode_cache = jinja2.FileSystemBytecodeCache(cache_path)", " for fn in cls.JINJA_TEMPLATE_FILTERS:\n app.add_template_filter(fn)", " for fn in cls.JINJA_TEMPLATE_GLOBALS:\n app.add_template_global(fn)", " for fn in cls.JINJA_CONTEXT_PROCESSORS:\n app.context_processor(fn)", " @classmethod\n def _configure_session(cls, app):\n tempdir = app.config[\"PYLOAD_API\"].get_cachedir()\n cache_path = os.path.join(tempdir, \"flask\")\n os.makedirs(cache_path, exist_ok=True)", " app.config[\"SESSION_FILE_DIR\"] = cache_path\n app.config[\"SESSION_TYPE\"] = \"filesystem\"\n app.config[\"SESSION_COOKIE_NAME\"] = \"pyload_session\"", "", " app.config[\"SESSION_PERMANENT\"] = False", " session_lifetime = max(app.config[\"PYLOAD_API\"].get_config_value(\"webui\", \"session_lifetime\"), 1) * 60\n app.config[\"PERMANENT_SESSION_LIFETIME\"] = session_lifetime", " @classmethod\n def _configure_api(cls, app, pycore):\n app.config[\"PYLOAD_API\"] = pycore.api", " @classmethod\n def _configure_logging(cls, app, pycore):\n # Inject our custom logger\n app.logger = pycore.log.getChild(\"webui\")", " def __new__(cls, pycore, develop=False, path_prefix=None):\n app = flask.Flask(__name__)", " cls._configure_logging(app, pycore)\n cls._configure_api(app, pycore)\n cls._configure_config(app, develop)\n cls._configure_templating(app)\n cls._configure_json_encoding(app)\n cls._configure_session(app)\n cls._configure_blueprints(app, path_prefix)\n cls._configure_extensions(app)\n cls._configure_themes(app, path_prefix or \"\")\n cls._configure_handlers(app)", " WSGIRequestHandler.protocol_version = \"HTTP/1.1\"", " return app" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [104], "buggy_code_start_loc": [81], "filenames": ["src/pyload/webui/app/__init__.py"], "fixing_code_end_loc": [106], "fixing_code_start_loc": [81], "message": "Sensitive Cookie in HTTPS Session Without 'Secure' Attribute in GitHub repository pyload/pyload prior to 0.5.0b3.dev32.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pyload:pyload:0.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "E5A06D79-6D64-41FB-9040-17E9630DF4E9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Sensitive Cookie in HTTPS Session Without 'Secure' Attribute in GitHub repository pyload/pyload prior to 0.5.0b3.dev32."}], "evaluatorComment": null, "id": "CVE-2023-0055", "lastModified": "2023-01-11T16:01:57.503", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.1, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 1.6, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "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": "2023-01-04T22:15:09.180", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/pyload/pyload/commit/7b53b8d43c2c072b457dcd19c8a09bcfc3721703"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/ed88e240-99ff-48a1-bf32-8e1ef5f13cce"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-319"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-614"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/pyload/pyload/commit/7b53b8d43c2c072b457dcd19c8a09bcfc3721703"}, "type": "CWE-319"}
241
Determine whether the {function_name} code is vulnerable or not.
[ "# -*- coding: utf-8 -*-\n# ____________\n# ___/ | \\_____________ _ _ ___\n# / ___/ | _ __ _ _| | ___ __ _ __| | \\\n# / \\___/ ______/ | '_ \\ || | |__/ _ \\/ _` / _` | \\\n# \\ ◯ | | .__/\\_, |____\\___/\\__,_\\__,_| /\n# \\_______\\ /_______|_| |__/________________________/\n# \\ /\n# \\/", "import os", "import flask\nimport jinja2\nfrom werkzeug.serving import WSGIRequestHandler", "from .blueprints import BLUEPRINTS\nfrom .config import get_default_config\nfrom .extensions import EXTENSIONS, THEMES\nfrom .filters import TEMPLATE_FILTERS\nfrom .globals import TEMPLATE_GLOBALS\nfrom .handlers import ERROR_HANDLERS\nfrom .helpers import JSONEncoder\nfrom .processors import CONTEXT_PROCESSORS", "\n#: flask app singleton?\nclass App:", " JINJA_TEMPLATE_GLOBALS = TEMPLATE_GLOBALS\n JINJA_TEMPLATE_FILTERS = TEMPLATE_FILTERS\n JINJA_CONTEXT_PROCESSORS = CONTEXT_PROCESSORS\n FLASK_ERROR_HANDLERS = ERROR_HANDLERS\n FLASK_BLUEPRINTS = BLUEPRINTS\n FLASK_EXTENSIONS = EXTENSIONS\n FLASK_THEMES = THEMES", "\n @classmethod\n def _configure_config(cls, app, develop):\n conf_obj = get_default_config(develop)\n app.config.from_object(conf_obj)", " @classmethod\n def _configure_blueprints(cls, app, path_prefix):\n for blueprint in cls.FLASK_BLUEPRINTS:\n url_prefix = path_prefix if not blueprint.url_prefix else None\n app.register_blueprint(blueprint, url_prefix=url_prefix)", " @classmethod\n def _configure_extensions(cls, app):\n for extension in cls.FLASK_EXTENSIONS:\n extension.init_app(app)", " @classmethod\n def _configure_themes(cls, app, path_prefix=\"\"):\n for theme in cls.FLASK_THEMES:\n theme.init_app(app, path_prefix)", " @classmethod\n def _configure_handlers(cls, app):\n \"\"\"\n Register error handlers.\n \"\"\"\n for exc, fn in cls.FLASK_ERROR_HANDLERS:\n app.register_error_handler(exc, fn)", " @classmethod\n def _configure_json_encoding(cls, app):\n app.json_encoder = JSONEncoder", " @classmethod\n def _configure_templating(cls, app):\n tempdir = app.config[\"PYLOAD_API\"].get_cachedir()\n cache_path = os.path.join(tempdir, \"jinja\")", " os.makedirs(cache_path, exist_ok=True)", " app.create_jinja_environment()\n", " # NOTE: enable auto escape for all file extensions (including .js)", " # maybe this will break .txt rendering, but we don't render this kind of files actually\n # that does not change 'default_for_string=False' (by default)\n app.jinja_env.autoescape = jinja2.select_autoescape(default=True)\n app.jinja_env.bytecode_cache = jinja2.FileSystemBytecodeCache(cache_path)", " for fn in cls.JINJA_TEMPLATE_FILTERS:\n app.add_template_filter(fn)", " for fn in cls.JINJA_TEMPLATE_GLOBALS:\n app.add_template_global(fn)", " for fn in cls.JINJA_CONTEXT_PROCESSORS:\n app.context_processor(fn)", " @classmethod\n def _configure_session(cls, app):\n tempdir = app.config[\"PYLOAD_API\"].get_cachedir()\n cache_path = os.path.join(tempdir, \"flask\")\n os.makedirs(cache_path, exist_ok=True)", " app.config[\"SESSION_FILE_DIR\"] = cache_path\n app.config[\"SESSION_TYPE\"] = \"filesystem\"\n app.config[\"SESSION_COOKIE_NAME\"] = \"pyload_session\"", " app.config[\"SESSION_COOKIE_SECURE\"] = app.config[\"PYLOAD_API\"].get_config_value(\"webui\", \"use_ssl\")", " app.config[\"SESSION_PERMANENT\"] = False", " session_lifetime = max(app.config[\"PYLOAD_API\"].get_config_value(\"webui\", \"session_lifetime\"), 1) * 60\n app.config[\"PERMANENT_SESSION_LIFETIME\"] = session_lifetime", " @classmethod\n def _configure_api(cls, app, pycore):\n app.config[\"PYLOAD_API\"] = pycore.api", " @classmethod\n def _configure_logging(cls, app, pycore):\n # Inject our custom logger\n app.logger = pycore.log.getChild(\"webui\")", " def __new__(cls, pycore, develop=False, path_prefix=None):\n app = flask.Flask(__name__)", " cls._configure_logging(app, pycore)\n cls._configure_api(app, pycore)\n cls._configure_config(app, develop)\n cls._configure_templating(app)\n cls._configure_json_encoding(app)\n cls._configure_session(app)\n cls._configure_blueprints(app, path_prefix)\n cls._configure_extensions(app)\n cls._configure_themes(app, path_prefix or \"\")\n cls._configure_handlers(app)", " WSGIRequestHandler.protocol_version = \"HTTP/1.1\"", " return app" ]
[ 1, 1, 1, 1, 1, 1, 1, 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": [104], "buggy_code_start_loc": [81], "filenames": ["src/pyload/webui/app/__init__.py"], "fixing_code_end_loc": [106], "fixing_code_start_loc": [81], "message": "Sensitive Cookie in HTTPS Session Without 'Secure' Attribute in GitHub repository pyload/pyload prior to 0.5.0b3.dev32.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pyload:pyload:0.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "E5A06D79-6D64-41FB-9040-17E9630DF4E9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Sensitive Cookie in HTTPS Session Without 'Secure' Attribute in GitHub repository pyload/pyload prior to 0.5.0b3.dev32."}], "evaluatorComment": null, "id": "CVE-2023-0055", "lastModified": "2023-01-11T16:01:57.503", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.1, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 1.6, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "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": "2023-01-04T22:15:09.180", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/pyload/pyload/commit/7b53b8d43c2c072b457dcd19c8a09bcfc3721703"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/ed88e240-99ff-48a1-bf32-8e1ef5f13cce"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-319"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-614"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/pyload/pyload/commit/7b53b8d43c2c072b457dcd19c8a09bcfc3721703"}, "type": "CWE-319"}
241
Determine whether the {function_name} code is vulnerable or not.
[ "import { useEffect, useState, useRef } from \"react\";\nimport { useTranslation } from \"react-i18next\";\nimport { useLocationStore, useDialogStore } from \"../store/module\";\nimport { memoSpecialTypes } from \"../helpers/filter\";\nimport Icon from \"./Icon\";\nimport \"../less/search-bar.less\";", "const SearchBar = () => {\n const { t } = useTranslation();\n const locationStore = useLocationStore();\n const dialogStore = useDialogStore();\n const memoType = locationStore.state.query.type;\n const [queryText, setQueryText] = useState(\"\");\n const inputRef = useRef<HTMLInputElement>(null);\n const [isFocus, setIsFocus] = useState(false);", " useEffect(() => {\n const handleKeyDown = (event: KeyboardEvent) => {\n if (!inputRef.current) {\n return;\n }\n if (dialogStore.getState().dialogStack.length) {\n return;\n }\n const isMetaKey = event.ctrlKey || event.metaKey;\n if (isMetaKey && event.key === \"f\") {\n event.preventDefault();\n inputRef.current.focus();\n return;\n }\n };\n document.body.addEventListener(\"keydown\", handleKeyDown);\n return () => {\n document.body.removeEventListener(\"keydown\", handleKeyDown);\n };\n }, []);", " useEffect(() => {\n const text = locationStore.getState().query.text;\n setQueryText(text === undefined ? \"\" : text);", " }, [locationStore.getState().query.text]);", "\n const handleMemoTypeItemClick = (type: MemoSpecType | undefined) => {\n const { type: prevType } = locationStore.getState().query ?? {};\n if (type === prevType) {\n type = undefined;\n }\n locationStore.setMemoTypeQuery(type);\n };", " const handleTextQueryInput = (event: React.FormEvent<HTMLInputElement>) => {\n const text = event.currentTarget.value;\n setQueryText(text);\n locationStore.setTextQuery(text.length === 0 ? undefined : text);\n };", " const handleFocus = () => {\n setIsFocus(true);\n };", " const handleBlur = () => {\n setIsFocus(false);\n };", " return (\n <div className={`search-bar-container ${isFocus ? \"is-focus\" : \"\"}`}>\n <div className=\"search-bar-inputer\">\n <Icon.Search className=\"icon-img\" />\n <input\n className=\"text-input\"\n autoComplete=\"new-password\"\n type=\"text\"\n placeholder=\"\"\n ref={inputRef}\n value={queryText}\n onChange={handleTextQueryInput}\n onFocus={handleFocus}\n onBlur={handleBlur}\n />\n </div>\n <div className=\"quickly-action-wrapper\">\n <div className=\"quickly-action-container\">\n <p className=\"title-text\">{t(\"search.quickly-filter\").toUpperCase()}</p>\n <div className=\"section-container types-container\">\n <span className=\"section-text\">{t(\"common.type\").toUpperCase()}:</span>\n <div className=\"values-container\">\n {memoSpecialTypes.map((type, idx) => {\n return (\n <div key={type.value}>\n <span\n className={`type-item ${memoType === type.value ? \"selected\" : \"\"}`}\n onClick={() => {\n handleMemoTypeItemClick(type.value as MemoSpecType);\n }}\n >\n {t(type.text)}\n </span>\n {idx + 1 < memoSpecialTypes.length ? <span className=\"split-text\">/</span> : null}\n </div>\n );\n })}\n </div>\n </div>\n </div>\n </div>\n </div>\n );\n};", "export default SearchBar;" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "import { useEffect, useState, useRef } from \"react\";\nimport { useTranslation } from \"react-i18next\";\nimport { useLocationStore, useDialogStore } from \"../store/module\";\nimport { memoSpecialTypes } from \"../helpers/filter\";\nimport Icon from \"./Icon\";\nimport \"../less/search-bar.less\";", "const SearchBar = () => {\n const { t } = useTranslation();\n const locationStore = useLocationStore();\n const dialogStore = useDialogStore();\n const memoType = locationStore.state.query.type;\n const [queryText, setQueryText] = useState(\"\");\n const inputRef = useRef<HTMLInputElement>(null);\n const [isFocus, setIsFocus] = useState(false);", " useEffect(() => {\n const handleKeyDown = (event: KeyboardEvent) => {\n if (!inputRef.current) {\n return;\n }\n if (dialogStore.getState().dialogStack.length) {\n return;\n }\n const isMetaKey = event.ctrlKey || event.metaKey;\n if (isMetaKey && event.key === \"f\") {\n event.preventDefault();\n inputRef.current.focus();\n return;\n }\n };\n document.body.addEventListener(\"keydown\", handleKeyDown);\n return () => {\n document.body.removeEventListener(\"keydown\", handleKeyDown);\n };\n }, []);", " useEffect(() => {\n const text = locationStore.getState().query.text;\n setQueryText(text === undefined ? \"\" : text);", " }, [locationStore.state.query.text]);", "\n const handleMemoTypeItemClick = (type: MemoSpecType | undefined) => {\n const { type: prevType } = locationStore.getState().query ?? {};\n if (type === prevType) {\n type = undefined;\n }\n locationStore.setMemoTypeQuery(type);\n };", " const handleTextQueryInput = (event: React.FormEvent<HTMLInputElement>) => {\n const text = event.currentTarget.value;\n setQueryText(text);\n locationStore.setTextQuery(text.length === 0 ? undefined : text);\n };", " const handleFocus = () => {\n setIsFocus(true);\n };", " const handleBlur = () => {\n setIsFocus(false);\n };", " return (\n <div className={`search-bar-container ${isFocus ? \"is-focus\" : \"\"}`}>\n <div className=\"search-bar-inputer\">\n <Icon.Search className=\"icon-img\" />\n <input\n className=\"text-input\"\n autoComplete=\"new-password\"\n type=\"text\"\n placeholder=\"\"\n ref={inputRef}\n value={queryText}\n onChange={handleTextQueryInput}\n onFocus={handleFocus}\n onBlur={handleBlur}\n />\n </div>\n <div className=\"quickly-action-wrapper\">\n <div className=\"quickly-action-container\">\n <p className=\"title-text\">{t(\"search.quickly-filter\").toUpperCase()}</p>\n <div className=\"section-container types-container\">\n <span className=\"section-text\">{t(\"common.type\").toUpperCase()}:</span>\n <div className=\"values-container\">\n {memoSpecialTypes.map((type, idx) => {\n return (\n <div key={type.value}>\n <span\n className={`type-item ${memoType === type.value ? \"selected\" : \"\"}`}\n onClick={() => {\n handleMemoTypeItemClick(type.value as MemoSpecType);\n }}\n >\n {t(type.text)}\n </span>\n {idx + 1 < memoSpecialTypes.length ? <span className=\"split-text\">/</span> : null}\n </div>\n );\n })}\n </div>\n </div>\n </div>\n </div>\n </div>\n );\n};", "export default SearchBar;" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "const escapeRegExp = (str: string): string => {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n};", "\nconst walkthroughNodeWithKeyword = (node: HTMLElement, keyword: string) => {\n if (node.nodeType === 3) {\n const span = document.createElement(\"span\");\n span.innerHTML = node.nodeValue?.replace(new RegExp(keyword, \"g\"), `<mark>${keyword}</mark>`) ?? \"\";\n node.parentNode?.insertBefore(span, node);\n node.parentNode?.removeChild(node);\n }\n for (const child of Array.from(node.childNodes)) {\n walkthroughNodeWithKeyword(<HTMLElement>child, keyword);\n }\n return node.innerHTML;\n};", "export const highlightWithWord = (html: string, keyword?: string): string => {\n if (!keyword) {\n return html;\n }", " keyword = escapeRegExp(keyword);", " const wrap = document.createElement(\"div\");", " wrap.innerHTML = html;", " return walkthroughNodeWithKeyword(wrap, keyword);\n};" ]
[ 0, 1, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "import { escape } from \"lodash\";", "\nconst walkthroughNodeWithKeyword = (node: HTMLElement, keyword: string) => {\n if (node.nodeType === 3) {\n const span = document.createElement(\"span\");\n span.innerHTML = node.nodeValue?.replace(new RegExp(keyword, \"g\"), `<mark>${keyword}</mark>`) ?? \"\";\n node.parentNode?.insertBefore(span, node);\n node.parentNode?.removeChild(node);\n }\n for (const child of Array.from(node.childNodes)) {\n walkthroughNodeWithKeyword(<HTMLElement>child, keyword);\n }\n return node.innerHTML;\n};", "export const highlightWithWord = (html: string, keyword?: string): string => {\n if (!keyword) {\n return html;\n }", " keyword = escape(keyword);", " const wrap = document.createElement(\"div\");", " wrap.innerHTML = escape(html);", " return walkthroughNodeWithKeyword(wrap, keyword);\n};" ]
[ 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "", "import { marked } from \"..\";\nimport Link from \"./Link\";", "export const BOLD_REG = /\\*\\*(.+?)\\*\\*/;", "const matcher = (rawStr: string) => {\n const matchResult = rawStr.match(BOLD_REG);\n return matchResult;\n};", "const renderer = (rawStr: string): string => {\n const matchResult = matcher(rawStr);\n if (!matchResult) {\n return rawStr;\n }\n", " const parsedContent = marked(matchResult[1], [], [Link]);", " return `<strong>${parsedContent}</strong>`;\n};", "export default {\n name: \"bold\",\n regex: BOLD_REG,\n matcher,\n renderer,\n};" ]
[ 0, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "import { escape } from \"lodash\";", "import { marked } from \"..\";\nimport Link from \"./Link\";", "export const BOLD_REG = /\\*\\*(.+?)\\*\\*/;", "const matcher = (rawStr: string) => {\n const matchResult = rawStr.match(BOLD_REG);\n return matchResult;\n};", "const renderer = (rawStr: string): string => {\n const matchResult = matcher(rawStr);\n if (!matchResult) {\n return rawStr;\n }\n", " const parsedContent = marked(escape(matchResult[1]), [], [Link]);", " return `<strong>${parsedContent}</strong>`;\n};", "export default {\n name: \"bold\",\n regex: BOLD_REG,\n matcher,\n renderer,\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "", "import { marked } from \"..\";\nimport Link from \"./Link\";", "export const BOLD_EMPHASIS_REG = /\\*\\*\\*(.+?)\\*\\*\\*/;", "const matcher = (rawStr: string) => {\n const matchResult = rawStr.match(BOLD_EMPHASIS_REG);\n return matchResult;\n};", "const renderer = (rawStr: string): string => {\n const matchResult = matcher(rawStr);\n if (!matchResult) {\n return rawStr;\n }\n", " const parsedContent = marked(matchResult[1], [], [Link]);", " return `<strong><em>${parsedContent}</em></strong>`;\n};", "export default {\n name: \"bold emphasis\",\n regex: BOLD_EMPHASIS_REG,\n matcher,\n renderer,\n};" ]
[ 0, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "import { escape } from \"lodash\";", "import { marked } from \"..\";\nimport Link from \"./Link\";", "export const BOLD_EMPHASIS_REG = /\\*\\*\\*(.+?)\\*\\*\\*/;", "const matcher = (rawStr: string) => {\n const matchResult = rawStr.match(BOLD_EMPHASIS_REG);\n return matchResult;\n};", "const renderer = (rawStr: string): string => {\n const matchResult = matcher(rawStr);\n if (!matchResult) {\n return rawStr;\n }\n", " const parsedContent = marked(escape(matchResult[1]), [], [Link]);", " return `<strong><em>${parsedContent}</em></strong>`;\n};", "export default {\n name: \"bold emphasis\",\n regex: BOLD_EMPHASIS_REG,\n matcher,\n renderer,\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "", "import { marked } from \"..\";\nimport Link from \"./Link\";", "export const EMPHASIS_REG = /\\*(.+?)\\*/;", "const matcher = (rawStr: string) => {\n const matchResult = rawStr.match(EMPHASIS_REG);\n return matchResult;\n};", "const renderer = (rawStr: string): string => {\n const matchResult = matcher(rawStr);\n if (!matchResult) {\n return rawStr;\n }\n", " const parsedContent = marked(matchResult[1], [], [Link]);", " return `<em>${parsedContent}</em>`;\n};", "export default {\n name: \"emphasis\",\n regex: EMPHASIS_REG,\n matcher,\n renderer,\n};" ]
[ 0, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "import { escape } from \"lodash\";", "import { marked } from \"..\";\nimport Link from \"./Link\";", "export const EMPHASIS_REG = /\\*(.+?)\\*/;", "const matcher = (rawStr: string) => {\n const matchResult = rawStr.match(EMPHASIS_REG);\n return matchResult;\n};", "const renderer = (rawStr: string): string => {\n const matchResult = matcher(rawStr);\n if (!matchResult) {\n return rawStr;\n }\n", " const parsedContent = marked(escape(matchResult[1]), [], [Link]);", " return `<em>${parsedContent}</em>`;\n};", "export default {\n name: \"emphasis\",\n regex: EMPHASIS_REG,\n matcher,\n renderer,\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "import { escape } from \"lodash-es\";\nimport Emphasis from \"./Emphasis\";\nimport Bold from \"./Bold\";\nimport { marked } from \"..\";\nimport InlineCode from \"./InlineCode\";\nimport BoldEmphasis from \"./BoldEmphasis\";", "export const LINK_REG = /\\[(.*?)\\]\\((.+?)\\)+/;", "const matcher = (rawStr: string) => {\n const matchResult = rawStr.match(LINK_REG);\n return matchResult;\n};", "const renderer = (rawStr: string): string => {\n const matchResult = matcher(rawStr);\n if (!matchResult) {\n return rawStr;\n }", " const parsedContent = marked(matchResult[1], [], [InlineCode, BoldEmphasis, Emphasis, Bold]);", " return `<a class='link' target='_blank' rel='noreferrer' href='${escape(matchResult[2])}'>${parsedContent}</a>`;\n};", "export default {\n name: \"link\",\n regex: LINK_REG,\n matcher,\n renderer,\n};" ]
[ 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "import { escape } from \"lodash-es\";\nimport Emphasis from \"./Emphasis\";\nimport Bold from \"./Bold\";\nimport { marked } from \"..\";\nimport InlineCode from \"./InlineCode\";\nimport BoldEmphasis from \"./BoldEmphasis\";", "export const LINK_REG = /\\[(.*?)\\]\\((.+?)\\)+/;", "const matcher = (rawStr: string) => {\n const matchResult = rawStr.match(LINK_REG);\n return matchResult;\n};", "const renderer = (rawStr: string): string => {\n const matchResult = matcher(rawStr);\n if (!matchResult) {\n return rawStr;\n }", " const parsedContent = marked(escape(matchResult[1]), [], [InlineCode, BoldEmphasis, Emphasis, Bold]);", " return `<a class='link' target='_blank' rel='noreferrer' href='${escape(matchResult[2])}'>${parsedContent}</a>`;\n};", "export default {\n name: \"link\",\n regex: LINK_REG,\n matcher,\n renderer,\n};" ]
[ 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [42, 25, 18, 18, 18, 21], "buggy_code_start_loc": [41, 1, 0, 0, 0, 20], "filenames": ["web/src/components/SearchBar.tsx", "web/src/labs/highlighter/index.ts", "web/src/labs/marked/parser/Bold.ts", "web/src/labs/marked/parser/BoldEmphasis.ts", "web/src/labs/marked/parser/Emphasis.ts", "web/src/labs/marked/parser/Link.ts"], "fixing_code_end_loc": [42, 23, 19, 19, 19, 21], "fixing_code_start_loc": [41, 1, 1, 1, 1, 20], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository usememos/memos prior to 0.9.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "9E9BB4B3-BBB1-406D-96EE-69114B828CF0", "versionEndExcluding": "0.9.0", "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 usememos/memos prior to 0.9.0."}], "evaluatorComment": null, "id": "CVE-2022-4695", "lastModified": "2023-01-05T14:07:08.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-27T15:15:11.603", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2559d548-b847-40fb-94d6-18c1ad58b789"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/65cc19c12efa392f792f6bb154b4838547e0af5e"}, "type": "CWE-79"}
242
Determine whether the {function_name} code is vulnerable or not.
[ "======= 3.4.9", "- fixed measuring dimension for `.gif` images", "", "\n======= 3.4.7", "- fixed: command injection in `Image.pipe()` and `Image.stream()`\n- fixed `DELETE` method for the schemas (now it works like `PATCH` method)\n- fixed: `controller.transfer()`", "======= 3.4.6", "- added: a support for Total.js v4 UIDs", "- updated: file stats\n- updated: calculating of `usage`", "- fixed: applying of `default_root` in static files\n- fixed: routing evaluation\n- fixed: parsing of longer WebSocket messages\n- fixed: mail error handling\n- fixed: `versions` with `default_root`", "======= 3.4.5", "- fixed: a problem with persistent images", "======= 3.4.4", "- added: schema options `$.successful(function(response) {})`\n- added: `options.reconnectserver {Boolean}` to `WEBSOCKETCLIENT`\n- added: `req.snapshot(callback(err, request_body))`\n- added: a new command `CMD('reload_preferences')`\n- added: a new FILESTORAGE mechanism based on `UID`\n- added: `sql` extension to `U.getContentType()`\n- added: `F.stats.performance.usage` which contains percentual usage of the thread", "- updated: `SchemaOptions` method `$.response([index/operation_name])`, e.g. `$.response('workflow.NAME')`\n- updated: snapshot `startscript.js.json` contains tabs instead of spaces\n- updated: `DatabaseBuilder.rule(rule, [param])`, supports string declaration of filter function\n- updated: `URL` validation", "- fixed: cleaning of NoSQL embedded databases\n- fixed: `String.parseCSV()`, now supports multiline strings\n- fixed: a bug when closing of websocket\n- fixed: `DatabaseBuilder.search()` method\n- fixed: `Error` in `CLONE()` method\n- fixed: `schema.inherit()` by adding `schema.middleware()` and `schema.verify()`\n- fixed: parsing messages in WebSocket\n- fixed: a problem in some commands pre-render in the view compiler\n- fixed: parsing of query strings", "======= 3.4.3", "- added: `HASH(value, [type])` for creating hash like in jComponent\n- added: `SchemaOptions.repo` as alias to `SchemaInstance.model.$$repository`\n- added: a new type `CONVERT syntax` to `schema.define()` (more in docs)\n- added: `SchemaEntity.verify(name, function($), [cache])` for async verification of values\n- added: `TEMP` variable as a new global variable (it's cleaned every 7 minutes)\n- added: `CONF.allow_persistent_images: true` which allows to reuse resized images in temp directory\n- added: `req.filecache(callback)` as alias for `F.exists()`\n- added: own QueryParser\n- added: `RESTBuilderInstance.convert('name:String,age:Number')` method\n- added: `RESTBuilder.upgrade(fn(restbuilder))` for upgrading of `RESTBuilder`\n- added: `RESTBuilder` parses Total.js Errors in responses as Error\n- added: `String.prototype.env()` replaces all values in the form `[key]` for `CONF.key`\n- added: WebSocket supports a new type - raw `buffer`\n- added: `Number.fixed(decimals)`", "- updated: `websocket.send2(message, comparer, replacer, [params])` by adding `params` argument for comparer function\n- updated: `Websocket.encodedecode` can enable/disable easily encoding of messages\n- updated: bundling skips all bundles with `-bk.bundle` in filename\n- updated: bundle filenames are displayed in console\n- updated: `UPDATE()` method by adding `noarchive` argument\n- updated: `TEST()` method supports `[subdomain]` keyword and `METHOD url` in URL address\n- updated: `MODIFY([filename], fn)` by adding `filename` argument\n- updated: background of schedulers by @fgnm\n- updated: `U.download()` by adding `param` argument\n- updated: `U.request()` by adding `param` argument\n- updated: `schema.cl(name, [value])` method by adding `value` argument for replacing of existing code-list\n- updated: Tangular version to `v4.0.0`", "- improved: `filename` in modificators (now filenames contain relative paths)\n- improved: performance of `U.request()` (around +10%)\n- improved: performance of `U.download()` (around +10%)\n- improved: performance of `RESTBuilder`\n- improved: CSS minifier by compressing single hex color from e.g. `#000000` to `#000`", "- fixed: localization in `totaljs` executable script\n- fixed: phone validation\n- fixed: `DOWNLOAD()`\n- fixed: `Number.VAT()` by Tomas Novak\n- fixed: debugging mode in Node.js v14\n- fixed: `allow_compile_html` in static files\n- fixed: `ROUTE()` method, there was a problem with spaces `GET /* `\n- fixed: `ACTION()` with json output\n- fixed: controller in `$ACTION()` with used `get` and `query` actions\n- fixed: `PATCH` method in `$ACTION()`\n- fixed: `schema.allow()` in `PATCH` method\n- fixed: image resizing in debug-mode", "======= 3.4.1", "- added: `SchemaOptions.parent` returns a parent model\n- added: Tangular template engine (experimental)\n- added: `String.makeid()` for creating of unique identifier from string\n- added: a new property called `message.ua` to `FLOWSTREAM()`", "- updated: `HttpFile.fs()` by adding `id` argument for updating of existing file\n- updated: default value for `allow_ssc_validation` to `true`", "- fixed: `String.parseDate(format)` with defined format\n- fixed: inheriting of controllers between schemas\n- fixed: `MailMessage.attachments()`\n- fixed: calling of `F.snapshotstats` in cache recycle\n- fixed: `controller.success()`\n- fixed: removing of unused files when a bundle is extracting\n- fixed: a processor function in `F.backup()`", "- improved: `Date.format()`\n- improved: Total.js translate (supports ErrorBuilder and DBMS)", "======= 3.4.0", "- added: `date.setTimeZone(timezone)`\n- added: `NOSQL('~absolute_path.nosql')' loads external NoSQL embedded database\n- added: `TABLE('~absolute_path.nosql')' loads external Table\n- added: `(generate)` subtype into the `config` files\n- added: `String.isBase64()`\n- added: new schema type `Base64`\n- added: SchemaEntity supports `schema.addWorkflowExtension(name, fn($, [data]))`\n- added: SchemaEntity supports `schema.addTransformExtension(name, fn($, [data]))`\n- added: SchemaEntity supports `schema.addOperationExtension(name, fn($, [data]))`\n- added: SchemaEntity supports `schema.addHookExtension(name, fn($, [data]))`\n- added: SchemaEntity supports `schema.setSaveExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setReadExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setQueryExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setRemoveExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setInsertExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setUpdateExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setPatchExtension(fn($, [data]))`\n- added: SchemaOptions supports `$.extend([data])` for evaluating of all extensions for the current operation\n- added: `WebSocket.keys` property (it contains all keys with connections)\n- added: `threads` directory for server-less functionality\n- added: a global variable called `THREAD` with a name of current thread\n- added: `require('total.js').http(..., { thread: 'thread_name' })` evaluates only specified thread\n- added: `require('total.js').cluster.http(..., { thread: 'thread_name' })` evaluates only specified thread in cluster\n- added: framework creates a file with app stats in the form `your_init_script_name.js.json`\n- added: a new config key `allow_stats_snapshot`\n- added: view engine `@{import()}` supports auto-merging JS or CSS files: `@{import('default.js + ui.js')}`\n- added: `exports.options` delegate to component in `FLOWSTREAM`\n- added: `DatabaseBuilder.autofill()` from DBMS\n- added: `HttpFile.extension` property\n- added: `HttpFile.size` property alias to `HttpFile.length`\n- added: auto-session cleaner of unused sessions\n- added: `allow_sessions_unused` config key for cleaning of unused sessions\n- added: missing `PATH.schemas`, `PATH.operations` and `PATH.tasks`\n- added: a new method `PATH.updates`\n- added: easy updating of applications via `UPDATE(versions, [callback], [pause_server_message])`\n- added: NOSQL counter `.reset([type], [id], [date], [callback])` method-\n- added: `session.listlive(callback)` returns all live items in session\n- added: `controller.ua` returns parsed User-Agent\n- added: `$.ua` returns parsed User-Agent in Schemas, Operations, TaskBuilder, `MIDDLEWARE()` and `AUTH()`\n- added: support for `.mjs` extensions\n- added: a simple support for DDOS protection `allow_reqlimit : Number` (max. concurent requests by IP just-in-time)\n- added: unit-testing supports colors, added by @dacrhu\n- added: `String.encryptUID()` as alias for `U.encryptUID()`\n- added: `String.decryptUID()` as alias for `U.decryptUID()`", "- updated: `WEBSOCKET()` supports `+`, `-` and `🔒` as authorization flags\n- updated: `LOAD()` supports `service` type\n- updated: cluster watches `restart` or `restart_NAME_of_THREAD` files for restarting of existing threads\n- updated: cluster supports `auto` mode\n- updated: cluster supports watcher in `debug` mode\n- updated: `*.filefs()`, `*.filenosql()`, `*.imagefs()`, `*.imagenosql()` by adding `checkmeta` argument\n- updated: `$.done([user_instance])` method in `AUTH()`, added a new argument called `user_instance` (optional)\n- updated: GZIP is enabled only for JSON bodies which have more than 4096 bytes\n- updated: `.env` parser supports parsing of `.env-debug` or `.env-release` files according to the mode\n- updated: list of user-agents in `String.parseUA()`", "- fixed: `ON('error404')` when the route doens't exist\n- fixed: `filter` in Schema `workflows`, `transformations` and `operations`\n- fixed: `NOSQL()` joins with absolute paths\n- fixed: `TABLE()` joins with absolute paths\n- fixed: `(random)` subtype in `config` files\n- fixed: `(response)` phrase in `ROUTE()` for multiple `OPERATIONS`\n- fixed: a response in `ROUTE()` with mulitple operations if the result contained some error\n- fixed: a security bug with a path traversal vulnerability\n- fixed: `debug` watcher for `themes`\n- fixed: `generators` in schemas with a new declaration\n- fixed: a problem with handling files in 404 action\n- fixed: `startup` directory in bundles\n- fixed: `schema.inherit()` didn't copy `required` fields.\n- fixed: `SUCCESS()` serialization with `SUCCESS()` argument\n- fixed: a critial bug with `UID()` generator\n- fixed: clearing of DNS cache", "- improved: `LOGMAIL()` mail format\n- improved: starting logs in console output (added IPv4 local address)\n- improved: performance with JSON serialization in `controller.success()` and `controller.done()`", "======= 3.3.2", "- fixed: default time zone (`utc` is default time zone)", "======= 3.3.1", "- added: `RESTBuilder.callback()` which performs `.exec()` automatically\n- added: `FLOWSTREAM()`", "- fixed: `AUDIT()` method\n- fixed: error handling in `controller.invalid()`\n- fixed: `req.authorize()`\n- fixed: CSS auto-vendor-prefixes, fixed `opacity` with `!important`\n- fixed: `CONVERT()` a problem with arrays", "======= 3.3.0", "- added: `NEWTASK(name, declaration)` for creating preddefined `TaskBuilder`\n- added: `TASK(name, taskname, callback, [controller/SchemaOptions/OperationOptions/ErrorBuilder])` for executing preddefined `TaskBuilder`\n- added: a new config key `directory_tasks` for `TaskBuilder`\n- added: a global alias `MODIFY()` for `F.modify()`\n- added: a global alias `VIEWCOMPILE()` for `F.view_compile()`\n- added: `mail.type = 'html'` can be `html` (default) or `plain`\n- added: `$.headers` into the `SchemaOptions`, `OperationOptions` and `TaskBuilder`\n- added: `String.parseCSV([delimiter])` returns `Object Array`\n- added: `String.parseUA([structured])` a simple user-agent parser\n- added: `req.useragent([structured])` returns parsed User-Agent\n- added: a new config key `default_crypto` it can rewrite Total.js crypto mechanism (default: `undefined`)\n- added: a new config key `default_crypto_iv` it's an initialization vector (default: generated from `secret`) or it can contain a custom `hex` value\n- added: a new config key `allow_workers_silent` can enable/disable silent workers (default: `false`)\n- added: a new config sub-type called `random`, example: `secret_key (random) : 10` and `10` means a length of value\n- added: a new command `clear_dnscache` for clearing DNS cache\n- added: commands `INSTALL('command', 'command_name', function)` for registering commands and `CMD(name, [a], [b], [c], [d])` for executing commands\n- added: `ENCRYPTREQ(req, val, [key], [strict])` to encrypt value according to the request meta data\n- added: `DECRYPTREQ(req, val, [key])` to decrypt value according to the request meta data\n- added: `controller.nocache()`\n- added: `controller.nocontent()`\n- added: `REPO` as a global variable\n- added: `FUNC` as a global variable\n- added: `MAIN` as a global variable\n- added: `DEF` as a global variable for defining of behaviour for some operations (alternative to `F`)\n- added: `PREF.set(name, [value])` (read+write) or `PREF.propname` (only read) for reading/writing a persistent preferences\n- added: `F.onPrefSave = function(obj)` to write preferences\n- added: `F.onPrefLoad = function(next(obj))` to read preferences\n- added: `RESTBuilder.url(url)` which returns a new instance of `RESTBuilder` for chaining\n- added: `restbuilder.keepalive()` enables a keepalive for `RESTBuilder` instance\n- added: `SESSION()` management, more in docs\n- added: `controller.sessionid` with ID of `SESSION()`\n- added: `AUTH()` supports a new auth declaration with `$` as `AuthOptions` like `SchemaOptions` or `OperationOptions`\n- added: `AuthOptions` to prototypes\n- added: `ErrorBuilder.length` property (alias for `instance.items.length)\n- added: Schemas `prepare` supports `req` argument\n- added: `DEF.currencies.eur = function(val) {}` registers a currency formatter\n- added: `DEF.helpers` registers a new view engine helper (`F.helpers` is alias for for this object)\n- added: `DEF.validators` is alias for for `F.validators`\n- added: usage of currency formatter `Number.currency(currency)`\n- added: new schema type `Number2` with default value is `null`, not zero `0`\n- added: `@{json2(model, elementID, key1, key2, key3)}` can serialize data with keys defined into the `<script type=\"application/json\">`\n- added: schemas supports `PATCH` and `.setPatch()`, only specified field are processed\n- added: `SchemaOptions` supports `$.keys` for `PATCH` method\n- added: `schema.cl(name)` (\"cl\" means codelist) returns `{Array}` a list of values from defined enum/keyvalue\n- added: `schema.props()` returns `{Object}` meta info about all defined properties\n- added: `SchemaOptions`, `OperationOptions` and `TaskOptions` supports `$.req` and `$.res` properties\n- added: `AUDIT(name, $, [type], message)` a method for audit logs\n- added: __obsolete__ message to older declaration of middleware, schemas and operations\n- added: `U.diffarr(prop, arr_A, arr_B)` for comparing of two arrays\n- added: `DIFFARR(prop, arr_A, arr_B)` is a global alias for `U.diffarr()`\n- added: `global.REQUIRE()` for local modules within app directory\n- added: `global.isWORKER` variable which contains `true` (when the process is executed as a worker) or `false`\n- added: `ACTION(url, [data], callback)` can evaluate a route without request creation\n- added: `ROUTE('🔒 METHOD URL')`, it means that 🔒 adds `authorized` flag\n- added: `ROUTE('+METHOD URL')`, it means that `++` or `+` adds `authorized` flag\n- added: `ROUTE('-METHOD URL')`, it means that `--` or `-` adds `authorized` flag\n- added: `SchemaOptions`, `OperationOptions`, `TaskOptions` supports filtered query arguments via `$.filter`\n- added: `controller.done([value])`\n- added: `SITEMAP()` as alias to `F.sitemap()`\n- added: config key `allow_localize` enables a localization for all `HTML` files\n- added: `controller.breadcrumb` returns all sitemap items\n- added: `PAUSESERVER(name, pause)` pauses web server (alias for `F.wait()`)\n- added: `PROXY(endpoint, hostname, [copypath], [before_fn(uri,req,res)], [after_fn(res)])` makes a direct proxy from webserver\n- added: `schema.middleware(function($, next))` for creating simple middlewares for Schema operations\n- added: `FILE404(fn(req, res))` performs a simple fallback for non-existing files\n- added: `$PATCH(schema, model, [options], callback, [controller])` method\n- added: `.env` parser to `process.env`\n- added: `String.parseENV()` for parsing `.env` syntax\n- added: `$.noop()` for custom responses\n- added: `$ACTION(schemaroute, [model], callback, [controller])` evaluates schema\n- added: `process.send('total:restart')` performs a restart of app when the app is in debug mode\n- added: `NOSQLREADER(filename)` for reading different files of NoSQL embedded databases\n- added: `TABLEREADER(filename)` for reading different files of Table embedded databases\n- added: `Mail.use()` an alias for `F.useSMTP()`\n- added: `F.onAudit(name, data)` delegate for handling audit logs\n- added: Components support a new features called `Parts`, more in docs", "- updated: `$.invalid()` without arguments can return a function `function(err)`\n- updated: Mail `unsubscribe` appends new header which enables `unsubscribe` in e.g. iOS\n- updated: `MODIFY`, handler contains a new argument `controller`\n- updated: `headers` argument in `controller.proxy` supports `flags: []` for REQEUST method\n- updated: `.filefs()` and `.filenosql()` supports `download` with `true` or with `(name, type) => 'new_name'` (`filename` will be read from NoSQL binary file)\n- updated: `$.done(arg)` argument `@arg` can be `boolean` (response will be as a value) or object/primitive value (`arg` will be as a value)\n- updated: `String.arg(obj, [encode], [def])` added `encode` (`true`, `json`, `html`) and `def` arguments\n- updated: `AUTH(req, res, flags, next)` and `next` function can handle `callback(err, user)`\n- updated: `REQUEST()` supports `keepalive` flag\n- updated: `bundles` mechanism supports merging files `--filename` between `bundles` files\n- updated: `String.hash(true)` returns unsigned int\n- updated: `CONF:default_image_converter` supports `magick` for new version of ImageMagick\n- updated: `CONF.default_image_consumption` can contain ZERO value which means disabled optimialization of CPU/memory consumption\n- updated: `CONF.default_image_consumption` has changed a default value to `0`\n- updated: `U.parseXML(str, [replace])` and `String.parseXML([replace])` contains a new argument called `replace`\n- updated: `LOAD()` added a callback function\n- updated: components support `encoding=\"utf8\"` attribute for `<file` tag (default: `base64`)\n- updated: `EventEmitter2` supports a new argument `obj`, example: `U.EventEmitter2(obj)` or supports `.extend` method: `U.EventEmitter2.extend(proto)`\n- updated: `UID()` generates new types of `UID` with 100% backward compatibility\n- updated: `FILESTORAGE()` now it works in cluster mode", "- fixed: schemas validation\n- fixed: error handling in dynamic schemas\n- fixed: CSS variables\n- fixed: CSS variables with additional `!important` clause\n- fixed: `controller.proxy()` with Gzip/Deflate compression\n- fixed: HTTP status code with `204` in `REQUEST()`\n- fixed: `cookies` in `WEBSOCKETCLIENT`\n- fixed: `REQUEST()` with `json` flag and with `null` and `''` value\n- fixed: rendering components in `layout`\n- fixed: resources, there was a bug with reading of value from `default.resource`\n- fixed: too many open files in `res.image()`\n- fixed: too many open files in `res.filefs()`\n- fixed: Schema `Boolean` parser\n- fixed: renamed `F.stats.request.path` to `F.stats.request.patch`\n- fixed: SMTP sender (a problem with auth mechanism with some mail servers)\n- fixed: filter in `F.backup()`\n- fixed: paths for stored directories in `F.backup()`\n- fixed: uploading files\n- fixed: `U.getExtension()` by @molda", "- renamed: `*.routeScript` to `*.public_js`\n- renamed: `*.routeStyle` to `*.public_css`\n- renamed: `*.routeFont` to `*.public_font`\n- renamed: `*.routeVideo` to `*.public_video`\n- renamed: `*.routeImage` to `*.public_image`\n- renamed: `*.routeDownload` to `*.public_download`\n- renamed: `*.routeStatic` to `*.public`\n- renamed: `controller.viewCompile()` to `controller.view_compile()`\n- renamed: event `cache-set` to `cache_set`:\n- renamed: event `controller-render-meta` to `controller_render_meta`\n- renamed: event `request-end` to `request_end`\n- renamed: event `websocket-begin` to `websocket_begin`\n- renamed: event `websocket-end` to `websocket_end`\n- renamed: event `request-begin` to `request_begin`\n- renamed: event `upload-begin` to `upload_begin`\n- renamed: event `upload-end` to `upload_end`\n- renamed: event `cache-expire` to `cache_expired`", "- __removed: backward compatibility__ with older version of Node.js < 10\n- removed: `F.hash()`, alternative `String.prototype.hash()`\n- removed: `controller.hash()`, alternative `String.prototype.hash()`", "- improved Schemas and error handling\n- improved `res.filefs()` method for nonexistent files", "======= 3.2.0", "- added: `WORKER()` alias to `F.worker()`\n- added: `WORKER2()` alias to `F.worker2()`\n- added: `F.cluster.https()`\n- added: `TaskBuilder.done2([send_value])` returns `function` with wrapped `.done()`\n- added: `TaskBuilder.success2([send_value])` returns `function` with wrapped `.success()`\n- added: `TaskBuilder.next2(name)` returns `function` with wrapped `.next()`\n- added: new `RESTBuilder` aliases `.DELETE()`, `.PUT()`, `.POST()`, `.PATCH() and `.GET()`\n- added: `schema.before(key, (value, model, index) => value)` is a simple and new alternative to `schema.setPrepare()`\n- added: `SchemaInstance.$parent` returns a parent schema (if the schema is nested schema)\n- added: `SchemaOptions.redirect(url)` can perform a redirect from the schema\n- added: `OperationOptions.redirect(url)` can perform a redirect from the operation\n- added: `.ics` extension as acceptable file for the web server", "- updated: `F.worker2()` returns entire `stdout` buffer in the `callback(err, buffer)`\n- updated: `$options()` by adding `disabled` key\n- updated: `String.ROOT()` by adding a support for jComponent `AJAX()` calls\n- updated: `RESTBuilder.method(method, [data])` added `data` argument\n- updated: `String.parseDate([format])` added `format` argument\n- updated: SMTP settings contain `heloid` as `heloidentifier` (manually can be defined `HELO` or `EHLO` command)\n- updated: SMTP hostname is computed from email if SMTP is not specified", "- fixed: critical bug with security + improved security\n- fixed: system routing\n- fixed: NoSQL sorting, solved a strange problem\n- fixed: `U.request()` with `GET` method by @khaledkhalil94 (it doesn't send JSON data if `data` is null/undefined)\n- fixed: `F.wait()` in WebSocket\n- fixed: `String.capitalize(true)`\n- fixed: `REQUEST()` uploading of additional multipart/form-data (removed encoding)\n- fixed: view engine conditions defined in `<script>`\n- fixed: auto-redirects in `U.download()`\n- fixed: image streams resizing\n- fixed: `@{'%config_key'}` a problem with rendering a value with `'`", "- removed: `X-Powered-By: Total.js`", "======= 3.1.0", "- added: CSS variables support default values `border-radius: $radius || 10px`\n- added: NoSQL storage `.find(beg, end, [threads])` + `.count(beg, end, [threads])` + '.scalar(beg, end, type, field, [threads])' with multiple thread support\n- added: `U.reader()`\n- added: `bundles` supports merging files between bundle and project, project file must start with e.g. `--name.js`\n- added: `.bundlesignore` support with similiar functionality like `.gitignore`\n- added: support for `SameSite` cookie attribute\n- added: `RUN()` for executing multiple Total.js operations\n- added: a new global alias `CONF` (it's a reference to config) for `F.config`\n- added: a new global alias `FUNC` (it's a reference to functions) for `F.functions`\n- added: `DatabaseBuilder.arg(key, value)` for adding an dynamic argument\n- added: NOSQL/TABLE modify supports `!field` as boolean toggle\n- added: NOSQL/TABLE modify supports a new type `$age: 'js_code'` with some JS code\n- added: NOSQL/TABLE update supports a new type `'js_code'` with some JS code\n- added: a new config item `default-restbuilder-timeout : 10000`\n- added: a new config item `default-cors : https://www.totaljs.com, https://www.componentator.com` which allows originators for `CORS()` method\n- added: a new config item `default-request-maxkeys : 33` for restricting query max. keys\n- added: a new config item `logger : false` which enables logging for Middleware, Schemas and Operations\n- added: a new config item `bundling : shallow` which enables shallow bundling (if `bundle.json` exists then the bundles won't be extracted)\n- added: `SchemaOptions` and `OperationOptions` supports `$.cancel()` method\n- added: `CACHE(name, [value], [expire], [persistent])` alias for `F.cache.get2()` and `F.cache.set()` or `F.cache.set2()`\n- added: encryption of config values\n- added: `F.refresh()` for refreshing of internal cache\n- added: `DatabaseBuilder.each(fn)` for browsing of evaluated records\n- added: Bundles can be downloaded from URL addresses\n- added: `ONCE()` alias to `F.once()`\n- added: `image.define(value)` performs `convert -define 'value'`\n- added: Total.js JS files (+ packages) tarted with `.` (dot) or ended with `-bk` won't be processed\n- added: A new builder called `TaskBuilder` for creating custom tasks in Schemas or Operations\n- added: `WebSocket.send2(message, [comparer(client, message)], [replacer])` a new method for better sending frames\n- addde: `PATH` as a global alias for `F.path`", "- updated: `debug` mode creates a `start_name_script.pid` instead of `debug.pid`\n- updated: `NEWOPERATION()` supports `repeat`, `stop` and `binderror` arguments (more in docs)\n- updated: routing, now it supports operations in the form `ROUTE('.. * --> @save_operation @load_operation (response)')`\n- updated: `ROUTE()` supports multiple HTTP method declaration `ROUTE('GET,POST,PUT /something/', action)`\n- updated: `ROUTE()` supports dynamic schemas\n- updated: `REQUEST()` can return binary data if the content-type is not `text/*` or `application/*`\n- updated: NoSQL joins support array values\n- updated: `ROUTING(id:|search, [flags])` method\n- updated: `F.path.mkdir(path, [cache])` can cache a current satte (default: false)\n- updated: `controller.all()` can return `Array` of all WebSocketClient\n- updated: startup info by adding user name\n- updated: `LOCALIZE()` now `url` arg can be a function which replaces `F.onLocale`", "- fixed: a critical bug with storing uploaded files via `httpfile.fs()` or `httpfile.nosql()`\n- fixed: a critical bug with JavaScript minificator\n- fixed: a critical bug with NoSQL counter and freezing app\n- fixed: a critical bug with rendering of multiple async components\n- fixed: a critical bug with GZIP compression (sometimes appeared in Safari)\n- fixed: `nosql.update()` and `nosql.modify()` methods if the first argument is a function\n- fixed: `F.wait()` in the test mode\n- fixed: `LOCALIZE()` for nested directories\n- fixed: sending of error handling when WebSocketClient is starting (for example: `unauthorized`)\n- fixed: `versions` and `auto` feature with enabled `F.wait()`\n- fixed: `versions` and `auto` feature with direct link to file\n- fixed: `LOAD('release')` a release mode\n- fixed: `SchemaInstance.$clean()` for nested schemas\n- fixed: extracting `bundles` (added `/flow/` and `/dashboard/`)\n- fixed: subdomain routing for `localhost`\n- fixed: service for database cleaner\n- fixed: rendering group of components\n- fixed: RESTBuilder - JSON request without param sends an empty object\n- fixed: `$MAKE()` with `callback`\n- fixed: `String.slug()` for UTF - Chinese/Japan/Arabic/etc. chars\n- fixed: async rendering of `components`\n- fixed: RESTBuilder cache works only if the response status is `200`\n- fixed: compressing CSS with `\\t` tabs\n- fixed: `controller.autoclear()`\n- fixed: `controller.proxy()`\n- fixed: `repeat` mode in `SCHEDULE()`\n- fixed: `--inspect` argument for Workers by Tema Smirnov\n- fixed: TLS in SMTP mail sender\n- fixed: applying of versions\n- fixed: unit-tests reads only `javascript` files\n- fixed: `controller.invalid()` a problem with ErrorBuilder as a argument", "- removed: `F.config.debug`\n- removed: `controller.isDebug`", "- improved: NoSQL reader\n- improved: `UID()` -> now it changes a random hash each minute\n- improved: CORS\n- improved: rendering of components", "======= 3.0.0", "- added: (IMPORTANT) bundles\n- added: (IMPORTANT) Total.js components can have async delegate\n- added: (IMPORTANT) Total.js components support nested public files encoded in base64\n- added: (IMPORTANT) NoSQL worker\n- added: (IMPORTANT) NoSQL embedded storage for smaller big data / IoT\n- added: `debugging` supports live reloading\n- added: new schema operations: `schema.setInsert()` and `schema.setUpdate()`\n- added: `RESTBuilder.patch([data])`\n- added: `RESTBuilder.type(new-content-type)`\n- added: `CONVERT(obj, schema)` for quick converting values like Schema (more in docs.)\n- added: `Capitalize2` schema type which converts only the first char\n- added: `MailMessage.high()` sets `high` priority of the email messsage\n- added: `MailMessage.low()` sets `low` priority of the email messsage\n- added: `MailMessage.confidential()` sets `Sensitivity` header with `confidential` value\n- added: `MailMessage.attachmentnosql(db, id, [name])` sends a file from NoSQL embedded database\n- added: `MailMessage.attachmentfs(storage_name, id, [name])` sends a file from FileStorage\n- added: `SchemaBuilderEntity.$stop()` stops the async list\n- added: `SchemaOptions.stop()` alias to `$.model.$stop()`\n- added: `SchemaOptions.next()` alias to `$.model.$next()`\n- added: `SchemaOptions.output()` alias to `$.model.$output()`\n- added: `SchemaOptions.clean()` alias to `$.model.$clean()`\n- added: `SchemaOptions.response()` alias to `$.model.$response([index])`\n- added: `SchemaOptions.$async(callback, [index])` alias to `$.model.$async()`\n- added: `SchemaOptions.$get([options], [callback])` alias to `$.model.$get()`\n- added: `SchemaOptions.$insert([options], [callback])` alias to `$.model.$insert()`\n- added: `SchemaOptions.$query([options], [callback])` alias to `$.model.$query()`\n- added: `SchemaOptions.$remove([options], [callback])` alias to `$.model.$remove()`\n- added: `SchemaOptions.$save([options], [callback])` alias to `$.model.$save()`\n- added: `SchemaOptions.$update([options], [callback])` alias to `$.model.$update()`\n- added: `SchemaOptions.$workflow(name, [options], [callback])` alias to `$.model.$workflow()`\n- added: `SchemaOptions.$transform(name, [options], [callback])` alias to `$.model.$transform()`\n- added: `SchemaOptions.$operation(name, [options], [callback])` alias to `$.model.$operation()`\n- added: `SchemaOptions.$hook(name, [options], [callback])` alias to `$.model.$hook()`\n- added: `SchemaOptions.stop()` alias to `$.model.$stop()`\n- added: a new route flag type `&group` something like `roles` but groups aren't evaluated\n- added: `route.groups` with defined groups\n- added: NoSQL `database.listing([view])` which generates a listing response\n- added: `DatabaseBuilder.insert(fn(doc))` can modify a document after `update` or `modify` has `insert` mode\n- added: `DatabaseBuilder.query(code)` can contain a raw JS condition in the form e.g. `doc.age > 18 && doc.age < 33`\n- added: `DatabaseBuilder.regexp(name, regexp)` RegExp search in strings\n- added: `DatabaseBuilder.fulltext(name, regexp, [weight])` full text search in strings, more info in docs.\n- added: `DatabaseBuilder.hour(name, [compare], value)` creates a condition for hours\n- added: `DatabaseBuilder.minute(name, [compare], value)` creates a condition for minutes\n- added: `Database.find2()` performs faster and reverse reading of documents (from end to begin of the file)\n- added: `Database.stream(fn, [repository], [callback(err, repository, count)])` for streaming documents\n- added: `Database.lock(callback(next))` locks all internal DB operations\n- added: `Database.ready(callback)` executes a callback when DB is ready to use (only for special cases if you use indexes)\n- added: new directory `schemas` with a new configuration item `directory-schemas'\n- added: new directory `operations` with a new configuration item `directory-operations'\n- added: `String.crc32([unsigned])`\n- added: `U.hash('crc32')` and `U.hash('crc32unsigned')`\n- added: config `nosql-worker' for enabling worker for NoSQL embedded database (default: `false`)\n- added: config `nosql-inmemory' can contain name of databases e.g. (`users, products`) or String Array\n- added: config `nosql-cleaner` for cleaning databases from removed documents (default: `1440` === 24 hours)\n- added: config `nosql-logger` (default `true`) enables simple logs when re-indexing and cleaning\n- added: config `security.txt` for auto-generating security.txt content (more in docs)\n- added: config `default-proxy` for default web proxy server\n- added: config `allow-cache-cluster` (default `true`) allow/disallow cache synchronization\n- added: `GUID()` a global alias for `U.GUID()`\n- added: `VIEW()` a global alias for `F.view()`\n- added: `SchemaBuilderEntity.$response([index])` returns a specific response from an operation in `async` queue\n- added: `$SAVE(schema, model, [options], [callback], [controller])` performs `schema.save()`\n- added: `$INSERT(schema, model, [options], [callback], [controller])` performs `schema.insert()`\n- added: `$UPDATE(schema, model, [options], [callback], [controller])` performs `schema.update()`\n- added: `$REMOVE(schema, [options], [callback], [controller])` performs `schema.remove()`\n- added: `U.streamer2()` same functionality as `U.streamer()` but it returns `Buffer` instead of `String`\n- added: `Number.round([precision])`\n- added: `UID([type])` supports custom types, e.g. `UID('users')` or `UID('orders')`\n- added: `REQUEST()` global method, it's alias to `U.request()`\n- added: `NOW` global property, it's alias to `F.datetime`\n- added: `DatabaseBuilder.promise()`\n- added: `RESTBuilder.promise()`\n- added: `RESTBuilder.plain()` it returns a raw string from the response body\n- added: `versions` file supports `auto` value for generating auto-checksum of files\n- added: `F.load()` supports `test`\n- added: NoSQL binary supports `custom` small data attributes\n- added: CSS and JS supports a simple View Engine markup (config + resources + F.global)\n- added: `controller.split` alias to `controller.req.split`\n- added: nicer error response messages\n- added: `RESTBuilder.proxy(proxy)` for HTTP proxy\n- added: `U.request()` supports a new flag `proxy`, for example `proxy 127.0.0.1:8080`\n- added: NoSQL database a new event `change`, more in docs\n- added: `schema.define()(DEFAULT_VALUE)` added `DEFAULT_VALUE`\n- added: `TESTUSER([user])` for faking of `F.onAuthorize` delegate, targeted for unit-testing only\n- added: `G` as a global alias for `F.global`\n- added: `ERROR([name])` is an improved `F.error()` without arguments\n- added: a simple support for `.heic` and `.heif` image format\n- added: `controller.sitemap_url2()`\n- added: `controller.sitemap_name2()`\n- added: `@{sitemap_url2()}`\n- added: `@{sitemap_name2()}`\n- added: `F.syshash` contains a simple MD5 hash with OS info\n- added: `SchemaEntity.clear()` for removing all current definition\n- added: new view engine markup `@{#}` for simulating of root URL\n- added: new view engine command `@{root}` for getting sub-root path\n- added: `String.ROOT()` for replacing `@{#}` markup in strings\n- added: `U.decryptUID(value, key)` for encrypting number/string values\n- added: `U.encryptUID(value, key)` for decrypting of number/string values\n- added: `F.config['secret-uid']` as a hidden secret for encrypting/decrypting values\n- added: `F.dir(path)` for changing of root directory\n- added: `NOSQL()/TABLE().memory(count, [size])` for memory consumption, more in docs\n- added: `HttpFile.fs(storage_name, [custom], [callback])` saves a file into the FileStorage\n- added: `HttpFile.nosql(db_name, [custom], [callback])` saves a file into the FileStorage\n- added: `res.filefs(storage_name, id, [download], [headers], [callback])` returns file from FileStorage\n- added: `res.filenosql(db_name, id, [download], [headers], [callback])` returns file from NoSQL binary\n- added: `res.imagefs(storage_name, id, image_make_fn, [headers], [callback])` returns file from FileStorage\n- added: `res.imagenosql(db_name, id, image_make_fn, [headers], [callback])` returns file from NoSQL binary\n- added: new stats `F.stats.performance` contains count of `request` and `file` per minute\n- added: new method `controller.operation(name, value, [callback], [options])` for evaluating of operation", "- updated: (IMPORTANT) NoSQL binary divides files to independent directories for 1000 files per directory\n- updated: `GROUP()` by adding a new argument `url_prefix`\n- updated: `NEWSCHEMA()` supports `NEWSCHEMA('group/name')`\n- updated: `ROUTE()`, extended syntax for schemas, for example: `Schema --> @name` (more in docs.)\n- updated: `ROUTE()` supports a new HTTP method definition `ROUTE('GET /api/users/')`, `ROUTE('POST /api/users/')`, etc.\n- updated: `ROUTE()` supports a schema definition directly in the URL `ROUTE('GET /api/users/ *User --> @save')`, etc.\n- updated: `tpm` supports a new command called `bundle`, for example: `tpm bundle cms`\n- updated: `F.restore()` filter can return a new filename (for files only)\n- updated: `@{import('livereload')}` or `@{import('livereload wss://mywebsite.com')}` supports `livereload` value and it's rendered in `debug` mode only\n- updated: information after the framework is started\n- updated: `schema.define('name', null)` removes a schema field\n- updated: Chunker supports `compression`, default `true`\n- updated: Chunker supports `autoremove` processed files in `each()` or `read()` method, default `true`\n- updated: `String.parseConfig(def, [onError])` can handle errors better\n- updated: `middleware`, now Total.js supports new declaration `F.middleware(function($) {})`\n- updated: `F.wait()` HTML template\n- updated: JavaScript compressor, now optimizes multiple `var` declarations\n- updated: `CORS()` without arguments for all routes, methods and origins\n- updated: `CORS()` tries to join multiple same preferences to one\n- updated: `CORS(path)` without additional arguments allows all HTTP methods\n- updated: `U.keywords()` for Chinese/Japan characters\n- updated: `@{import()}` by adding `manifest` value linked to `/manifest.json`\n- updated: `F.use()` supports `function` instead of `middleware` name\n- updated: improved crypto algorithm\n- updated: decreased a maximum count of keys to `33` from `69` when the query string is parsing\n- updated: extended `schema.required(name, (model, workflow) => workflow.update)`, more in docs.\n- updated: `$MAKE(schema, model, [filter/workflows], ...)` supports `workflows` (array or object) instead of filter for `schema.required()`\n- updated: `OPERATION()` by adding `controller`", "- fixed: mail attachments\n- fixed: mail `message.manually()`\n- fixed: WebSocket comparing of `origin` header\n- fixed: uninstalling CORS routes\n- fixed: cache for `favicon`\n- fixed: `Date.extend()`\n- fixed: `String.isJSON()` validator\n- fixed: `String.parseDate()` now it parses date to UTC correctly\n- fixed: `Date.format()` now it formats a date as UTC correctly\n- fixed: HTML compressor with `\\r\\n` (Windows line endings)\n- fixed: schema validation\n- fixed: `U.atob()`\n- fixed: `U.btoa()`\n- fixed: schema field can be changed dynamically\n- fixed: `String.arg()`\n- fixed: `controller.href()` with Array values\n- fixed: `U.get()` a problem with path with `-`\n- fixed: `U.set()` a problem with path with `-`\n- fixed: `F.path.mkdir()` in Windows and Linux", "- replaced: config `disable-clear-temporary-directory` to `allow-clear-temp : true|false`\n- replaced: config `disable-strict-server-certificate-validation` to `allow-ssc-validation : true|false`\n- replaced: config `default-websocket-request-length` to `default-websocket-maxlength`\n- replaced: config `default-request-length` to `default-request-maxlength`\n- replaced: config `default-maximum-file-descriptors` to `default-maxopenfiles`\n- replaced: `controller.proxy()` functionality (the name remains) via `controller.proxy2()` functionality", "- removed: `F.responseFile()`\n- removed: `F.responsePipe()`\n- removed: `F.responseImage()`\n- removed: `F.responseImageWithoutCache()`\n- removed: `F.responseStream()`\n- removed: `F.responseBinary()`\n- removed: `F.responseContent()`\n- removed: `F.responseRedirect()`\n- removed: `F.response400()`\n- removed: `F.response401()`\n- removed: `F.response404()`\n- removed: `F.response408()`\n- removed: `F.response431()`\n- removed: `F.response500()`\n- removed: `F.response501()`\n- removed: `F.responseStatic()`\n- removed: `F.setModified()`\n- removed: `F.notModified()`\n- removed: `F.responseCode()`\n- removed: `F.noCache()`\n- removed: `controller.$modified()`\n- removed: `controller.$etag()`", "- improved: `debug` mode timing with improved consumption\n- improved: performance (+20%) NoSQL embedded database\n- improved: reading performance (+5%) in `U.streamer()`\n- improved: CSS compressor\n- improved: CORS processing\n- improved: internal encryption/decryption mechanism", "======= 2.9.4 (HOTFIX)", "- fixed: mail attachments\n- fixed: comparing `origin` header in WebSocket\n- fixed: unit-testing", "======= 2.9.3 (HOTFIX)", "- added: `String.arg(obj)` for a simple templating `Hello {variable}!`\n- added: new event `ON('@controllername', function() {})` -> is executed if the controller is evaluated", "- updated: RESTBuilder default headers are lower-case\n- updated: `content-disposition` header by adding `utf-8` according to [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2.2)", "- fixed: a missing property `controller.params` in WebSocket controller\n- fixed: `$ASYNC()` execution in some cases\n- fixed: `SCRIPT()` code with comments\n- fixed: a callback reference in `OPERATION()`\n- fixed: cache after route is removed\n- fixed: `409` system route\n- fixed: requests with `range` header and bad values\n- fixed: `clearSchedule()`\n- fixed: `Date.extend()` problem with months\n- fixed: NoSQL counter reading stats", "======= 2.9.2", "- added: `controller.html(body, [headers])`\n- added: `F.cluster.master(name, [data])` - for child processes, this method emits an event in master process\n- added: `F.cluster.on(name, callback(data))` - master event listener\n- added: `LOGMAIL()` global alias for `F.logmail()`\n- added: `MAIL()` global alias for `F.mail()`\n- added: own implementation of `onFinished`\n- added: `RESTBuilder.cookies(obj)` can set cookies as raw object\n- added: `RESTBuilder.cook([true/false])` enables persistent cookies\n- added: `SchemaOptions.params` which returns dynamic params from the controller's action\n- added: `SchemaOptions.done([arg])` as a callback (contains wrapped SUCCESS())\n- added: `SchemaOptions.DB()` which returns `DB(this.error)` instance (for SQL Agent)\n- added: `OperationOptions.done([arg])` as a callback (contains wrapped SUCCESS())\n- added: `OperationOptions.DB()` which returns `DB(this.error)` instance (for SQL Agent)\n- added: static method `Image.measure(type, buffer)` for measuring width/height of image\n- added: `EACHOPERATION(function(name) {})` for obtaining all registered operations\n- added: `controller.params` which returns dynamic params from the action", "- updated: `F.load()`, now supports `string` for `debug` or `release` mode\n- updated: `F.cluster.request()` can be executed from master process\n- updated: `Image.miniature()` change a default filter from `Box` to `Hamming`\n- updated: `U.request()` supports a new flag `cookies` which enables a parsing cookies from response", "- fixed: schema validation (problem with Arrays)\n- fixed: determines `x-forwarded-proto`\n- fixed: nested schema validation\n- fixed: themes static routing\n- fixed: NoSQL reader\n- fixed: NoSQL counter (sorting while reading stats)\n- fixed: loading dependencies\n- fixed: uninstalling middleware\n- fixed: reading/updating sitemap in controller", "- removed: max. sort `string` length\n- removed: `auto` appending `.css` and `.js` extension in view engine\n- removed: experimental `defer` feature", "- improved: GZIP compression\n- improved: code", "======= 2.9.1 (HOTFIX)", "- added: `controller.throw409()`, `req.throw409()`\n- added: new view aliases: `@{R.something}` for `repository`, `@{M.something}` for `model` and `@{G.something}` for `global`", "- updated: `ErrorBuilder.push()` supports `.push(name, status_code)` or `.push(name, error, status_code)`", "- fixed: sitemap language auto-setting\n- fixed: NoSQL: `builder.paginate()` a problem with zero limit (default limit will be `maxlimit`)\n- fixed: NoSQL number filtering\n- fixed: localization of ErrorBuilder in controllers", "======= 2.9.0", "- added: `WebSocketClient`\n- added: `$ASYNC(schema, callback, [index], [controlller])` alias to `SchemaBuilderEntity.$async()`\n- added: `ArrayBuffer.prototype.toBuffer()`\n- added: `AUTH(fn)` is an alias to `F.onAuthorize = fn`\n- added: `controller.success()` alias to `controller.json(SUCCESS(value))`\n- added: `CORS()` alias to `F.cors()`\n- added: `DatabaseBuilder.paginate(page, limit)`\n- added: `F.config['allow-compile']` can disable the whole compilation of static files\n- added: `F.config['default-dependency-timeout']` it's a timeout for module dependencies\n- added: `F.path.rmdir(directory/directories, callback)`\n- added: `F.path.unlink(file/files, callback)`\n- added: `LOCALIZE()` a new global alias to `F.localize()`\n- added: `MAP()` a new global alias to `F.map()`\n- added: `MERGE()` a new global alias to `F.merge()`\n- added: `MIDDLEWARE()` a new global alias to `F.middleware()`\n- added: `NOSQL('users').backups([filter(doc)], callback(err, response))` returns all backups\n- added: `SchemaOptions.invalid(name, [value], [path], [index])` alias to `$.errors.push() + callback()`\n- added: `SchemaOptions.success()` alias to `callback(SUCCESS(value))`\n- added: `controller.sitemapid` contains a sitemap identifier\n- added: `controller.sitemap_add(parent, name, url)` appends a new item into the sitemap per request\n- added: `@{sitemap_add(parent, name, url)}` appends a new item into the sitemap per request\n- added: `SchemaEntity.required('fieldname', boolean/function(model))` which can disable/enable validation for this field", "- updated: `sitemap` routing can contain an additional path, e.g. `#sitemapid/path/`\n- updated: `F.localize()` supports sitemap routing\n- updated: `F.merge()` supports sitemap routing\n- updated: `F.map()` supports sitemap routing\n- updated: `F.http(mode, [options], [middleware(listen)])` added a new argument `middleware`\n- updated: `debug.js` now reads directories according to the config (author: @luoage)\n- updated: config parser supports `config` sub-type\n- updated: `controller.$exec()` --> `callback` is by default `controller.callback()`\n- updated: `F.localize()` has enabled `compression` by default\n- updated: HTTP server is listening after the framework is completely loaded\n- updated: (IMPORTANT) HTTP cache in dynamic content and static files\n- updated: `F.prototypes()` by adding `OperationOptions`\n- updated: ErrorHandling in schemas (supports inline validation and advanced conditions)\n- updated: `F.noCache()` is obsolete", "- renamed: `allow-handle-static-files` to `allow-static-files`", "- fixed: (IMPORTANT) `DatabaseBuilder.in()`\n- fixed: (IMPORTANT) `U.ls2()`\n- fixed: (IMPORTANT) `WebSocket` implementation (author: @jozefgula)\n- fixed: `ArrayBuffer` in webosocket\n- fixed: `F.path.mkdir()` on Windows (author: @molda)\n- fixed: `F.restore()` on Windows (author: @molda)\n- fixed: `F.rmdir` removes all files and directories\n- fixed: `JSON` type in Total.js schemas\n- fixed: `MODEL()`, `MODULE()`, `INCLUDE()` now are direct aliases\n- fixed: a check for maximum length of request data\n- fixed: Date formatting with `a` value\n- fixed: empty localization in view engine e.g. `@()`\n- fixed: external static routing in view engine on Windows\n- fixed: NoSQL filtering with `or`\n- fixed: NoSQL multiple updates\n- fixed: NoSQL sorting of boolean values in larger dataset\n- fixed: responding on `range` header\n- fixed: unit testing (author: @ckpiggy)\n- fixed: `schema.setPrefix()` in nested schemas\n- fixed: sitemap localization\n- fixed: CORS custom headers\n- fixed: NoSQL date filtering", "- improved: performance and security", "======= 2.8.0", "- added: `NOSQL().restore()` restores a database (its package)\n- added: Mail options support a new property `xoauth2` (it needs to contain a `BASE64` value) for sending emails via OAuth 2.0 tokens (more in docs)\n- added: `F.path.mkdir(path)` creates all directories according to the path\n- added: `MailMessage.send2([callback])` sends a message according to the framework configuration\n- added: a new filter for NoSQL embedded `DatabaseBuilder.contains(name)`\n- added: a new filter for NoSQL embedded `DatabaseBuilder.empty(name)`\n- added: (IMPORTANT) NoSQL counter supports daily stats (NoSQL counter files will be upgraded automatically and backwards incompatible)\n- added: (IMPORTANT) NoSQL database and counter can read data from URL\n- added: NoSQL counter `db.counter.daily_sum([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.daily_max([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.daily_min([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.monthly_sum([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.monthly_max([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.monthly_min([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.yearly_sum([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.yearly_max([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.yearly_min([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.stats_sum(top, [year], [month], [day], callback)` for reading stats\n- added: NoSQL counter `db.counter.stats_max(top, [year], [month], [day], callback)` for reading stats\n- added: NoSQL counter `db.counter.stats_min(top, [year], [month], [day], callback)` for reading stats\n- added: NoSQL counter `db.counter.minimum([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.maximum([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.min(id, value)` for writing stats\n- added: NoSQL counter `db.counter.max(id, value)` for writing stats\n- added: NoSQL counter `db.counter.sum(id, value)` for writing stats (alias for `db.counter.hit()`)\n- added: NoSQL counter: a new event `stats` when the stats are changed\n- added: NoSQL logging in `DatabaseBuilder.log(msg, [user])`\n- added: NoSQL backuping documents while they are updating/removing in `DatabaseBuilder.backup([user])`\n- added: `CLONE(obj)` alias for `U.clone()`\n- added: `GROUP(flags, fn)` alias for `F.group()`\n- added: `F.cache.set2()` it creates a persistent cache (persistent items are stored in a file)\n- added: new View Engine command `@{'%config'}` which reads a value from config directly\n- added: `F.config['allow-filter-errors']` for filtering network unhandled errors\n- added: `REDIRECT()` alias for `F.redirect()`", "- updated: (IMPORTANT) packages compress/decompress function supports streaming data\n- updated: (IMPORTANT) `NOSQL().backup()` !!! was changed !!!!\n- updated: `controller.view(name/url, [model], [headers], [partial])` can render a view from URL address\n- updated: `F.backup()` argument `path` can contain `String Array` file list\n- updated: `controller.viewCompile(body, model, [headers], [partial], [cacheKey])` add a cache key\n- updated: `image.command(arg, value, [priority], [escape])` a `priority` argument can be `escape` when it contains `boolean` value\n- updated: `U.getExtension()` returns lower-case extensions\n- updated: `total.js/debug` watchs `/workflows` file\n- updated: file `/workflows` supports custom `options`, more in docs\n- updated: `Array.random()` algorithm (+70% faster than older)\n- updated: `RESTBuilder.file(name, filetarget, [filename])` can contain `filename` instead of buffer\n- updated: `U.streamer(beg, [end], onItem(item, index), [skip], [stream])` added a new argument `stream` for flushing buffer\n- updated: `ErrorBuilder.addTransform(name, callback(isResponse))` by adding new argument `isresponse`\n- updated: `sorting` (framework + NoSQL embedded), now supports `internationalization`\n- updated: `total.js/debugger` by adding a new option `options.watch = ['directory']`\n- updated: `U.streamer()` supports \"cancelation\", just return `false`\n- updated: CSS auto-prefixer, added: `repeating-linear-gradient`, `radial-gradient`, `repeating-radial-gradient` and removed `-o` prefix", "- fixed: (IMPORTANT) long messages in WebSocket\n- fixed: (IMPORTANT) `controller` param in schemas\n- fixed: moved executing of `MailMessage.callback()` to better place\n- fixed: mail auth when `options.user` and `options.password` are blank\n- fixed: JS/CSS/HTML blocks\n- fixed: `F.prototypes()`\n- fixed: `F.decrypt()` a problem with parsing JSON and date formats\n- fided: `debug.js` sometimes was created a problem with output informations", "- improved: Date formatting (+50%)\n- improved: NoSQL performance (around 60% in some cases)", "======= 2.7.0", "- added: __IMPORTANT__ new unit-testing mechanism\n- added: __IMPORTANT__ `F.prototypes(function(proto) {})` for extending all internal prototypes\n- added: `HttpFile` is set in `global` for extending of prototype\n- added: `file.move()` a new alias for `file.rename()`\n- added: `SchemaBuilderEntity.$controller(new_controller)`\n- added: `EMPTYCONTROLLER` is a global variable\n- added: new alias `NOSQL.set()` and `NOSQL.get()` for `NOSQL.meta()`\n- added: `RESTBuilder.file(name, filename, [buffer])` supports uploading files\n- added: `RESTBuilder.mobile()` adds `iPhone` phrase into the `User-Agent` header\n- added: `RESTBuilder.robot()` adds `Bot` phrase into the `User-Agent` header\n- added: a small protection for multipart data\n- added: a new global aliases `ROUTE()` --> `F.route()`, `FILE()` --> `F.file()` and `WEBSOCKET()` --> `F.websocket()`", "- updated: __IMPORTANT__ components (framework can render css/js from specific group)\n- updated: `F.cluster` each operation checks whether cluster is activated\n- updated: default IP to `0.0.0.0`\n- updated: `Date.prototype.format()` with `ddd` renders name of day with 2 capital letters", "- fixed: new schemas with defined callback `function($)`\n- fixed: loading of `config-test` file (added rewriting of existing values)\n- fixed: Total.js version in `debug.js`\n- fixed: cluster initialization", "- improved: `cors` in `F.restful()` and `F.restful2()`\n- improved: `auto-vendor-prefixes`\n- improved: parsing files from multipart data", "======= 2.6.2 (HOTFIX)", "- fixed: a critical bug with `debug.js`\n- fixed: `try/catch` block from parsing of WebSocket message", "======= 2.6.1 (HOTFIX)", "- fixed: timeout in `RESTBuilder` and `U.request()`\n- fixed: `F.merge()` a problem with `.js` or `.css` extension in some directory", "======= 2.6.0", "- added: `F.config['default-errorbuilder-status']` a default HTTP status for all error builders default `200`\n- added: `F.config['default-listenpath']` starts a UNIX socket server listening for connections on the given path\n- added: `F.listenpath` contains `default-listenpath` location\n- added: `F.custom(mode, http, request_prototype, response_prototype, options)` a new mode for overwriting default HTTP server\n- added: `schema.inherit([group], name)` can inherit all values from another schema\n- added: NoSQL synchronization for cluster (more in docs)\n- added: cache synchronization for cluster (more in docs)\n- added: `F.cluster` (more in docs)\n- added: Total.js `debug` script `require('total.js/debug')` instead of `debug.js` file\n- added: a support for `async` attribute when `<script async src=\"` tag is generating, e.g. `@{import('async default.js')}`", "- updated: `F.http(type, options)` supports `options.listenpath` for HTTP server (a direct shortcut for `default-listenpath`)\n- updated: `F.script` returns error if compilation fails\n- updated: `debug.js` supports `inspector`\n- updated: NoSQL embedded database sorting (increased read performance about 30%)\n- updated: RESTBuilder parsers JSON date string as `Date` object\n- updated: `favicon()` generates `<link rel=\"icon\"` instead of `<link rel=\"shortcut icon\"`", "- fixed: `controller.send()` bad declaration of `connection.id` for `id` and `blacklist` arguments\n- fixed: `totaljs --translate` problem with `node_modules` and `.git` directory\n- fixed: a waiting mode in `GETSCHEMA()`\n- fixed: cache `instance.cache()` in RESTBuilder\n- fixed: NoSQL filtering (critical)\n- fixed: a bug ImageMagick/GraphicsMagick when the path contains spaces (critical)\n- fixed: `controller.memorize()` didn't work (critical)\n- fixed: dynamic params when `controller.transfer()` is performed", "======= 2.5.0", "- added: a missing property for WebSocket controller `controller.mobile`\n- added: `EMIT()` alias for `F.emit()`\n- added: `ON()` alias for `F.on()`\n- added: `OFF()` alias for `F.removeListener(eventName, listener)` or `F.removeAllListeners([eventName])`\n- added: `controller.components()` adds script/css tag into the head\n- added: `@{components([group], [settings])}` renders all components together from selected group\n- added: a new alias `WAIT()` alias for `U.wait()`\n- added: `res.status(code)` for express middleware\n- added: `F.clearSchedule(id)` for removing existing schedules\n- added: a support for WebSocket compression\n- added: removing `.package` files from `tmp` directory\n- added: a new schema implementation (more in docs)\n- added: `F.restful2()` has simplified route mechanism (it doesn't use \"{id}\" param for insert(POST)/update(POST)/delete(DELETE) method with except \"GET\" method)\n- added: `res.binary(buffer, contentType, [type], [download], [headers])`\n- added: a new route flag `novalidate` (a prevention for Schema validation)\n- added: `U.upload(files, url, [callback], [cookies], [headers], [method], [timeout])` for multiple uploading files\n- added: `RESTBuilder.redirect(true/false)` enables/disables auto-redirect (default: enabled)\n- added: new schema aliases (`$QUERY()`, `$GET()`, `$WORKFLOW()`, '$TRANSFORM()' and `$OPERATION()`)\n- added: `allow-head` (default: false) adds `head` method into the each route automatically\n- added: `F.config['allow-defer']` enables deferring functions with `DEFER` keyword (default: false)\n- added: `DEFER` feature\n- added: `F.config['allow-debug']` starts a mini debugger\n- added: `res.image_nocache()` alternative to `F.responseImageWithoutCache`\n- added: `req.localize()` performs localization (executes `F.onLocale`)\n- added: `image.limit(type, value)` creates a memory/map/disk/etc. limitation for GM or IM\n- added: `default-image-consumption` for GM/IM memory limitation (default value `30%`)\n- added: `F.useSMTP(smtp, [options], [callback(err)])` rewrites current SMTP settings", "- updated: `F.http('debug/release/test', { debug: true })` can start a mini debugger\n- updated: `F.route()`, `F.websocket()` and `F.file()` --> now returns `FrameworkRoute` instance instead of `Framework` instance (more in docs)\n- updated: `F.load(debug, [types], [path])` supports a new type `service` which enables `F.on('service')`\n- updated: Components (now doesn't have to has `html` body)\n- updated: A component implementation can contain `exports.group = 'name';`\n- updated: framework loads all dependencies in order\n- updated: routes (web/websockets/files) can have an identifier in this form `F.route('/', ['id:custom_dentificator']);\n- updated: `UNINSTALL(type, url/id/fn)` supports new types `web`, `websocket` and `file`, e.g. `UNINSTALL('web', 'id:custom_identifier')`\n- updated: `U.request()`, added a new flag: `raw` (sends raw data)\n- updated: `F.schedule()` returns an identifier\n- updated: `U.clone()` supports `buffer` properties\n- updated: `setTimeout2(name, fn(param), timeout, [limit], [param])` added a new argument `limit` and `param`\n- updated: `F.script()` --> `now` argument (in the script body) is function `now()` which it still returns `new Date()`\n- updated: `F.script(body, value, callback(err, response, param), [param])` --> `param` argument is a helper\n- updated: middleware `next(false)` cancels calling of next middleware and controller\n- updated: `OPERATION(name, value, [callback(err, response, param)], [param])` added a new (helper) argument `param`\n- updated: Mail error handling (added Message instance)\n- updated: `U.request()` add a new flag `noredirect`\n- updated: `F.exists(req, res, [max], callback(next, filename, req, res))` added a new arguments into the callback `req` and `res`\n- updated: `F.memorize()` uses `themeName` as a part of the cache key\n- updated: `debug.js` (missing `startup` directory)", "- renamed: configuration `mail.address.from` for `mail-address-form`\n- renamed: configuration `mail.address.reply` for `mail-address-reply`\n- renamed: configuration `mail.address.copy` for `mail-address-copy`\n- renamed: configuration `mail.smtp` for `mail-smtp`\n- renamed: configuration `mail.smtp-options` for `mail-smtp-options`", "- fixed: config `static-accepts` (it didn't work)\n- fixed: routing with `upload` flag\n- fixed: workers timeout\n- fixed: modificators by George Okojie Davis\n- fixed: NoSQL comparing dates `equal` in `where` condition\n- fixed: a problem with `booting` packages if are used custom paths (by @harry-stot)\n- fixed: JavaScript compression\n- fixed: `allow-compile-style` for inline CSS in views", "- improved: events\n- improved: parsing data from requests\n- improved: mechanism of components\n- improved: performance\n- improved: responding\n- improved: mail attachments", "======= 2.4.0", "- added: `components` more in docs\n- added: `X-Powered-By` header again with option to change/remove it in the framework config `default-xpoweredby : Total.js`\n- added: `UPTODATE(type, url, [options], interval, [callback(err)])` more in docs\n- added: `F.on('uptodate', function(type, name) {})` new event for up-to-date dependencies\n- added: `F.stats.other.mail` with a count of sent emails\n- added: `F.stats.response.errorBuilder` with count of sent ErrorBuilders\n- added: `F.stats.response.image` with count of processed images via GM or IM\n- added: `F.stats.request.schema` with count of request to SchemaBuilder\n- added: `String.prototype.parseTerminal([fields], fn(values, index, count, realIndex), [skipLines], [takeLines])`\n- added: `TRACE(message, [name], [url], [ip])` is an alias for `F.trace()`\n- added: `F.config['trace-console']` (default: `true`) shows tracing on the console\n- added: `F.convert(name, type/function(val))` registers a new convertor (convertors uses QueryParser (GET/POST))\n- added: `F.convert(obj)` performs convertor for an object\n- added: `F.download(url, filename, [callback])` a new alias for `F.snapshot()`\n- added: `$$$([group], name)` for `GETSCHEMA([group], name)`\n- added: configuration files supports options for all dependencies `module#mymodulename (Object) : { name: 'A custom options for dependency' }`\n- added: `U.chunker()` added a new property `chunker.pages` with count of all stored pages\n- added: `U.chunker()` added a new property `chunker.count` with count of all stored items\n- added: `NEWOPERATION(name, fn(error, callback(response), value))` - registers a new operation (same as schemas)\n- added: `OPERATION('name', function(err, response))` - executes an operation (same as schemas)\n- added: `.flac` file extensions\n- added: a new method for `MailMessage` object `message.unsubscribe('your URL or email address')`", "- updated: new error message `The field \"@\" is invalid.`\n- updated: `NOSQL().insert(doc, [unique])`\n- updated: `quicksort` algorithm has been replaced for `shellsort` (increased performance of sorting about 10-15%)\n- updated: `NOSQL().counter.monthly(true, ...)` shows all stats by ID\n- updated: `NOSQL().counter.yearly(true, ...)` shows all stats by ID\n- updated: `dependencies` supports up-to-date features e.g. `module (1 day) : https://......js`\n- updated: `F.findConnections([path])` a `path` argument is optional\n- updated: `U.streamer(beg, [end], function, [skip])` add a new argument `skip`\n- updated: deprecated methods in Node.js v7\n- updated: `String.parseJSON([date])` added `date` argument (date fields will be converted to `datetime`)\n- updated: `F.script()` can compile code to function e.g.: `F.script('next(a + b)')` returns a compiled function\n- updated: `String.captialize([onlyFirst])` add a new argument `onlyFirst`\n- updated: `F.onParseQuery(value, req)` add a new argument `req`\n- updated: `F.onParseXML(value, req)` add a new argument `req`\n- updated: `F.onParseJSON(value, req)` add a new argument `req`\n- updated: `RESTBuilder.url()` without argument returns a current URL\n- updated: `RESTBuilder.exec(function(err, value, response))` when the `error` exists the `value` is still `EMPTYOBJECT`\n- updated: addded a new argument `replacer` to `controller.send(message, [id], [blacklist], [replacer])` and `client.send(message, [raw], [replacer])`", "- removed: behaviours\n- removed: restrictions\n- removed: `TransformBuilder`\n- removed: `F.config['allow-compatibility']` (not used)\n- removed: `controller.date()` method has been useless\n- removed: dynamic view compilation through `.view()` method\n- removed: `contorller.proxy()` in WebSocket controller", "- fixed: JS minificator\n- fixed: global alias `I` for isomorphic code\n- fixed: streaming files in `debug` mode (removed cache)\n- fixed: (critical) a bug with authorization in WebSocket\n- fixed: `nosql_builder.join()` a problem with using `nosql_builder.first()` by @yexing (Xing Ye)\n- fixed: `String.parseInt2()` - a possible NaN value\n- fixed: `String.parseFloat2()` - a possible NaN value\n- fixed: `F.snapshot()`\n- fixed: HTML compression (a fixed problem with HTML comments)\n- fixed: restarting framework (missing cleaning of `F.temporary`)\n- fixed: `U.isDate()` a problem with older dates than 1970, reported by @docgit", "- improved: code\n- improved: memory consumption for static files\n- improved: CSS compression\n- improved: CPU and memory consumption\n- improved: performance\n- improved: updating of `F.datetime`\n- improved: `uninstall` dependencies\n- improved: installing 3rd-party dependencies (framework compares same contents)", "======= 2.3.0", "- added: support for `/workflows` file (more in documentation)\n- added: `ShcemaBuilderEntity.$exec(name, callback)` (more in documentation)\n- added: `SchemaBuilder` supports new types `enum` and `keyvalue`\n- added: `controller.$exec(name, [options], [callback])` (more in documentation)\n- added: a new argument `description` to each SchemaBuilder `set` + `add` method e.g. `.setSave()`, `.addWorkflow()`, etc..\n- added: `SchemaBuilder.meta` contains all registered handlers with their descriptions\n- added: a property `controller.schema`\n- added: `F.viewCompile(body, [model], [layout], [repository], [language])` - dynamic views\n- added: `controller.viewCompile(body, [model], [headers], [partial])` - dynamic views\n- added: `{viewCompile(body, [model])}` - dynamic views\n- added: `Controller` is a global variable for extending prototype\n- added: `F.validators` with Regular Expressions\n- added: View Engine supports `@{continue}` and `@{break}` command for looping\n- added: `URLBuilder.make(fn)`\n- added: `NOSQLMEMORY(dbName, [viewName])` enables in-memory database collection\n- added: NoSQL `nosql.upsert(doc)` inserts a new document where document doesn't exist in DB\n- added: NoSQL `nosql.release()` for releasing of in-memory DB (framework clears unused in-memory databases automatically)\n- added: NoSQL `nosql.scalar(type, dbName, [view])` performs scalar operation by type: `sum`, `min`, `max`, `avg`, `count` or `group`\n- added: NoSQL `nosql.binary.all(callback)` browses all stored files\n- added: NoSQL `nosql.binary.clear(callback)`removes all stored files\n- added: NoSQL `DatabaseBuilder.random()`\n- added: NoSQL `DatabaseBuilder.join(field, dbName, [view])` returns `DatabaseBuilder` with updated `.where(field_JoinedDB, field_currentdb)` method (it supports `.fields()` too)\n- added: NoSQL `DatabaseBuilder.join()` supports scalar operation too, e.g. `nosql.join(...).scalar('count')`\n- added: NoSQL `DatabaseBuilder.scalar(type, [field])` - types: `sum`, `min`, `max`, `avg`, `count` or `group`\n- added: NoSQL `DatabaseBuilder.month(field, [operator], value)` filters `Date` fields according its month number\n- added: NoSQL `DatabaseBuilder.year(field, [operator], value)` filters `Date` fields according its year number\n- added: NoSQL `DatabaseBuilder.day(field, [operator], value)` filters `Date` fields according its day number\n- added: NoSQL events (documents): `insert`, `update`, `modify` and `remove`\n- added: NoSQL events (binary): `insert`, `remove` and `clear`\n- added: NoSQL events (counter): `hit`, `remove` and `clear`\n- added: a new alias `NOBIN(dbName)` witch it returns `NOSQL(dbName).binary` (a binary instance)\n- added: a new alias `NOCOUNTER(dbName)` witch it returns `NOSQL(dbName).counter` (a counter instance)\n- added: `F.kill(signal)` for killing an instance of the framework\n- added: `I` alias for `isomorphic code on server-side and client-side together by hhhaker6@gmail.com <https://github.com/Creeplays>\n- added: `F.script(body, value, callback(err, value))` evaluates script securly in safe scope (more in documentation)\n- added: new alias `SCRIPT()` for `F.script()`\n- added: `HttpFile.rename(filename, [callback(err)])` moves file to another directory", "- updated: `F.on('exit', function(signal) {})` added a signal code\n- updated: SchemaBuilderEntity contains new argument `controller`, e.g. `.setSave(function(error, model, options, callback, controller) { ..`\n- updated: removed all validators of email addresses from FrameworkMail\n- updated: `GETSCHEMA([group], name, [callback(err, schema)])` can wait for a schema\n- updated: `F.localize()` supports modificators as `static` type\n- updated: `F.modify()` supports a new type `static`, it's group of `.html`, `.txt` and `.md` files\n- updated: `U.trim(obj, [clean])` supports a new argument `clean` (default `false`) and when it's `true` and a value is `''` then it sets the value to `undefined`\n- updated: `nosql.update(docToUpdate, [docToInsert])` when the document for updating doesn't exist then database performs insert\n- updated: `nosql.modify(docToUpdate, [docToInsert])` when the document for updating doesn't exist then database performs insert\n- updated: `nosql.binary` stores a creation date as meta info", "- fixed: Image.stream()\n- fixed: global variable `Image` (in a single library)\n- fixed: JavaScript compressor (problem with Regular Expressions)\n- fixed: custom paths in `F.model()` and `F.source()`\n- fixed: NoSQL removing documents (problem with different filters in one queue)\n- fixed: fix view compiler error message\n- fixed: `String.prototype.capitalize`", "- removed: `nosql` doesn't support cache (`DatabaseBuilder.cache` is obsolete)\n- removed: `F.refresh()` the method was useless", "- replaced: `Array.randomize()` for `Array.random()`", "- improved: code", "======= 2.2.0", "- added: `controller.proxy2(url, [callback], [headers], [timeout])` creates a proxy between current request and new URL\n- added: `Image.watermark(filename, [x], [y], [width], [height])` creates a watermark\n- added: hidden hack `res.noCompress = true` disables compilation of `.js` or `.css`\n- added: `RESTBuilder` for creating REST requests (more in docs)\n- added: new config item `allow-cache-snapshot` - to prevent cache when the framework is restarted", "- updated: `SINGLETON(name, [def = {}])` about `def` argument\n- updated: `debug.js` adds timestamps\n- updated: `F.redirect()` can contain a relative URL of file\n- updated: NoSQL embedded parser, dates are parsed as date object\n- updated: `Pagination.next()`, `Pagination.prev()`, `Pagination.last()` and `Pagination.first()` supports new arguments `.html([link_inner_html], [class_name])`\n- updated: `F.worker()` supports packages `F.worker('@eshop/myworker-script')`\n- updated: `FrameworkImage` when the instance contains no command then `.minify()` method is performed automatically for preventing of empty response\n- updated: `F.config['static-accepts']` removed dots from all extensions", "- improved: `@{href(key, value)}` performance\n- improved: Total Package Manager `$ tpm --help`\n- improved: FrameworkImage command building", "- fixed: (critical) NoSQL `nosql.modify()` and problem with updating `undefined` values\n- fixed: (critical) security with GM and IM --> 10000x thanks for Luis Figueiredo <luisf@hexasoftware.com>\n- fixed: `Image.stream()` and `Image.pipe()`", "- renamed: `F.onLocate` renamed to __`F.onLocale`__", "======= 2.1.0", "- added: `F.sitemap_add(string)` for adding entries to sitemap by Martin Smola <https://github.com/molda>\n- added: SchemaBuilderEntity `schema.addHook(name, fn(error, model, options, callback))`\n- added: SchemaBuilderEntity `schema.hook(name, model, [helper], callback)`\n- added: `controller.$hook(name, [helper], callback)`\n- added: `String.parseInt2()` the method searchs number and converts it to integer\n- added: `String.parseFloat2()` the method searchs number and converts it to float\n- added: `@{title2('this content will be added to end of current title')}`\n- added: `String.parseInt2()` the method searchs number and converts it to integer\n- added: `String.parseFloat2()` the method searchs number and converts it to float\n- added: `@{absolute(url, [hostname])}` for importing links with absolute URL by George Okojie Davis <https://github.com/binarygeotech>\n- added: `sitemap_replace(name, title, url)` can change sitemap `title` and `url` onetime\n- added: new JavaScript minificator algorithm because of Douglas Crockford \"Good, not Evil\"\n- added: NoSQL supports counter for e.g. views or downloads, etc., more in documentation\n- added: new routing mechanism `F.mmr(url, action)` for streaming `multipart/x-mixed-replace` types (client-->server)\n- added: `controller.mmr(filename, [stream], callback)` for streaming `multipart/x-mixed-replace` (server-->client)\n- added: `setTimeout2(key, fn, timeout)` resets old and creates a new `setTimeout` according to the `key`\n- added: `clearTimeou2(key)` resets existing timeout\n- added: `dnscache` into the `controller.pipe()` and `F.responsePipe()`\n- added: `CREATE([group], name)` the methods create an empty object according to the schema\n- added: `F.group(flags, fn)` for extending routes (web, websocket, file) flags\n- added: `Number.prototype.filesize([decimals], [type])` formatting file sizes\n- added: `binary` importing CSV `-csv`\n- added: `controller.autodestroy([callback])` only for websocket", "- updated: `framework.view()`, `controller.view()` and `@{view()}` supports `=theme/viewname`\n- updated: sitemap routing supports localization\n- updated: `F.cache.fn(name, fnCache, fnCallback(value, isFromCache))` - added argument `isFromCache`\n- updated: `F.use(name, url, types, [first])` - `first` (default: `false`) argument adds a new middleware to the beginning of a route middleware\n- updated: `String.toSearch()` - removes duplicates characters + better performance\n- updated: `String.decode()` - improves decoding by Tom Spaccialbelli <https://github.com/harry-stot>", "- fixed: (critical) NoSQL views\n- fixed: (critical) view compilation in release mode (problem with just-in-time rendering)\n- fixed: (critical) `F.eval()`\n- fixed: (critical) parsing Date instance as Date instance in SchemaBuilder\n- fixed: `F.resize()` additional path `~`\n- fixed: `controller.memorize()` threw a timeout when the action contains some error in the memorize scope\n- fixed: `F.sitemap()` fixed problem with `me` argument\n- fixed: SchemaBuilderEntity preparing and validation\n- fixed: QuickSort algorithm (problem with dates)\n- fixed: `TRY()` scope\n- fixed: problem with resources in views\n- fixed: CSS compressor\n- fixed: CORS\n- fixed: problem with SUCCESS() and async schemas\n- fixed: killing the process\n- fixed: HTML compressor in views", "======= 2.0.1", "- added: binary supports webserver `totaljs 8000` starts webserver on 8000 port and the current directory will be a public directory\n- added: configuration supports new subtype (`env` or `environment`) for binding values from `process.env`\n- added: `SchemaBuilderEntity.$next(type, [name], helper)` --> adds a new operation (type: `workflow`, `transform`, `operation`, `save`, `read`, `query`, `remove`) to async list as next step\n- added: `SchemaBuilderEntity.$push(type, [name], helper)` --> adds a new operation (type: `workflow`, `transform`, `operation`, `save`, `read`, `query`, `remove`) to async list as last step\n- added: `SchemaBuilderEntity.$index(index)` can changed `obj.$async()` index (the index can be string e.g. `+1` or `-1`)\n- added: `SchemaBuilderEntity.$callback(fn)` can changed `obj.$async()` callback\n- added: `SchemaBuilderEntity.$repository(name, [value])` can get / set temporary value", "- added: `SchemaBuilderEntity.$output()` sets the current `callback(value)` as output/result for `obj.$async(function(err, output))`", "- updated: when the config contains `directory-temp` with empty value then the framework uses system temporary directory\n- updated: `U.reduce()` supports array", "- fixed: binary `totaljs`, fixed problem with creating localized texts\n- fixed: `F.responseFile()` problem with cached filename, extension was broken when the framework reads the file from cache\n- fixed: preparing values with subtype for array in SchemaBuilder\n- fixed: generation UID\n- fixed: problem with uninstalling middleware\n- fixed: email validation, a problem with e.g. `blabla@somedomain.business` by @VarunBatraIT", "- improved: view engine rendering\n- improved: view engine memory consumption", "======= 2.0.0", "- added: new NoSQL version v4.0.0 is fully optimized for total.js\n- added: `controller.invalid([status])` creates the ErrorBuilder instance and it responds in the next tick\n- added: `controller.sitemap_url([id])` returns an URL from the sitemap\n- added: `controller.sitemap_name([id])` returns a name/title from the sitemap\n- added: `controller.sitemap_change(id, property, newvalue)` can change a current value in the sitemap\n- added: `controller.sitemap_navigation([parent], [langauge])` can get list of all items according to the parent\n- added: `@{sitemap_url([id], [arg1], [arg2], [argN])}` returns an URL from the sitemap\n- added: `@{sitemap_name([id], [arg1], [arg2], [argN])}` returns a name/title from the sitemap\n- added: `@{sitemap_change(id, property, newvalue)}` can change a current value in the sitemap\n- added: `@{sitemap_navigation([parent], [language])` can get list of all items according to the parent\n- added: `/startup/` all scripts in this directory are executed only one (then are renamed automatically)\n- added: `F.route()` supports a new flag: `cors` (creates a cors route) and `credentials` (enables cookies for cors)\n- added: `ErrorBuilder.plain()` returns all errors as a simple string\n- added: `Array.findItem()` alias to `Array.find()`\n- added: `Number.async(fn(index, next), callback)` for asynchronous operations\n- added: `UID()` for generating unique identifiers (contains minimum 18 chars)\n- added: `F.restart()` for restarting app\n- added: `F.on('restart')`\n- added: quicksort algorithm for sorting arrays\n- added: `Array.quicksort(property_name, [asc], [maxlength])` for sorting arrays\n- added: `String.removeTags()` by @harry-stot\n- added: F.nosql(name) + NOSQL(name) --> alias for NoSQL embedded database (it can be used with e.g. SQL Agent)\n- added: modificators can handle `INSTALL('view', ...)`\n- added: `String.isPhone()` for phone number validation\n- added: `String.isUID()` for UID() validation\n- added: `String.isZIP()`\n- added: `Pagination.html(max, format)` returns `String`\n- added: `Pagination.json(max, format)` returns `String`\n- added: new schemabuilder types `Email` (string, maxlength 120), `Phone` (string, maxlength 20), `Zip` (string, maxlength 10), `Capitalize` (string), `Lowerize` (string), `Upperize` (string), `UID` (string, minlength 18, maxlength 20), `Url` (string, maxlength 500), `JSON` (string)\n- added: `SchemaBuilderEntity.fields` and it contains all field names in array.\n- added: `Mail.send(smtp, options, messages, [callback])` messages must be array\n- added: `Mail.send2(messages, [callback])` sends messages according to the framework configuration\n- added: `Mail.try(smtp, options, callback)` tries to open a SMTP\n- added: `F.datetime` contains current datetime and each 1 minute is the value increased\n- added: `F.stats.other.restart` contains a new property with count of restarting\n- added: `F.config.trace` for enable/disable tracing, `Boolean`, in a debug mode: `true`, release mode: `false`\n- added: `F.trace(message, [name], [uri], [ip])`\n- added: `controller.trace(message)`\n- added: `req.split` contains splitted url\n- added: `F.touch(url/req)` for clearing internal cache of cached static files (it works only in release mode)\n- added: `F.path.exists(path, callback(exist, size, isFile))` for check of existing file\n- added: `U.chunker(name, [max])` creates the chunker (for streaming some items)\n- added: `F.worker2(name, [args], [callback], [timeout])`\n- added: `SchemaBuilderEntity.allow('fieldname1', 'fieldnameN')` - allows other keys out of defined fields\n- added: `global.EMPTYOBJECT`\n- added: `global.EMPTYARRAY`\n- added: `global.SINGLETON(name)` returns a singleton object instance\n- added: `controller.referrer` returns a value from `req.headers['referer']`\n- added: `controller.author(value)` can change `<meta name=\"author\"`\n- added: `@{author(value)}` can change `<meta name=\"author\"`\n- added: view engine supports looping with objects `@{foreach m in model} key: @{m.key} and value: @{m.value} @{end}`", "- updated: subdomain routing supports wildcard routing `F.route('[*]/', 'homepage')` (`F.websocket()` is supported too)\n- updated: `F.route(url, ...)` - `url`can be String Array with multiple relative paths by @Harry-Stot\n- updated: `F.file()` supports flags instead of middleware and the flags supports extensions `['.jpg', '.png']`. The `name` argument has been removed.\n- updated: `F.localize()` supports flags and the `name` argument has been removed\n- updated: `F.sitemap()` returns object with a new field: `wildcard: {Boolean}`\n- updated: `F.problem()`, `F.change()`, `controller.problem()` and `controller.change()` write logs to the file\n- updated: `F.mail()` and `controller.mail()` subject is translated according to the language\n- updated: `F.file(fnValidation/relative_path, fnExecute, [flags])` the file routing is completely changed\n- updated: `export.booting` can contain `root` attribute for `package` applications\n- updated: `Array.orderBy()` added quicksort algorithm\n- updated: `Date.format()` supports day names `ddd` (short) and `dddd` (full)\n- updated: `String.removeDiacritics()` supports multiple languages (by @Harry-Slot)\n- updated: (IMPORTANT) `U.getExtension(filename)` --> returns extension without `.` dot\n- updated: (IMPORTANT) `F.resize(url, action(image), [flags])` new resize routing\n- updated: `F.resize()` flags can contain http/https `path` e.g. `F.resize('/img/*.*', (image) => image.minify(), ['https://www.totaljs.com/img/']);`\n- updated: `U.GUID()` supports better charset by Guy Fraser\n- updated: `Date.add(number)` supports number increase/decrease in milliseconds\n- updated: `U.send(name, stream, url, callback, [cookies], [headers], [method], [timeout])` supports cookies and timeout\n- updated: `U.request()` supports a new flag `< 200` (kB), it means that the method stores a content with maxixmum size 200 kB.\n- updated: `ErrorBuilder` instance contains a new property `instance.unexpected` when is `instance.push()` a classic Error's instance.\n- updated: configuration files + resources support types like String, Number, Array, Date, etc. via `key (type) : value`\n- updated: `F.use(name, [url], [types])` - now supports new attributes `url`, and `types`", "- fixed: `Websocket.destroy()`\n- fixed: Too many open files with `F.log()` and `F.logger()`\n- fixed: `String.isJSON()` the problem with `\\n` character\n- fixed: `FrameworkImage.save()` problem with streams\n- fixed: `CLEANUP(stream)` method\n- fixed: `controller.memorize()` problem with `controller.content()`\n- fixed: `multipart/form-data` parser\n- fixed: `Array.async()` without arguments\n- fixed: view inline helpers\n- fixed: `FrameworkImage.save()` doens't work when it doesn't contain any operation\n- fixed: Windows paths\n- fixed: problem with `websocket.destroy()`\n- fixed: `F.cors()`\n- fixed: WebSocket initialization (critical)\n- fixed: Mail sender (problem with ZOHO SMTP)\n- fixed: `Number.add()` problem with percentage\n- fixed: `U.isDate()` by Guy Fraser\n- fixed: `U.parseXML` problem with `CDATA`\n- fixed: `U.join()` problem with Windows path by Martin Smola\n- fixed: uploading files (problem with unexpected closed requests)\n- fixed: `F.assert()` a problem with external URL address", "- renamed: event `route-add` to `route`\n- renamed: `F.versionNode` to `F.version_node`", "- removed: (IMPORTANT) `X-Powered-By` header\n- removed: `SCHEMA()`\n- removed: composer from `SchemaBuilderEntity`\n- removed: rules from `SchemaBuilderEntity`\n- removed: obsolete code\n- removed: `controller.async()`\n- removed: `framework.async()`\n- removed: `Utils.validate()`\n- removed: `Utils.isEmail()`\n- removed: `Utils.isURL()`\n- removed: `Utils.isValid()`\n- removed: `Utils.isNullOrEmpty()`\n- removed: `controller.global` property by Guy Fraser (a problem with referrencing)\n- removed: `controller.database()`, use `F.database()`\n- removed: `controller.functions()`\n- removed: `controller.models()`", "- improved: Controller initialization by Guy Fraser\n- improved: SMTP sender\n- improved: redirecting\n- improved: Array.orderBy(), added quicksort algorithm\n- improved: ErrorBuilder\n- improved: `WebSocket.send()` for JSON communication\n- improved: code (a lot)\n- improved: preparing `SchemaBuilderEntity`\n- improved: performance\n- improved: a lot of code by Guy Fraser", "======= 1.9.7", "- added: `F.web()` --> alias to F.route()\n- added: `F.cors(url, flags, credentials)`\n- added: `config['default-response-maxage']`, default value `11111111`\n- added: `U.get(obj, path)` reads a value from `obj` by path\n- added: `U.set(obj, path, value)` sets a value into `obj` by path\n- added: (IMPORTANT) `config['default-root']` can replace root relative path\n- added: `FrameworkImage` --> `instance.make(function(image) {})`\n- added: `FrameworkImage` supports middleware `FrameworkImage.middleware(extension, fn)`\n- added: `controller.$get([helper], callback)` or alias `controller.$read([helper], callback)` - schema must be defined in the route\n- added: `controller.$remove([helper], callback)` - schema must be defined in the route\n- added: `controller.$save([helper], callback)` - schema must be defined in the route\n- added: `controller.$query([helper], callback)` - schema must be defined in the route\n- added: `controller.$transform(name, [helper], callback)` - schema must be defined in the route\n- added: `controller.$workflow([name, [helper], callback)` - schema must be defined in the route\n- added: `controller.$operation(name, [helper], callback)` - schema must be defined in the route\n- added: `controller.$async(callback, [index])` - schema must be defined in the route\n- added: new `F.route()` flag `binary` (works only with `raw` flag)\n- added: `U.ls2()` --> returns additional information about files (stat Object);\n- added: `Pagination` is a global variable\n- added: `SchemaBuilder.workflow2(name, options, callback)` skips preparing and validation\n- added: `SchemaBuilder.transform2(name, options, callback)` skips preparing and validation\n- added: `SchemaBuilder.operation2(name, options, callback)` skips preparing and validation\n- added: `ErrorBuilder.exception(message)` - adds a new exception message\n- added: `F.findConnection()` finds a websocket connection\n- added: `F.findConnections()` finds websocket connections", "- updated: (IMPORTANT) Array.async([NEW: threadCount (Number)], [callback]) supports `threads`\n- updated: (IMPORTANT) Array.wait(onItem(item, index), [callback], [threadCount]) supports `threads`\n- updated: (IMPORTANT) U.streamer(beg, [end], callback) --> supports \"end\" delimiter\n- updated: Date.format(format, [resource_name]) supports name of months via `MMM` (short) and `MMMM` (full)\n- updated: Resources support months e.g. `January : Január`\n- updated: `F.merge()` supports directories, e.g. `F.merge('app.js', '/js/*.js')`\n- updated: NoSQL embeddded version\n- updated: `U.ls()` --> [filter] can be `string` or `RegExp`\n- updated: `@{meta(title, [description], [keywords], [image])}` and `@{keywords(value)}` keywords can be String Array\n- updated: `@{section name}` can be used in the view more times\n- updated: `U.request()` flags supports `number` for timeout and encoding `utf8`, `ascii`, etc.\n- updated: `F.restfull()` each action support SchemaBuilder", "- fixed: (IMPORTANT) Expires headers - problem with Russian timezone, reported by [Андрей Владимирович](https://github.com/anddesigner)\n- fixed: (IMPORTANT) SchemaBuilder validation\n- fixed: (IMPORTANT) view caching\n- fixed: (IMPORTANT) U.keywords()\n- fixed: @{checkbox} value binding\n- fixed: dynamic views translator caching\n- fixed: URL search string in `F.redirect()` (doesn't work on local relative address)\n- fixed: binary / executable for Windows\n- fixed: SUCCESS()\n- fixed: Schema Validation is performed after F.onAuthorize().\n- fixed: checking of maximum request length\n- fixed: regexp routing\n- fixed: F.restrictions.allow()\n- fixed: `U.request()` and fixed `head` method, callback returns headers when is `head` method used\n- fixed: Pagination by DusanDragula\n- fixed: View inline helpers - reported by [Андрей Владимирович](https://github.com/anddesigner)\n- fixed: `Array.findIndex` - reported by [Liao San-Kai](https://github.com/liaosankai)\n- fixed: `WebSocket.send()` problem with `[id]` and `[blacklist]`", "- improved: performance in `Expires Header`", "======= 1.9.6", "- added: MailMessage.manually() and removes auto-sending mail --> works only with `F.mail()` and `controller.Mail()`.\n- added: view engine supports now `@{'route-to-static-file.jpg'}`\n- added: `U.clone(obj, [skip])`\n- added: `U.parseTheme(path)` --> parses theme name\n- added: `@{href}` or `@{href(obj)}` or `@{href(key, value)}` --> query string manipulation (more in documentation)\n- added: `.jsx` content-type\n- added: `robot` flag into the routing (for search engines)\n- added: property `req.robot`\n- added: property `controller.robot`\n- added: property `controller.mobile`\n- added: support for default theme name, e.g. `=?/index` (the framework replaces `?` for `default-theme`)\n- added: String.localeCompare2(value) --> same as localeCompare() but this method works with diacritics\n- added: F.register(filename); --> the methods registers new e.g. resource (it solves the problem with resources in packages)", "- updated: (IMPORTANT) controller.isSecure was renamed to controller.secured\n- updated: (IMPORTANT) req.isSecure was renamed to req.secured\n- updated: (IMPORTANT) Array.wait(onItem, onCallback, [NEW: threadCount (Number) or removeItemFromArray (Boolean)]) supports `threads`\n- updated: `F.mail()` supports themes with view nema like this `=default/someview'`\n- updated: `@{import()}` supports movies and images\n- updated: `@{import()}` can contain schema name in the path like this `=YOURTHEME/somefile.js`\n- updated: `F.route('/', '=themeName/viewname')` supports inline themes\n- updated: `F.resize()` added new options parameter --> `direction` (top, center or bottom)\n- updated: SUCCESS(), now supports function as first argument and the method returns wrapped function too", "- fixed: problem with views path (`./some/path/in/hdd/` routed view anywhere)\n- fixed: static file routing (`@{import()}`, `@{routeScript}`, etc..)\n- fixed: miss `Sec-WebSocket-Protocol` by Liao San-Kai\n- fixed: `MailMessage.send()` --> `options` argument is optional\n- fixed: problem with UTF8 in U.request() by Ivan Marchukov\n- fixed: WebSocket parser\n- fixed: WebSocket closing message (problem with UTF8)\n- fixed: U.getExtension()\n- fixed: problem with WebSocket `destroy`\n- fixed: sync2() doesn't work\n- fixed: problem with themes in controller.memorize()\n- fixed: problem with timeout in controller.memorize()\n- fixed: fixed unitialized memory block in `mail` (by ChALkeR)\n- fixed: problem with static files (directories with extensions)", "- removed: all `controller.current...()` methods\n- removed: all `@{current...()}` methods\n- removed: (IMPORTANT) `framework.fs`\n- removed: (IMPORTANT) `controller.fs`", "- improved: (IMPORTANT) SchemaBuilder by Ivan Marchukov\n- improved: (IMPORTANT) ViewEngine performance about 15%\n- improved: request cookie parsing", "======= 1.9.5", "I had to skip v1.9.4 version because of NPM (my mistake).", "- added: (IMPORTANT) new feature: THEMES\n- added: `@{theme}` --> return String\n- added: `F.onTheme` delegate\n- added: `controller.theme(theme_name)` --> select theme;\n- added: `config['default-theme']`\n- added: `U.keywords(content, [forSearch], [alternative(true|false|soundex)], [max_count(200)], [max_length(20)], [min_length(2)]);`\n- added: `String.prototype.keywords([forSearch], [alternative(true|false|soundex)], [max_count(200)], [max_length(20)], [min_length(2)])`\n- added: `String.prototype.soundex()`\n- added: `F.wait(name, [enable])` the server waits for pending task and it responds via 503 status code\n- added: `U.parseQuery()` and `String.parseQuery()`\n- added: `U.join(path1, path2, path3)`\n- added: `U.getName(path)`\n- added: `F.on('error400')`\n- added: `F.on('error401')`\n- added: `F.on('error403')`\n- added: `F.on('error404')`\n- added: `F.on('error408')`\n- added: `F.on('error431')`", "- updated: (IMPORTANT) F.onAuthorization() was renamed to F.onAuthorize()\n- updated: `Date.format()` supports `w` and `ww` for week number\n- updated: `Date.add()` supports `w`, `ww`, `week`, `weeks`\n- updated: MailMessage supports display name `mail.from('Name <vali@demail>');`\n- updated: MailMessage supports display name `mail.to('Name <vali@demail>');`\n- updated: MailMessage supports display name `mail.to(email, [name], [clear]);`\n- updated: MailMessage supports display name `mail.cc('Name <vali@demail>');`\n- updated: MailMessage supports display name `mail.cc(email, [name], [clear]);`\n- updated: U.resolve(url, [callback]) --> `callback` is optional", "- fixed: HTTP cache for HTML 5 offline manifest files\n- fixed: async() error handling\n- fixed: NoSQL embedded paths\n- fixed: problem with empty SMTP options\n- fixed: ErrorBuilder default transformation to JSON\n- fixed: Error handling\n- fixed: SchemaBuilder request auto-validation\n- fixed: String.isJSON()\n- fixed: F.responsePipe() --> problem with transmitted headers\n- fixed: evaluating of @{helpers.helper_name()}\n- fixed: HTML minification of UTF8 characters\n- fixed: U.isEqual()\n- fixed: FrameworkImage.save() in Windows by LiaoTzukai\n- fixed: SchemaBuilder prefix by Dušan Dragula", "- improved performance of the response\n- improved total performance\n- improved view engine performance", "======= 1.9.3", "- added: (IMPORTANT) merging supports BLOCKS (.js,.css), e.g. F.merge('merge.js', 'fileA.js#management,common', 'fileB.js#management')\n- added: (IMPORTANT) a route with schema binding can contain filter e.g. `*Schema#update` or `*Group/Schema#create` --> the framework validates only fields by filter\n- added: TRANSFORM([transform], obj)\n- added: NEWTRANSFORM(name, fn, [isDefault]) --> alias for TransformBuilder.addTransform()\n- added: packages can be stored as directories (recommended for debug mode only)\n- added: F.localize(name, url, [middleware], [options], [minify]) --> minify argument\n- added: email supports calendar (.ics) request sending\n- added: SchemaBuilderEntity.make(function(schema))\n- added: F.install() supports packages mapping\n- added: Support for unicode routing\n- added: Packages can be loaded in framework structure (/controllers/, /modules/) `exports.booting = true`\n- added: route flags can contains object --> the object is an additional options for middleware\n- added: Utils.btoa(str) --> returns base64\n- added: Utils.atob(str) --> returns binary\n- added: global.TRY(fnScope, [fnError]) --> creates safe scope (more in documentation)\n- added: Utils.getExtension(filename)\n- added: @{head} can be imported as @{import('head')}\n- added: @{meta} can be imported as @{import('meta')}\n- added: controller.cookie('KEY') --> for reading\n- added: controller.cookie('KEY', 'VALUE', expire, [options]) --> for writting\n- added: framework.onParseQuery(function(value)) --> for parsing values from the requests\n- added: framework.onParseXML(function(value)) --> for parsing values from the requests\n- added: framework.onParseJSON(function(value)) --> for parsing values from the requests", "- updated: (IMPORTANT) F.onValidation() was renamed to F.onValidate()\n- updated: (IMPORTANT) SchemaBuilderEntity.onValidation() was renamed to SchemaBuilderEntity.onValidate()\n- updated: (IMPORTANT) SchemaBuilderEntity.setValidation() was renamed to SchemaBuilderEntity.setValidate()\n- updated: CSS compressor removes comments\n- updated: F.restrictions.allow('IP') --> does not have to be full IP\n- updated: F.restrictions.disallow('IP') --> does not have to be full IP\n- updated: String.startsWith() and String.endsWith() according to ES6 but with the backward compatibility\n- updated: String.parseDate() supports JSON format and classic date serialization\n- updated: U.request() --> response always returns string\n- updated: debug.js --> now watchs packages", "- fixed: framework starting path (fixed problem with PM2 module)\n- fixed: controller.memorize() - prevention for multiple requests\n- fixed: routing (POST request without content-type is considered as `application/x-www-form-urlencoded`)\n- fixed: sync2()\n- fixed: U.minifyHTML() - now compresses JS and CSS in HTML\n- fixed: Async.cancel()\n- fixed: email attachments\n- fixed: throwing error in global middleware\n- fixed: Pagination.last()\n- fixed: CSS auto-vendor-prefixes\n- fixed: `tpm` binary (bug in creating packages on Windows)\n- fixed: controller generators\n- fixed: F.install() --> problem with names via URL import\n- fixed: F.map() on Windows (problem with paths)\n- fixed: HTML compression in views\n- fixed: U.Async() object (problem with waitingFor)\n- fixed: F.map(), problem in Windows\n- fixed: CLEANUP(stream, [callback]);\n- fixed: HTTP CACHE", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/blocks", "======= 1.9.2 (HOTFIX)", "- added: support for node +v4.0.0", "- updated: F.load(.., ..., [path]) path arguments supports '..' for parent directory\n- updated: PageBuilder (+added properties: `nextPage`, `prevPage`, `firstPage`, `lastPage`) by [Liao San-Kai](https://github.com/liaosankai)\n- updated: NoSQL", "- fixed: U.request() --> `DELETE` method has `application/x-www-form-urlencoded` as default content type\n- fixed: routing with `delete` flag\n- fixed: F.worker()\n- fixed: WebSocket event handlers\n- fixed: sync2()\n- fixed: @{place}\n- fixed: @{section}\n- fixed: controller.memorize() - problem with different layouts", "- improve: routing performance with F.onAuthorization()", "======= 1.9.1 (HOTFIX)", "- added: new sitemap system\n- added: a default schema validator is F.onValidation()\n- added: ErrorBuilder.setContentType() --> default application/json\n- added: View engine supports `else if`\n- added: U.parseBoolean(val, [def])\n- added: F.backup(filename, path, [callback], [filter]) --> backup some path to one file\n- added: F.restore(filename, target, [callback], [filter]) --> restore backup file (but not evaluating)\n- added: MailMessage supports custom headers `message.headers = { key: 'value' }`\n- added: @{notranslate} --> disables view translation\n- added: F.mode('debug') or F.mode('release') --> changes a mode of the framework\n- added: EACHSCHEMA([group], prepare(group, name, schema))", "- updated: MailMessage.bcc(email, [clear]) --> added clear\n- updated: MailMessage.cc(email, [clear]) --> added clear\n- updated: MailMessage.reply(email, [clear]) --> added clear", "- fixed: uploading files\n- fixed: prevention for mail double callback calling (by Andrea Sessa)\n- fixed: worker messaging\n- fixed: problem with schema parser (by Andrea Sessa)\n- fixed: F.load() --> \"versions\" is configurable\n- fixed: \"raw\" receiving of data\n- fixed: U.request(), the problem with default method\n- fixed: F.exists() - problem with URL query string\n- fixed: framework startup path\n- fixed: Date.format()\n- fixed: Assertion Testing", "======= 1.9.0", "- added: (IMPORTANT) ISOMORPHIC using\n- added: (IMPORTANT) new flag `mobile` (mobile routing), you can create a route to mobile device\n- added: (IMPORTANT) new flag `delay` for long time operations (it removes timeout)\n- added: readonly `req.mobile` -> returns `boolean`\n- added: new view tag: @{mobile} –> returns `boolean`\n- added: new view tag: @{isomorphic} –> returns `Object` with isomorphic objects\n- added: `config['disable-clear-temporary-directory'] = false` (after start)\n- added: `config['allow-compatibility'] = false` - a backward compatibility mode\n- added: `config['default-timezone']`\n- added: `config['directory-isomorphic']`\n- added: `config['directory-private']`\n- added: `F.path.private([filename])`\n- added: `F.path.isomorphic([filename])`\n- added: `Controller.ping()` for WebSocket\n- added: `global.DB()` --> same as `global.DATABASE()`\n- added: `global.isomorphic` --> returns `framework.isomorphic` --> returns isomorphic objects\n- added: `global.is_client` and `global.is_server` for isomorphic\n- added: cache for HTTP routing\n- added: RegExp routing `F.route('/{/^\\\\d+$/}', ...)`\n- added: `F.responseBinary(req, res, contentType, buffer, [type], [download], [headers])`\n- added: `SchemaBuilderEntity.filter(custom, [model], [reverse])`\n- added: `SchemaBuilderEntity.trim = true`(enable/disable trim strings (default: true))\n- added: `Number.prototype.add(value, [decimals])` -> supports percentage\n- added: `Date.prototype.toUTC([ticksOnly])`\n- added: `Date.prototype.extend()` -> extend current datetime about new date or time (more in documentation)\n- added: `F.stats.request.mobile`, `F.stats.request.desktop`\n- added: `res.setHeader('Vary', 'Accept-Encoding, User-Agent')` for same url addresses and different devices (desktop vs mobile)\n- added: binary - `total --translatecsv`\n- added: controller.jsonp(method_name, obj, [headers], [beautify], [replacer]);\n- added: CSS variables likes sass, example: `$color: red;`\n- added: CSS nesting\n- added: modificators for dynamic modification before compilation: views, styles and scripts\n- added: TransformBuilder\n- added: F.load(debug, load_types, [path]);\n- added: F.isWorker (is true when is called F.load())\n- added: F.isCluster (is true when the framework is running in the cluster)\n- added: F.logmail(address, [subject], body, [callback]) --> send e-mail message as plain text\n- added: Array.unique([property]) by Andrea Sessa\n- added: Array.pair(array, property, fn(itemA, itemB), [remove]) - pair arrays\n- added: String.base64ToBuffer();\n- added: terminal -> `tpm unpack [package_name] [optional: target_directory]`\n- added: versions is applied to raw HTML\n- added: versions supports auto-mapping\n- added: sync2(), e.g. sync2(fn), diff with v1: sync(fn)() and v2: sync2(fn)\n- added: \"dependencies\" file for installing dependencies (modules, packages, etc.)\n- added: @{nocompress html}, @{nocompress js}, @{nocompress css}, @{nocompress all}\n- added: req.authorize(callback(err, userprofile, isAuthorized))\n- added: res.content(code, body, type, [compress]) -> alias for F.responseContent()\n- added: F.localize(name, path, [middleware], [options]) - auto translating static files\n- added: F.listener(req, res) -> for multiple server listeners\n- added: F.restful(url, flags, onQuery, onGet, onSave, onDelete) -> creates routing\n- added: F.onSchema(req, group, name, callback(err, body)) -> for custom schemas\n- added: @{import(filename1, filename2, filenameN)}\n- added: SchemaBuilderEntity.setError(function(error, model, type, name));\n- added: F.snapshot(url, filename, [callback]);\n- added: CLEANUP(stream, [callback]) - clean up readable streams\n- added: configs directory\n- added: F.behaviour(url, flags);\n- added: behaviour: disable-measuring (default: false)\n- added: behaviour: disable-middleware (default: false)", "- updated: (IMPORTANT) routing: `json` flag is not required for receiving incomming data as JSON\n- updated: `F.mail(address, subject, view, [model], [callback], [language])` added language\n- updated: `F.view(name, model, [layout], [repository], [language])` added language\n- updated: `F.route(url, ...)`, `F.websocket(url, ...)` --> URL can be function(url, req, [flags])\n- updated: `versions` affects F.map() and F.merge()\n- updated: `controller.mail(address, subject, view, [model], [callback], [language])` added language\n- updated: `config['allow-performance']` is set to true\n- updated: (IMPORTANT) `F.map(url, filename/directory, [filter])` supports mapping directories\n- updated: (IMPORTANT) arguments order `SchemaBuilderEntity.setValidate(function(name, value, path, model, schema){})`\n- updated: (IMPORTANT) `U.extend(target, source, [rewrite]);` --> rewrite is by default: __true__\n- updated: `SchemaBuilderEntity.setPrepare(function(name, value, index, model){})` --> __model__ is new\n- updated: `SchemaBuilderEntity.define(name, value, required, [custom])` --> __custom__ is new\n- updated: HTML compressor\n- updated: favicon `(removed rel=\"icon\")`\n- updated: binary `tpm create [package] [directory]` (added argument [package], [directory])\n- updated: better handling middleware errors and added prevention of \"memory leak\"\n- updated: (IMPORTANT): Websocket ping is set to 3 minutes\n- updated: framework responds for bad requests with HTTP 403\n- updated: Mail (added support for Office365)\n- updated: Date.prototype.add() supports e.g. Date.prototype.add('25 days')\n- updated: String.prototype.params() -> supports double \"{{\"\n- updated: F.schedule(date, [repeat], fn) --> added [repeat]\n- updated: `F.responseStream()` and `controller.stream()` added [nocompress] argument\n- updated: binary `tpm` supports install package from different URL", "- removed: XSS check", "- fixed: `controller.binary(buffer, contentType, [download], [headers])`\n- fixed: routing `DELETE`\n- fixed: `binary` (creating empty-project, bad record with smtp options)\n- fixed: calling generator action\n- fixed: `binary --translate` (filenames)\n- fixed: SchemaBuilderEntity prepare (problem with nullable Boolean)\n- fixed: (IMPORTANT) 431 system route\n- fixed: F.log(), F.logger() –> problem with objects, reported by Nikita Shmidt\n- fixed: Number formatting (problem with negative numbers)", "- improved: performance +15%\n- improved: code optimalization\n- improved: Date.prototype.format()\n- improved: String.prototype.format()\n- improved: Number.prototype.pluralize()\n- improved: view debugging", "__IMPORTANT:__\n`exports.install = function(framework) {}` framework variable is removed but with backward compatibility (`config['allow-compatibility']`).", "======= 1.8.0", "source-code: \"tabs\" instead of \"spaces\"", "- added: SchemaBuilderEntity->setPrepare(function(name, value, index))\n- added: SchemaBuilderEntity–>setPrefix(prefix)\n- added: SchemaBuilderEntity->setResource(resourcename)\n- added: auto-trim strings in SchemaBuilderEntity\n- added: Controller.route;\n- added: ErrorBuilder is a global class\n- added: F.on('upload-begin', function(req, file) {})\n- added: F.on('upload-end', function(req, file) {})\n- added: config['static-accepts']: woff2\n- added: F.logger(filename, arg1, ...), controller.logger(...), @{logger(...)}\n- added: (IMPORTANT) F.exists(req, res, callback(next, filename))\n- added: callback: F.responseFile(), controller.file(), response.file()\n- added: callback: F.responseImage(), controller.image(), response.image()\n- added: callback: F.responseImageWithoutCache()\n- added: callback: F.responseStream(), controller.stream(), response.stream()\n- added: callback: F.responseStatic(), response.continue()\n- added: Array.prototype.findIndex(cb, [value]) returns Number\n- added: Array.prototype.toObject([name]) returns Object\n- added: Array.prototype.limit(max, fn(items, next), [callback])\n- added: Array.prototype.compare(propName, arr, comparer)\n- added: Image.geometry(w, h, options)\n- added: Image.thumbnail(w, h, options)\n- added: Image.filter(type)\n- added: `config['default-maximum-file-descriptors'] = 0` (0 = the watcher is disabled)\n- added: `config['default-interval-clear-dnscache'] = 2880` for clearing DNS cache of Utils.request(), Utils.download()\n- added: Utils.resolve(url, callback(err, uri)) DNS cache\n- added: Utils.clearDNS() clears DNS cache\n- added: Utils.isObject()\n- added: String.prototype.parseJSON()\n- added: Date.prototype.diff([date], type)\n- added: framework.onCompileView(name, content, model)\n- added: framework.on('cache-set', function(name, value, expire))\n- added: `@{compile handlerbars}CONTENT TO COMPILE@{end}`\n- added: `@{compile}CONTENT TO COMPILE@{end}`\n- added: Utils.streamer(delimiter, function(value, index)) returns function\n- added: HEAD method support for (controller.json(), .view(), .plain(), .file(), .stream())\n- added: global.NEWSCHEMA([group], name) for creating new schemas (more in docs)\n- added: global.GETSCHEMA([group], name) for getting new schemas (more in docs)\n- added: global.FINISHED(res/stream, callback) --> real end of the stream\n- added: global.DESTROY(stream) --> destroys the stream\n- added: (IMPORTANT) node.js generators for the routes", "- updated: (IMPORTANT): for evaluation multiple roles in routing (@role) framework validates only one role\n- updated: GZIP compression for static files (added .md, .json)\n- updated: request schema parser and XML parser -> better handling errors\n- updated: wrapped decodeURIComponent for prevention of parsing\n- updated: removed HTTP cache in DEBUG mode\n- updated: Image.miniature(w,h,color,[filter]) --> added filter\n- updated: binary supports translation files `--translate my-localization.txt`\n- updated: framework.mail() --> returns MailMessage\n- updated: controller.mail() --> returns MailMessage\n- updated: SchemaBuilderEntity.$async(callback, [return-only-this-index])\n- updated: translation @(#KEY) (direct reading) or @(TEXT TO TRANSLATE) (hash reading)\n- updated: Utils.request(), Utils.download() supports `dnscache` flag for caching host IP\n- updated: SchemaBuilderEntity.validation()\n- updated: F.cache.set(key, value, expire, [sync])\n- updated: NoSQL\n- updated: (IMPORTANT): Websocket ping is disabled by default", "- fixed: Image.resize()\n- fixed: F.usage() --> fixed queue pendings\n- fixed: (CRITICAL) SchemaBuilderEntity preparing (problem with prototypes)\n- fixed: (CRITICAL) a package or module installation from the URL address\n- fixed: (CRITICAL) response content-length\n- fixed: framework.redirect()\n- fixed: HTTP cache (added longer time)\n- fixed: auto JSON parsing in `json` request\n- fixed: Pagination.last() (Nikita Shmidt)\n- fixed: loading packages\n- fixed: callback error in MailMessage\n- fixed: TPM restore package\n- fixed: Utils.request() --> double calling of callback()\n- fixed: routing with `get` and `json` flag together", "- replaced: (IMPORTANT) `uri` to `url` in F.problems, F.changes, F.errors (saves memory)", "- improved: U.removeDiacritics() -> increase about 30%\n- improved: handling files\n- improved: auto-image-resizer (routes)\n- improved: Image.miniature() -> increase about 50%\n- improved: U.queue()\n- improved: (IMPORTANT) SchemaBuilder validation and preparation", "__GENERATORS__:", "- added: Image.$$save(filename, [writer])\n- added: Image.$$measure();\n- added: Image.$$identify();\n- added: Utils.$$request();\n- added: Utils.$$download();\n- added: Utils.$$send();\n- added: Utils.$$wait();\n- added: Utils.$$resolve();\n- added: HttpFile.$$copy()\n- added: HttpFile.$$read()\n- added: HttpFile.$$md5()", "======= 1.7.2", "- added: Array.prototype.extend(obj, [rewrite])\n- added: SchemaBuilderEntity->constant(name, [value])\n- added: Utils.minifyHTML(value);\n- added: Utils.minifyScript(value);\n- added: Utils.minifyStyle(value);\n- added: FrameworkImage.measureSVG(buffer);\n- added: auto-parsing SVG width/height\n- added: framework.translator([language], text);\n- added: TRANSLATOR\n- added: SUCCESS(boolean, [value]) returns { success: boolean, value: [value] }\n- added: framework.onLocate(req, res) --> this method sets the current localization\n- added: new installation event framework.on('module#name');\n- added: new installation event framework.on('controller#name');\n- added: new installation event framework.on('model#name');\n- added: new installation event framework.on('definition#name');\n- added: new installation event framework.on('config#name');", "- updated: CSS compressor (better compression)\n- updated: Utils.Request() supports head method", "- fixed: binary `total --diff`\n- fixed: debug.js (fixed port)\n- fixed: F.onCompileStyle and F.onCompileJavaScript (problem with filename)\n- fixed: Number.prototype.pluralize()\n- fixed: WebSocket message parsing\n- fixed: (CRITICAL) mail sender (problem with CRLF in BASE64)\n- fixed: (CRITICAL) `../src/node_http_parser.cc, line 392.`\n- fixed: the framework duplicates width/height in upload auto-parser\n- fixed: JPG width/height auto-parser", "======= 1.7.1 (HOTFIX)", "This version will work on `io.js` without problems.", "- added: framework.schedule(date/string/number, fn);\n- added: (IMPORTANT) a prevention for the HeaderSent exception\n- added: new option `sleep` for framework.http() & framework.https()\n- added: request.ip caching\n- added: framework.useConfig(filename-configuration)", "- updated: String.toSearch() removes non-word characters\n- updated: Utils.trim() supports arrays", "- fixed: framework.versionNode (updated for io.js)\n- fixed: (CRITICAL) if the controller middleware does not exist framework throws exception correctly\n- fixed: Utils.validation() (for Arrays)\n- fixed: authorization routing\n- fixed: (CRITICAL) request with multipart content-type (+fixed problem XSS)\n- fixed: (CRITICAL) controller.memorize() in JSON output\n- fixed: (CRITICAL) uploading files, problem with the filename/name field (if it contained `;`)", "- removed: mmr", "======= 1.7.0", "Framework supports a backward compatibility.\nFramework supports: one file only (all libraries in one JS file)\nFramework loads modules, packages, models, definitions, controllers", "- added: SCHEMA(name), returns group of schemas\n- added: Builders.Schema() - schema supports onGet, onSave, onRemove, onQuery\n- added: Builders.Schema() - schema supports workflows\n- added: Builders.Schema() - schema supports composer\n- added: Builders.Schema() - schema supports transformations\n- added: Builders.Schema() - schema supports grouping `Builders.schema('group').get('schema_name)`\n- added: Builders.Schema() - schema supports rules\n- added: Builders.Schema().make(obj, callback(err, model)) - make object with $save, $remove, $compose, etc.\n- added: framework.mail() - is alias for controller.mail()\n- added: framework.view(name, [model], [layout], [repository]) - is alias for controller.view()\n- added: validate handler contains new parameter model -> (name, value, path, schema, model)\n- added: String.prototype.replaceAt(index, character)\n- added: String.prototype.parseXML()\n- added: String.prototype.toSearch()\n- added: async queue - Utils.queue(name, maximumCalls, fn) (for e.g. EMFILE, too many open files)\n- added: Utils.isEqual(obj1, obj2, [properties])\n- added: ErrorBuilder.prototype.push()\n- added: ErrorBuilder.prototype.transform()\n- added: ErrorBuilder.prototype.output()\n- added: ErrorBuilder.prototype.setTransform(name) - set default transform\n- added: ErrorBuilder.addTransform(name, fn, [isDefault]) - add transform\n- added: ErrorBuilder.setDefaultTransform() for all ErrorBuilders\n- added: Pagination.addTransform(name, fn, [isDefault]) - add transform\n- added: Pagination.setDefaultTransform(name) for all Paginations\n- added: Pagination.prototype.transform()\n- added: Pagination.prototype.setTransform(name) - set default transform\n- added: Pagination.prototype.first()\n- added: Pagination.prototype.last()\n- added: Pagination.prototype.isFirst\n- added: Pagination.prototype.isLast\n- added: framework.config['allow-custom-titles'] - (default: false)\n- added: new option into Mail: rejectUnauthorized (for TLS)\n- added: @{log()} and @{LOG()} into views\n- added: @{console} (.log, .info, etc.) into views\n- added: framework.on('controller-render-head', function(controller) {})\n- added: framework.on('controller-render-meta', function(controller) {})\n- added: framework.on('init')\n- added: framework.merge('/merge.js', '/js/file1.js', '/js/file2.js')\n- added: framework supports X-Forwarded-Protocol header\n- added: FrameworkImage supports buffer\n- added: auto-vendor-prefixes: box-sizing\n- added: new flag `noxhr` or `-xhr` because all route contains +xhr as default\n- added: config['default-errorbuilder-resource-name']\n- added: config['default-errorbuilder-resource-prefix']\n- added: config['allow-handle-static-files']\n- added: FrameworkCache.get() alias for FrameworkCache.read()\n- added: supports creating route without action (framework wraps action)\n- added: .md (markdown) into static-accepts\n- added: (modules, models, sources and controllers) exports.id instead of export.name\n- added: framework.map(url, new_filename)\n- added: framework.config['directory-packages'] for packages\n- added: (IMPORTANT) PACKAGES (same as modules but package can contain many files in one file)\n- added: framework.stats.request.request (requests count)\n- added: FrameworkImage.miniature(w, h, bgColor)\n- added: Array.first([def])\n- added: Array.last([def])\n- added: framework.routing(name)\n- added: global --> ROUTING(name)\n- added: global --> NOOP() empty function (exists: noop(), Utils.noop())\n- added: global --> DEBUG boolean property (is the framework in debug mode?)\n- added: global --> RELEASE boolean property (is the framework in release mode?)\n- added: global --> TEST boolean property (is the framework in test mode?)\n- added: global --> F object property (is alias for \"framework\")\n- added: routing supports schemas `*custom-schema/User` and we can define it in flags\n- added: String.prototype.parseBool()\n- added: String.prototype.parseJSON()\n- added: framework.responseImagePrepare(req, res, fnPrepare, fnProcess, [headers])\n- added: response.throw400([problem])\n- added: response.throw401([problem])\n- added: response.throw403([problem])\n- added: response.throw404([problem])\n- added: response.throw408([problem])\n- added: response.throw431([problem])\n- added: response.throw500([error])\n- added: response.throw501([problem])\n- added: response.redirect(url, [permanent])\n- added: view supports localization\n- added: assertion testing --> framework sets global.assert = require('assert')\n- added: module/controller supports dependencies --> exports.dependencies = ['moduleA', 'moduleB'];\n- added: framework.dependencies (this object contains all installed total.js dependencies)\n- added: controller.translate([text]);\n- added: framework.translate([language], text)\n- added: @{body.} instead of @{post.}\n- added: @{query.} instead of @{get.}\n- added: @{files} uploaded files\n- added: .manifest to accept list\n- added: BINARY added --diff for creating difference between two resources", "- updated: framework.resize(), added: options.cache (true/false, default: true)\n- updated: the route flag can contian number (TIMEOUT for current route)\n- updated: (IMPORTANT) framework doesn't remove subdirectories with files in temporary directory\n- updated: (IMPORTANT) all models are loaded after is the framework loaded\n- updated: framework.redirect(url, redirectTo, [permanent]) supports relative redirects\n- updated: Utils.request(), timeout is possible to add as cookie, headers or encoding\n- updated: Utils.request() returns EventEmitter (begin, end, data(chunk, percentage))\n- updated: Utils.request() supports auto-redirect if response status code is 301\n- updated: Utils.download() returns EventEmitter (begin, end, data(chunk, percentage))\n- updated: Controller.proxy() - returns EventEmitter (begin, end, data(chunk, percentage))\n- updated: Array.wait(fnItem, fnCallback, removeItems) - default: function doesn't remove items\n- updated: Builders.UrlBuilder() -> toString([skipEmpty])\n- updated: Number.format([decimals], [separator], [decimalSeparator])\n- updated: Date.format([format]) - format is optional, function returns ISO format without \"Z\"\n- updated: response.send(), response.json() - supports ErrorBuilder\n- updated: framework.error() (returns a wrapped delegate if error is undefined)\n- updated: controller.baa([message]) - read documentation\n- updated: Array.where(), Array.find(), Array.remove() - added a new functionality\n- updated: @{view(name, [model], [expire], [expire-key])}\n- updated: @{cookie(name)} --> read cookie\n- updated: framework.mail(address, subject, view, model, callback, replyTo) - added: replyTo\n- updated: controller.view(name) can execute without name (controller.viewname contains name according to URL)\n- updated: @{post} is deprecated\n- updated: @{get} is deprecated\n- updated: String.encode(), String.decode()\n- updated: (IMPORTANT) changed the arguments in callback for workflow, compose, transform\n- updated: BINARY total --translate SOME TEXT create translate identifier", "- renamed: config['directory-angular'] to config['directory-public-virtual']\n- renamed: config['allow-compress-html'] to config['allow-compile-html']\n- renamed: (IMPORTANT) default view layout from `_layout` to `layout`\n- renamed: Utils.parseDateExpire() -> Utils.parseDateExpiration()", "- removed: JS CSS\n- removed: (IMPORTANT) view markup for Angular.js from the core (it will be a module)\n- removed: Controller.fileAsync()\n- removed: Controller.await()\n- removed: Controller.wait()\n- removed: Controller.run()\n- removed: Controller.complete()\n- removed: Controller.jsonAsync()\n- removed: Controller.viewAsync()\n- removed: Controller.redirectAsync()\n- removed: framework.run()", "- fixed: LOG()\n- fixed: view engine rendering (fixed problem with undefined and null values)\n- fixed: buffer exceeded if a framework receives a data\n- fixed: if path starts '/' then is view loaded directly from /views/ directory\n- fixed: xml parser\n- fixed: problem with parsing a bad JSON datas - framework.decrypt();\n- fixed: String.prototype.parseDate()\n- fixed: path in framework.resize()\n- fixed: framework.responseImageWithoutCache()\n- fixed: appending .js or .css through @{head()}\n- fixed: WebSocket authorization\n- fixed: WebSocketClient.req\n- fixed: routing (+ asterix routing)\n- fixed: controller.cancel() (after framework.emit('controller', ...))\n- fixed: view helpers (calling without arguments)\n- fixed: dynamic cache of views\n- fixed: mail sending\n- fixed: clearing temporary directory\n- fixed: parse JSON by the JSON route\n- fixed: paths in Windows\n- fixed: subject encoding in mail (supports UTF-8)\n- fixed: sender name encoding in mail (supports UTF-8)\n- fixed: Utils.trim()\n- fixed: Utils.validation() (problem with schema array)\n- fixed: Response.cookie()\n- fixed: String.prototype.format() --> null/undefined --> returns empty string\n- fixed: Utils.request() problem with unicode\n- fixed: framework.assert() problem with unicode\n- fixed: XML parsing", "- improvements: routing performance", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/static-file-merge\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/framework-schema-and-validation", "======= 1.6.2 (HOTFIX)", "- updated: obtaining `req.xhr` before middleware", "======= 1.6.1 (HOTFIX)", "- added: `ErrorBuilder.errors` list of errors\n- added: transform-style, perspective, backface-visibility into the CSS auto-vendor-prefixes\n- added: WebSocket supports global middleware\n- added: WebSocketClient.isWebSocket (for middleware instead of Response)", "- updated: assertion testing (author: @toshipon)", "- fixed: controller.callback([view_name]), supports NoSQL Embeded Database\n- fixed: WebSocket auto-ping\n- fixed: (debug mode) caching of static files\n- fixed: global middleware (fixed exception in exception)\n- fixed: Mail (problem with secure option, author: @asessa)\n- fixed: binary (if debug.pid exists then is deleted and created again)", "- improvements: framework (comparison of undefined)", "======= 1.6.0", "- added: framework.http(mode, [options]) - mode: test, debug or development, release or production\n- added: framework.https(mode, [options]) - I recommend to use NGINX as HTTPS proxy\n- added: middleware delegate: function(req, res, next, [options], [controller]) { next(); }\n- added: middleware to framework.websocket(url, funcInitialize, [flags], [protocols], [allow], [maximumSize], [middleware])\n- added: middleware to framework.file([name], [fnValidation], [fnExecute], [middleware])\n- added: middleware to framework.use(name), this is global middleware\n- added: middleware can add as flag: '#middleware1', '#middleware2'\n- added: Response.controller, link to the current controller (if exists)\n- added: Response.send([code], body, [contentType])\n- added: Response.json(obj);\n- added: Response.file(filename, [downloadName], [headers])\n- added: Response.stream(contentType, stream, [downloadName], [headers])\n- added: Response.continue();\n- added: Response.req (current request)\n- added: Request.query;\n- added: Request.body;\n- added: Request.files;\n- added: controller.middleware(names, [options], [callback])\n- added: controller.body --> is same as Controller.post\n- added: controller.query --> is same as Controller.get\n- added: controller.isController (for middleware)\n- added: controller.json(obj, [beautify], [replacer]) and ErrorBuilder.json([beautify], [replacer]), author: bir <https://github.com/bir>\n- added: utils.wait(fnValid, fnCallback, [timeout(default: 5000 ms)], [interval(default: 500 ms)])\n- added: new flag: 'xml' in controller.route()\n- added: new flag: 'xml' in utils.request()\n- added: new flag: 'xml' in framework.assert()\n- added: assertion testing: exports.usage = function() {} for custom results of test\n- added: assertion testing: exports.disabled = true for disabling current test\n- added: assertion testing: priority (example: exports.priority = 1)\n- added: routing supports multiple HTTP-VERBS/METHODS together (author: bir <https://github.com/bir>)\n- added: routing supports options for middleware, author: bir <https://github.com/bir>\n- added: config-test (new config file)\n- added: config['default-interval-clear-resources'], default 20 (minutes)\n- added: config['default-interval-clear-temporary'], default 3 (minutes)\n- added: config['default-interval-precompile-views'], default 61 (minutes)\n- added: config['default-interval-websocket-ping'], default 1 (minutes)\n- added: config['disable-strict-server-certificate-validation'], default true\n- added: create automatically a ping message for websocket clients\n- added: global INSTALL(type, name, declaration/url/function, [options], [callback]);\n- added: global UNINSTALL(type, name, [options]);\n- added: global CONTROLLER(name);\n- added: framework.install(type, name, declaration/url/function, [options], [callback]);\n- added: framework.uninstall(type, name, [options]);\n- added: framework.on('install', function(type, name) {});\n- added: framework.on('uninstall', function(type, name) {});\n- added: framework.on('route-add', function(type, route) {})\n- added: module/model/source/controller: exports.name = 'name ';\n- added: module/model/source/controller: exports.version = 'version';\n- added: model/source: exports.install = function(framework, options, name) {}\n- added: module/model/source/controller: exports.uninstall = function(framework, options) {}\n- added: String.prototype.parseDateExpire() - parse expiration date, example: '1 minute', '1 year'\n- added: String.parseConfig([default]);\n- added: framework.fs.create.database()\n- added: framework.fs.rm.database()\n- added: controller.isTransfer\n- added: Date.compare(date) - for instance of date;\n- added: Date.compare(d1, d2);\n- added: Controller.date(type, date)\n- added: Controller.callback([viewName])\n- added: HttpFile.type (HttpFile.contentType is deprecated)\n- added: controller.section(name, [value]);", "- updated: NoSQL v2.0.8\n- updated: String.parseDate('yyyy-MM-dd HH:mm:ss') - time is optional\n- updated: module: exports.install = function(framework, options) {};\n- updated: (IMPORTANT) INCLUDE(name, [options]), SOURCE(name, [options]) –> object\n- updated: (IMPORTANT) SOURCE(name, [options]), framework.source(name, [options]) –> object\n- updated: framework.controller(name) - definition was removed (use: framework.install())\n- updated: framework.run([http], config, [port], [ip], [options])\n- updated: utils.validate(), Builders.validate() –> prepare function (added: schemaName): function(name, value, path, schemaName)\n- updated: framework.assert() supports \"data\" as function (for future data)\n- updated: empty-project\n- updated: request.signature([key]) - added key param\n- updated: middleware function to: function(req, res, next) {}\n- update: expiration supports string (framework.cache, response.cookie), example: '1 minute'\n- updated: $view(name, model, [expire]), $viewToggle(name, model, [expire]) - added expiration {String}\n- updated: controller.validate('schema_name', model);\n- updated: Angular.js version\n- updated: @{css()} and @{js()} supports multiple values\n- updated: @{place()} doesn't add `<script>` tag automatically", "- renamed: framework.on('expire') -> framework.on('cache-expire')\n- renamed: framework.accepts(extension, [contentType]) -> framework.accept(extension, [contentType])", "- fixed: controller.custom()\n- fixed: utils.validate()\n- fixed: long messages in WebSocket by Andrea Sessa <https://plus.google.com/u/0/104713619368072403016>\n- fixed: view engine parser (reported by @tohachan)\n- fixed: Builders.prepare()\n- fixed: Builders.validate()\n- fixed: framework.responseFile()\n- fixed: framework.onCompileStatic()\n- fixed: framework configuration\n- fixed: JS CSS\n- fixed: Auto vendor prefixer (CSS)\n- fixed: Image.command()", "- removed: (IMPORTANT) COMPONENTS()\n- removed: (IMPORTANT) prefixes + framework.onPrefix()\n- removed: (IMPORTANT) controller.framework (use: framework. instead of self.framework)\n- removed: (IMPORTANT) global middleware from controllers\n- removed: (IMPORTANT) global module #\n- removed: (IMPORTANT) Request.data.get\n- removed: (IMPORTANT) Request.data.post\n- removed: (IMPORTANT) Request.data.files\n- removed: (IMPORTANT) view engine: templates were changed to views\n- removed: (IMPORTANT) `@{content()}`\n- removed: (IMPORTANT) framework.injectModel() -> framework.install()\n- removed: (IMPORTANT) framework.injectModule() -> framework.install()\n- removed: (IMPORTANT) framework.injectSource() -> framework.install()\n- removed: (IMPORTANT) framework.injectDefinition() -> framework.install()\n- removed: (IMPORTANT) framework.injectController() -> framework.install()\n- removed: (IMPORTANT) framework.onRoute() - TIP: use middleware\n- removed: (IMPORTANT) framework.onRequest() - TIP: use middleware\n- removed: (IMPORTANT) controller & module -> exports.request()", "- clean code\n- improvements: framework", "======= 1.5.3 (HOTFIX)", "- added: request.query (alias for request.data.get)", "- (IMPORTANT) renamed: framework.partial() to framework.middleware()", "- fixed: exit code in assertion testing (bug with lowest priority)\n- (CRITICAL) fixed: WebSocket event", "======= 1.5.2 (HOTFIX)", "- added: CONFIG(name) - returns a value from the config file\n- added: RESOURCE(name, key) - returns a value from the resource file\n- added: utils.parseXML(xml)\n- added: config['static-accept'] += '.json'\n- added: String.prototype.slug([max])\n- added: Array.prototype.orderBy([name], [asc])\n- added: framework.on('request', function(req, res) {})\n- added: framework.on('websocket', function(req, socket) {})", "- updated: assertion testing", "- fixed: WebSocket in IE\n- fixed: calling global helpers like this: @{someHelper('some-argument')}\n- fixed: controller.proxy()\n- fixed: request.signature()\n- fixed: cache.read() - problem with exact expiration\n- fixed: \"options\" route flag\n- fixed: configuration (fixer: @peterkc)\n- fixed: schemas\n- fixed: assertion testing\n- fixed: view @{foreach ....}", "======= 1.5.0 & 1.5.1", "- added: TOTAL.JS PACKAGE MANAGER (new binary: tpm === [t]otal.js [p]ackage [m]anager)\n- added: JS CSS (important: removed LESS)\n- added: framework.noCache(req, [res])\n- added: request.noCache()\n- added: response.noCache()\n- added: new config file (this file is loaded in a debug and in a release mode): /some-app/config\n- added: String.prototype.startsWith(text, [ignoreCase]);\n- added: String.prototype.endsWith(text, [ignoreCase]);\n- added: picture auto resizer: framework.resize(url, [width], [height], [extensions], [path], [options])\n- added: .webm into the config['static-accepts']\n- added: in views - into the repository, model, user, session, get, post, global, config can assign some value: @{repository.name = 'total.js'}\n- added: in views - supports @{foreach [property] in [array]} ... @{end}\n- added: in views - supports nested conditions\n- added: in views - supports inline helpers\n- added: in views - supports sections\n- added: controller.throw400([problem])\n- added: controller.throw401([problem])\n- added: controller.throw403([problem])\n- added: controller.throw404([problem])\n- added: controller.throw500(error)\n- added: controller.throw501([problem])\n- added: request.signature()\n- added: Builders.create(schemaName)\n- added: controller.exception\n- added: framework.onMail(address, subject, body, callback)\n- added: controller.mail(address, subject, viewName, [model], [callback])\n- added: controller.transfer(url, [flags])", "- updated: config['default-websocket-encodedecode'] - default: true\n- updated: @{options(array/object)} - supports Object\n- updated: utils.request(url, flags, [data], callback, cookies, headers, encoding, timeout)\n- updated: utils.download(url, flags, [data], callback, cookies, headers, encoding, timeout)\n- updated: framework.eval(string/url/function) - this function supports eval code from another URL\n- updated: assertion testing (new features)\n- updated: framework.isProcessed(filename or request)\n- updated: framework.isProcessing(filename or request)\n- updated: binary (some changes and improvements)\n- updated: template engine\n- updated: ErrorBuidler.toString([delimiter])", "- renamed: ErrorBuilder.length -> ErrorBuilder.count", "- fixed: framework.isProcessed()\n- fixed: binary (test.js in empty-project)\n- fixed: @{ngCommon()}\n- fixed: @{ngStyle()}\n- fixed: measure JPG - extended buffer\n- fixed: utils.validate()\n- fixed: Mail sender (problem with TLS)", "- removed: IMPORTANT: old template engine was removed from templates\n- removed: IMPORTANT: LESS CSS", "- improvements: views\n- improvements: templates", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/controller-transfer\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/controller-mail\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/css-jscss\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/routing-resize\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/views-place-sections\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/views\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/views-custom-helper", "======= 1.4.0", "- added: new global methods: INCLUDE() - framework.source(), SOURCE() - framework.source(), MODEL(name) -> framework.model(), MODULE(name) -> framework.module(), DATABASE() -> framework.database()\n- added: unauthorize flag\n- added: config['allow-compress-html'] (default: true)\n- added: controller.language (read from request.language)\n- added: framework sets response['Content-Length'] for some static files", "- updated: debug.js (added \"source\")", "- fixed: View not found (message includes full filename)\n- fixed: @{ngFilter()}\n- fixed: routing priority\n- fixed: config['allow-gzip']\n- fixed: utils.decode()\n- fixed: utils.request()", "- renamed: String.prototype.link([max]) to -> String.prototype.linker([max])", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/font-awesome\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/websocket\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/angularjs-websocket\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/config-debug-release", "- MODULES (NEW): https://github.com/totaljs/modules/tree/master/twitter", "======= 1.3.1 (HOTFIX)", "- updated: angular.js version (v1.2.15)", "- fixed: partial views rendering in the layout\n- fixed: internally utils", "======= 1.3.0", "- added: supports CoffeeScript\n- added: framework.isWindows (readonly, boolean)\n- added: framework.isCoffee (readonly, boolean)\n- added: framework.config['directory-source'], great for business logic\n- added: framework.injectSource(name)\n- added: framework.source(name), call a business logic\n- added: new global methods include() and source() are linked into the config['directory-source']\n- added: config['default-websocket-encodedecode'] - encodeURIComponent && decodeURIComponent (IMPORTANT: default: false)\n- added: Builders.ErrorBuilder.resource(filename, prefix) - can change resource filename or prefix\n- added: new global variables - Builders, Mail, Utils\n- added: Builders.validate(schemaName, model) - returns ErrorBuilder from everywhere (uses framework.resource)\n- added: allowed controllers in subdirectories\n- added: utils.assign(obj, path, value/function) - read more in documentation", "- updated: Builders.schema(name, obj, [defaults], [validator]) - validator is new\n- updated: Builders.validation(name, [arr] or [function])\n- updated: controller.find(id or function)\n- updated: utils.copy(source, [target]);\n- updated: WebSocket.close([id], [message], [code]);\n- updated: WebSocketClient.close([message], [code]);", "- fixed: Controller properties on the WebSocket connections\n- fixed: binary\n- fixed: utils.validation()\n- fixed: multipart upload (problem with multiple values)\n- fixed: layout in partial views (from the controller)\n- fixed: Windows path", "IMPORTANT:\nrewritten: WebSocket + WebSocket supports: text, JSON, binary, ping + pong", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs-bootstrap\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/bootstrap\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/framework-schema-validation\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/webrtc (unfinished but for an idea)\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/framework-business-logic-source\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/framework-inject-business-logic-source", "======= 1.2.3-1 (HOTFIX)", "IMPORTANT:\n- fixed: [authorize] flag\n- updated: utils.copy(source, target), previous: utils.copy(target, source);", "======= 1.2.3", "- added: view @{helper('name', [arg1], [arg2], ...)}\n- added: controller.helper(name, [arg1], [arg2], ...)\n- added: controller.change(message)\n- added: new markup /*auto*/ for auto-vendor-prefixes\n- added: [authorize] flag\n- added: @{ng(name)}\n- added: @{ngTemplate(name, [id])}\n- added: @{ngController(name)}\n- added: @{ngFilter(name)}\n- added: @{ngService(name)}\n- added: @{ngDirective(name)}\n- added: @{ngResource(name)}\n- added: @{ngCommon(name)}\n- added: @{ngInclude(name)}\n- added: @{ngStyle(name)}\n- added: @{ngLocale(name)}\n- added: @{helper(helperName, [param1], [param2], ...)}\n- added: config['directory-angular']\n- added: config['angular-version']\n- added: config['angular-i18n-version']\n- added: binary: total -angular [or] total -a\n- added: framework.change(message, [name], [uri], [ip]);\n- added: framework.changes;\n- added: framework.on('change', message, [name], [uri], [ip]);", "IMPORTANT:\n- added: routing with asterix, example: framework.route('/subpage/*', ...);", "IMPORTANT:\n- updated: [logged] flag is obsolete, new flag: authorize\n- updated: [unlogged] flag is obsolete (without flag)", "- fixed: helpers\n- fixed: static files caching in debug mode", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs-websocket\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs-common\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs-mongodb-rest-resources\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs-routing\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/changes\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/routing\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/problems", "======= 1.2.1-1 (NPM problem)\n======= 1.2.1 (NPM problem)\n======= 1.2.0", "- new: NEW TEMPLATE ENGINE 2.0", "- added: route to website, route to file and route to websocket is possible everywhere\n- added: node harmony functions (see example)\n- added: gc() into framework.on('service')\n- added: config['allow-performance'] true/false (default, false)\n- added: config['default-image-converter'] (default \"gm\" - GraphicsMagick, another possibility: \"im\" - ImageMagick)\n- added: new views/templates/contents cache\n- added: framework.problem(message, [name], [uri], [ip]);\n- added: framework.on('problem', message, [name], [uri], [ip])\n- added: framework.problems;\n- added: req.language;\n- added: controller.title()\n- added: controller.description()\n- added: controller.keywords()\n- added: controller.problem(message)\n- added: controller.memorize(key, expire, fnTo, [fnFrom]) - cache for controller.view(), controller.json(), controller.plain()\n- added: Array.prototype.trim()\n- added: Array.prototype.wait()\n- added: Array.prototype.async()\n- added: String.prototype.hash([type])\n- added: Pagination.next([format]), Pagination.prev([format])\n- added: utils.isRegExp(obj)", "- updated: license\n- updated: parsing of configuration: # and // is a comment\n- updated: auto-vendor-prefixes (updated linear-gradient prioraty according to w3schools.com)\n- updated: websocket.send(message, [id], [blacklist]), id and blacklist can be a function\n- updated: controller.view400([problem])\n- updated: controller.view403([problem])\n- updated: controller.view404([problem])\n- updated: controller.view501([problem])\n- updated: controller.plain(contentBody, [headers]) - added JSON serialized for objects\n- updated: controller.json(obj, [header], [beaufity]);\n- updated: framework.usage([detailed]) - returns OBJECT\n- updated: FrameworkCache.removeAll(search or regexp-pattern)\n- updated: @{sitemap} is currently: @{sitemap()}\n- updated: PageBuilder\n- updated: @{template()} and controller.template() - default repository is controller repository", "- removed: border-radius and box-shadow from auto-vendor-prefixes", "- obsolete: Array.prototype.waiting()", "- fixed: controller.view500()\n- fixed: controller.proxy(), utils.request(), utils.download() - problem with NGINX, missing Content-Length header\n- fixed: WebSocket skips throwing error (socket close, EPIPE)\n- fixed: mail (SPAM fixes)\n- fixed: buffer.write (new node => 0.11.11)\n- fixed: IP and heroku deploy", "- rewritten: view engine\n- rewritten: template engine (according to view engine)", "- improvements: views\n- improvements: templates\n- improvements: partial routing", "IMPORTANT: framework.usage() returns OBJECT\nIMPORTANT: markup of template is OBSOLETE. Templates support only view markup.", "- EXAMPLE (NEW): https://github.com/totaljs/demo\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/heroku\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/controller-memorize\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/generators\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/routing-inline\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/problems\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/mongoose\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/pagination\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/templates", "======= 1.1.0", "- added: new feature COMPONENTS\n- added: new feature MODELS\n- added: framework.id\n- added: framework.isDebug\n- added: framework.isTest\n- added: framework.model(name)\n- added: framework.controller(name, definition)\n- added: framework.functions\n- added: framework.assert(name, callback)\n- added: framework.assert(name, url, callback, method, data, headers, xhr)\n- added: framework.injectComponent(name, url)\n- added: framework.injectModel(name, url)\n- added: framework.path.components([filename])\n- added: framework.path.models([filename])\n- added: controller.model(name)\n- added: controller.$model - (property contains current model)\n- added: flag: OPTIONS", "- updated: framework.usage([detailed])\n- updated: BINARY\n- updated: WebSocket skips throwing error (ECONNRESET)", "- fixed: framework.controller(name)\n- fixed: // char in views and templates\n- fixed: assertion testing\n- fixed: mail attachment (fixed: line too long)\n- fixed: \"@charset\" keyword in CSS\n- fixed: cache-control header\n- fixed: HTML conditional comments in views\n- fixed: controller.cors(), fixed problem with preflight\n- fixed: controller.empty() -> added 204 http status code", "improvements: views (in release mode)", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/components\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/models\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/minimal\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/framework-functions\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/cors\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/cluster", "======= 1.0.2 (HOTFIX)", "- fixed: mail message (problem with diacritics in OUTLOOK)", "======= 1.0.1 (HOTFIX)", "- added: advanced template conditions", "- fixed: builders.prepare()\n- fixed: binary (command-line tools)\n- fixed: views conditions" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [3, 6627], "buggy_code_start_loc": [3, 6625], "filenames": ["changes.txt", "utils.js"], "fixing_code_end_loc": [5, 6627], "fixing_code_start_loc": [4, 6625], "message": "The package total.js before 3.4.8 are vulnerable to Remote Code Execution (RCE) via set.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:totaljs:total.js:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "903890AB-2DE4-4BA4-83F0-AC47EEF03AFB", "versionEndExcluding": "3.4.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The package total.js before 3.4.8 are vulnerable to Remote Code Execution (RCE) via set."}, {"lang": "es", "value": "El paquete total.js versiones anteriores a 3.4.8, es vulnerable a una ejecuci\u00f3n de c\u00f3digo remota (RCE) por medio de set"}], "evaluatorComment": null, "id": "CVE-2021-23344", "lastModified": "2021-03-05T19:26:24.673", "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"}, {"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": "report@snyk.io", "type": "Secondary"}]}, "published": "2021-03-04T17:15:13.153", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/totaljs/framework/commit/c812bbcab8981797d3a1b9993fc42dad3d246f04"}, {"source": "report@snyk.io", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-TOTALJS-1077069"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-94"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/totaljs/framework/commit/c812bbcab8981797d3a1b9993fc42dad3d246f04"}, "type": "CWE-94"}
243
Determine whether the {function_name} code is vulnerable or not.
[ "======= 3.4.9", "- fixed measuring dimension for `.gif` images", "- fixed potential remote code execution in `U.set()` founded by [Snyk](https://snyk.io/vuln)", "\n======= 3.4.7", "- fixed: command injection in `Image.pipe()` and `Image.stream()`\n- fixed `DELETE` method for the schemas (now it works like `PATCH` method)\n- fixed: `controller.transfer()`", "======= 3.4.6", "- added: a support for Total.js v4 UIDs", "- updated: file stats\n- updated: calculating of `usage`", "- fixed: applying of `default_root` in static files\n- fixed: routing evaluation\n- fixed: parsing of longer WebSocket messages\n- fixed: mail error handling\n- fixed: `versions` with `default_root`", "======= 3.4.5", "- fixed: a problem with persistent images", "======= 3.4.4", "- added: schema options `$.successful(function(response) {})`\n- added: `options.reconnectserver {Boolean}` to `WEBSOCKETCLIENT`\n- added: `req.snapshot(callback(err, request_body))`\n- added: a new command `CMD('reload_preferences')`\n- added: a new FILESTORAGE mechanism based on `UID`\n- added: `sql` extension to `U.getContentType()`\n- added: `F.stats.performance.usage` which contains percentual usage of the thread", "- updated: `SchemaOptions` method `$.response([index/operation_name])`, e.g. `$.response('workflow.NAME')`\n- updated: snapshot `startscript.js.json` contains tabs instead of spaces\n- updated: `DatabaseBuilder.rule(rule, [param])`, supports string declaration of filter function\n- updated: `URL` validation", "- fixed: cleaning of NoSQL embedded databases\n- fixed: `String.parseCSV()`, now supports multiline strings\n- fixed: a bug when closing of websocket\n- fixed: `DatabaseBuilder.search()` method\n- fixed: `Error` in `CLONE()` method\n- fixed: `schema.inherit()` by adding `schema.middleware()` and `schema.verify()`\n- fixed: parsing messages in WebSocket\n- fixed: a problem in some commands pre-render in the view compiler\n- fixed: parsing of query strings", "======= 3.4.3", "- added: `HASH(value, [type])` for creating hash like in jComponent\n- added: `SchemaOptions.repo` as alias to `SchemaInstance.model.$$repository`\n- added: a new type `CONVERT syntax` to `schema.define()` (more in docs)\n- added: `SchemaEntity.verify(name, function($), [cache])` for async verification of values\n- added: `TEMP` variable as a new global variable (it's cleaned every 7 minutes)\n- added: `CONF.allow_persistent_images: true` which allows to reuse resized images in temp directory\n- added: `req.filecache(callback)` as alias for `F.exists()`\n- added: own QueryParser\n- added: `RESTBuilderInstance.convert('name:String,age:Number')` method\n- added: `RESTBuilder.upgrade(fn(restbuilder))` for upgrading of `RESTBuilder`\n- added: `RESTBuilder` parses Total.js Errors in responses as Error\n- added: `String.prototype.env()` replaces all values in the form `[key]` for `CONF.key`\n- added: WebSocket supports a new type - raw `buffer`\n- added: `Number.fixed(decimals)`", "- updated: `websocket.send2(message, comparer, replacer, [params])` by adding `params` argument for comparer function\n- updated: `Websocket.encodedecode` can enable/disable easily encoding of messages\n- updated: bundling skips all bundles with `-bk.bundle` in filename\n- updated: bundle filenames are displayed in console\n- updated: `UPDATE()` method by adding `noarchive` argument\n- updated: `TEST()` method supports `[subdomain]` keyword and `METHOD url` in URL address\n- updated: `MODIFY([filename], fn)` by adding `filename` argument\n- updated: background of schedulers by @fgnm\n- updated: `U.download()` by adding `param` argument\n- updated: `U.request()` by adding `param` argument\n- updated: `schema.cl(name, [value])` method by adding `value` argument for replacing of existing code-list\n- updated: Tangular version to `v4.0.0`", "- improved: `filename` in modificators (now filenames contain relative paths)\n- improved: performance of `U.request()` (around +10%)\n- improved: performance of `U.download()` (around +10%)\n- improved: performance of `RESTBuilder`\n- improved: CSS minifier by compressing single hex color from e.g. `#000000` to `#000`", "- fixed: localization in `totaljs` executable script\n- fixed: phone validation\n- fixed: `DOWNLOAD()`\n- fixed: `Number.VAT()` by Tomas Novak\n- fixed: debugging mode in Node.js v14\n- fixed: `allow_compile_html` in static files\n- fixed: `ROUTE()` method, there was a problem with spaces `GET /* `\n- fixed: `ACTION()` with json output\n- fixed: controller in `$ACTION()` with used `get` and `query` actions\n- fixed: `PATCH` method in `$ACTION()`\n- fixed: `schema.allow()` in `PATCH` method\n- fixed: image resizing in debug-mode", "======= 3.4.1", "- added: `SchemaOptions.parent` returns a parent model\n- added: Tangular template engine (experimental)\n- added: `String.makeid()` for creating of unique identifier from string\n- added: a new property called `message.ua` to `FLOWSTREAM()`", "- updated: `HttpFile.fs()` by adding `id` argument for updating of existing file\n- updated: default value for `allow_ssc_validation` to `true`", "- fixed: `String.parseDate(format)` with defined format\n- fixed: inheriting of controllers between schemas\n- fixed: `MailMessage.attachments()`\n- fixed: calling of `F.snapshotstats` in cache recycle\n- fixed: `controller.success()`\n- fixed: removing of unused files when a bundle is extracting\n- fixed: a processor function in `F.backup()`", "- improved: `Date.format()`\n- improved: Total.js translate (supports ErrorBuilder and DBMS)", "======= 3.4.0", "- added: `date.setTimeZone(timezone)`\n- added: `NOSQL('~absolute_path.nosql')' loads external NoSQL embedded database\n- added: `TABLE('~absolute_path.nosql')' loads external Table\n- added: `(generate)` subtype into the `config` files\n- added: `String.isBase64()`\n- added: new schema type `Base64`\n- added: SchemaEntity supports `schema.addWorkflowExtension(name, fn($, [data]))`\n- added: SchemaEntity supports `schema.addTransformExtension(name, fn($, [data]))`\n- added: SchemaEntity supports `schema.addOperationExtension(name, fn($, [data]))`\n- added: SchemaEntity supports `schema.addHookExtension(name, fn($, [data]))`\n- added: SchemaEntity supports `schema.setSaveExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setReadExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setQueryExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setRemoveExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setInsertExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setUpdateExtension(fn($, [data]))`\n- added: SchemaEntity supports `schema.setPatchExtension(fn($, [data]))`\n- added: SchemaOptions supports `$.extend([data])` for evaluating of all extensions for the current operation\n- added: `WebSocket.keys` property (it contains all keys with connections)\n- added: `threads` directory for server-less functionality\n- added: a global variable called `THREAD` with a name of current thread\n- added: `require('total.js').http(..., { thread: 'thread_name' })` evaluates only specified thread\n- added: `require('total.js').cluster.http(..., { thread: 'thread_name' })` evaluates only specified thread in cluster\n- added: framework creates a file with app stats in the form `your_init_script_name.js.json`\n- added: a new config key `allow_stats_snapshot`\n- added: view engine `@{import()}` supports auto-merging JS or CSS files: `@{import('default.js + ui.js')}`\n- added: `exports.options` delegate to component in `FLOWSTREAM`\n- added: `DatabaseBuilder.autofill()` from DBMS\n- added: `HttpFile.extension` property\n- added: `HttpFile.size` property alias to `HttpFile.length`\n- added: auto-session cleaner of unused sessions\n- added: `allow_sessions_unused` config key for cleaning of unused sessions\n- added: missing `PATH.schemas`, `PATH.operations` and `PATH.tasks`\n- added: a new method `PATH.updates`\n- added: easy updating of applications via `UPDATE(versions, [callback], [pause_server_message])`\n- added: NOSQL counter `.reset([type], [id], [date], [callback])` method-\n- added: `session.listlive(callback)` returns all live items in session\n- added: `controller.ua` returns parsed User-Agent\n- added: `$.ua` returns parsed User-Agent in Schemas, Operations, TaskBuilder, `MIDDLEWARE()` and `AUTH()`\n- added: support for `.mjs` extensions\n- added: a simple support for DDOS protection `allow_reqlimit : Number` (max. concurent requests by IP just-in-time)\n- added: unit-testing supports colors, added by @dacrhu\n- added: `String.encryptUID()` as alias for `U.encryptUID()`\n- added: `String.decryptUID()` as alias for `U.decryptUID()`", "- updated: `WEBSOCKET()` supports `+`, `-` and `🔒` as authorization flags\n- updated: `LOAD()` supports `service` type\n- updated: cluster watches `restart` or `restart_NAME_of_THREAD` files for restarting of existing threads\n- updated: cluster supports `auto` mode\n- updated: cluster supports watcher in `debug` mode\n- updated: `*.filefs()`, `*.filenosql()`, `*.imagefs()`, `*.imagenosql()` by adding `checkmeta` argument\n- updated: `$.done([user_instance])` method in `AUTH()`, added a new argument called `user_instance` (optional)\n- updated: GZIP is enabled only for JSON bodies which have more than 4096 bytes\n- updated: `.env` parser supports parsing of `.env-debug` or `.env-release` files according to the mode\n- updated: list of user-agents in `String.parseUA()`", "- fixed: `ON('error404')` when the route doens't exist\n- fixed: `filter` in Schema `workflows`, `transformations` and `operations`\n- fixed: `NOSQL()` joins with absolute paths\n- fixed: `TABLE()` joins with absolute paths\n- fixed: `(random)` subtype in `config` files\n- fixed: `(response)` phrase in `ROUTE()` for multiple `OPERATIONS`\n- fixed: a response in `ROUTE()` with mulitple operations if the result contained some error\n- fixed: a security bug with a path traversal vulnerability\n- fixed: `debug` watcher for `themes`\n- fixed: `generators` in schemas with a new declaration\n- fixed: a problem with handling files in 404 action\n- fixed: `startup` directory in bundles\n- fixed: `schema.inherit()` didn't copy `required` fields.\n- fixed: `SUCCESS()` serialization with `SUCCESS()` argument\n- fixed: a critial bug with `UID()` generator\n- fixed: clearing of DNS cache", "- improved: `LOGMAIL()` mail format\n- improved: starting logs in console output (added IPv4 local address)\n- improved: performance with JSON serialization in `controller.success()` and `controller.done()`", "======= 3.3.2", "- fixed: default time zone (`utc` is default time zone)", "======= 3.3.1", "- added: `RESTBuilder.callback()` which performs `.exec()` automatically\n- added: `FLOWSTREAM()`", "- fixed: `AUDIT()` method\n- fixed: error handling in `controller.invalid()`\n- fixed: `req.authorize()`\n- fixed: CSS auto-vendor-prefixes, fixed `opacity` with `!important`\n- fixed: `CONVERT()` a problem with arrays", "======= 3.3.0", "- added: `NEWTASK(name, declaration)` for creating preddefined `TaskBuilder`\n- added: `TASK(name, taskname, callback, [controller/SchemaOptions/OperationOptions/ErrorBuilder])` for executing preddefined `TaskBuilder`\n- added: a new config key `directory_tasks` for `TaskBuilder`\n- added: a global alias `MODIFY()` for `F.modify()`\n- added: a global alias `VIEWCOMPILE()` for `F.view_compile()`\n- added: `mail.type = 'html'` can be `html` (default) or `plain`\n- added: `$.headers` into the `SchemaOptions`, `OperationOptions` and `TaskBuilder`\n- added: `String.parseCSV([delimiter])` returns `Object Array`\n- added: `String.parseUA([structured])` a simple user-agent parser\n- added: `req.useragent([structured])` returns parsed User-Agent\n- added: a new config key `default_crypto` it can rewrite Total.js crypto mechanism (default: `undefined`)\n- added: a new config key `default_crypto_iv` it's an initialization vector (default: generated from `secret`) or it can contain a custom `hex` value\n- added: a new config key `allow_workers_silent` can enable/disable silent workers (default: `false`)\n- added: a new config sub-type called `random`, example: `secret_key (random) : 10` and `10` means a length of value\n- added: a new command `clear_dnscache` for clearing DNS cache\n- added: commands `INSTALL('command', 'command_name', function)` for registering commands and `CMD(name, [a], [b], [c], [d])` for executing commands\n- added: `ENCRYPTREQ(req, val, [key], [strict])` to encrypt value according to the request meta data\n- added: `DECRYPTREQ(req, val, [key])` to decrypt value according to the request meta data\n- added: `controller.nocache()`\n- added: `controller.nocontent()`\n- added: `REPO` as a global variable\n- added: `FUNC` as a global variable\n- added: `MAIN` as a global variable\n- added: `DEF` as a global variable for defining of behaviour for some operations (alternative to `F`)\n- added: `PREF.set(name, [value])` (read+write) or `PREF.propname` (only read) for reading/writing a persistent preferences\n- added: `F.onPrefSave = function(obj)` to write preferences\n- added: `F.onPrefLoad = function(next(obj))` to read preferences\n- added: `RESTBuilder.url(url)` which returns a new instance of `RESTBuilder` for chaining\n- added: `restbuilder.keepalive()` enables a keepalive for `RESTBuilder` instance\n- added: `SESSION()` management, more in docs\n- added: `controller.sessionid` with ID of `SESSION()`\n- added: `AUTH()` supports a new auth declaration with `$` as `AuthOptions` like `SchemaOptions` or `OperationOptions`\n- added: `AuthOptions` to prototypes\n- added: `ErrorBuilder.length` property (alias for `instance.items.length)\n- added: Schemas `prepare` supports `req` argument\n- added: `DEF.currencies.eur = function(val) {}` registers a currency formatter\n- added: `DEF.helpers` registers a new view engine helper (`F.helpers` is alias for for this object)\n- added: `DEF.validators` is alias for for `F.validators`\n- added: usage of currency formatter `Number.currency(currency)`\n- added: new schema type `Number2` with default value is `null`, not zero `0`\n- added: `@{json2(model, elementID, key1, key2, key3)}` can serialize data with keys defined into the `<script type=\"application/json\">`\n- added: schemas supports `PATCH` and `.setPatch()`, only specified field are processed\n- added: `SchemaOptions` supports `$.keys` for `PATCH` method\n- added: `schema.cl(name)` (\"cl\" means codelist) returns `{Array}` a list of values from defined enum/keyvalue\n- added: `schema.props()` returns `{Object}` meta info about all defined properties\n- added: `SchemaOptions`, `OperationOptions` and `TaskOptions` supports `$.req` and `$.res` properties\n- added: `AUDIT(name, $, [type], message)` a method for audit logs\n- added: __obsolete__ message to older declaration of middleware, schemas and operations\n- added: `U.diffarr(prop, arr_A, arr_B)` for comparing of two arrays\n- added: `DIFFARR(prop, arr_A, arr_B)` is a global alias for `U.diffarr()`\n- added: `global.REQUIRE()` for local modules within app directory\n- added: `global.isWORKER` variable which contains `true` (when the process is executed as a worker) or `false`\n- added: `ACTION(url, [data], callback)` can evaluate a route without request creation\n- added: `ROUTE('🔒 METHOD URL')`, it means that 🔒 adds `authorized` flag\n- added: `ROUTE('+METHOD URL')`, it means that `++` or `+` adds `authorized` flag\n- added: `ROUTE('-METHOD URL')`, it means that `--` or `-` adds `authorized` flag\n- added: `SchemaOptions`, `OperationOptions`, `TaskOptions` supports filtered query arguments via `$.filter`\n- added: `controller.done([value])`\n- added: `SITEMAP()` as alias to `F.sitemap()`\n- added: config key `allow_localize` enables a localization for all `HTML` files\n- added: `controller.breadcrumb` returns all sitemap items\n- added: `PAUSESERVER(name, pause)` pauses web server (alias for `F.wait()`)\n- added: `PROXY(endpoint, hostname, [copypath], [before_fn(uri,req,res)], [after_fn(res)])` makes a direct proxy from webserver\n- added: `schema.middleware(function($, next))` for creating simple middlewares for Schema operations\n- added: `FILE404(fn(req, res))` performs a simple fallback for non-existing files\n- added: `$PATCH(schema, model, [options], callback, [controller])` method\n- added: `.env` parser to `process.env`\n- added: `String.parseENV()` for parsing `.env` syntax\n- added: `$.noop()` for custom responses\n- added: `$ACTION(schemaroute, [model], callback, [controller])` evaluates schema\n- added: `process.send('total:restart')` performs a restart of app when the app is in debug mode\n- added: `NOSQLREADER(filename)` for reading different files of NoSQL embedded databases\n- added: `TABLEREADER(filename)` for reading different files of Table embedded databases\n- added: `Mail.use()` an alias for `F.useSMTP()`\n- added: `F.onAudit(name, data)` delegate for handling audit logs\n- added: Components support a new features called `Parts`, more in docs", "- updated: `$.invalid()` without arguments can return a function `function(err)`\n- updated: Mail `unsubscribe` appends new header which enables `unsubscribe` in e.g. iOS\n- updated: `MODIFY`, handler contains a new argument `controller`\n- updated: `headers` argument in `controller.proxy` supports `flags: []` for REQEUST method\n- updated: `.filefs()` and `.filenosql()` supports `download` with `true` or with `(name, type) => 'new_name'` (`filename` will be read from NoSQL binary file)\n- updated: `$.done(arg)` argument `@arg` can be `boolean` (response will be as a value) or object/primitive value (`arg` will be as a value)\n- updated: `String.arg(obj, [encode], [def])` added `encode` (`true`, `json`, `html`) and `def` arguments\n- updated: `AUTH(req, res, flags, next)` and `next` function can handle `callback(err, user)`\n- updated: `REQUEST()` supports `keepalive` flag\n- updated: `bundles` mechanism supports merging files `--filename` between `bundles` files\n- updated: `String.hash(true)` returns unsigned int\n- updated: `CONF:default_image_converter` supports `magick` for new version of ImageMagick\n- updated: `CONF.default_image_consumption` can contain ZERO value which means disabled optimialization of CPU/memory consumption\n- updated: `CONF.default_image_consumption` has changed a default value to `0`\n- updated: `U.parseXML(str, [replace])` and `String.parseXML([replace])` contains a new argument called `replace`\n- updated: `LOAD()` added a callback function\n- updated: components support `encoding=\"utf8\"` attribute for `<file` tag (default: `base64`)\n- updated: `EventEmitter2` supports a new argument `obj`, example: `U.EventEmitter2(obj)` or supports `.extend` method: `U.EventEmitter2.extend(proto)`\n- updated: `UID()` generates new types of `UID` with 100% backward compatibility\n- updated: `FILESTORAGE()` now it works in cluster mode", "- fixed: schemas validation\n- fixed: error handling in dynamic schemas\n- fixed: CSS variables\n- fixed: CSS variables with additional `!important` clause\n- fixed: `controller.proxy()` with Gzip/Deflate compression\n- fixed: HTTP status code with `204` in `REQUEST()`\n- fixed: `cookies` in `WEBSOCKETCLIENT`\n- fixed: `REQUEST()` with `json` flag and with `null` and `''` value\n- fixed: rendering components in `layout`\n- fixed: resources, there was a bug with reading of value from `default.resource`\n- fixed: too many open files in `res.image()`\n- fixed: too many open files in `res.filefs()`\n- fixed: Schema `Boolean` parser\n- fixed: renamed `F.stats.request.path` to `F.stats.request.patch`\n- fixed: SMTP sender (a problem with auth mechanism with some mail servers)\n- fixed: filter in `F.backup()`\n- fixed: paths for stored directories in `F.backup()`\n- fixed: uploading files\n- fixed: `U.getExtension()` by @molda", "- renamed: `*.routeScript` to `*.public_js`\n- renamed: `*.routeStyle` to `*.public_css`\n- renamed: `*.routeFont` to `*.public_font`\n- renamed: `*.routeVideo` to `*.public_video`\n- renamed: `*.routeImage` to `*.public_image`\n- renamed: `*.routeDownload` to `*.public_download`\n- renamed: `*.routeStatic` to `*.public`\n- renamed: `controller.viewCompile()` to `controller.view_compile()`\n- renamed: event `cache-set` to `cache_set`:\n- renamed: event `controller-render-meta` to `controller_render_meta`\n- renamed: event `request-end` to `request_end`\n- renamed: event `websocket-begin` to `websocket_begin`\n- renamed: event `websocket-end` to `websocket_end`\n- renamed: event `request-begin` to `request_begin`\n- renamed: event `upload-begin` to `upload_begin`\n- renamed: event `upload-end` to `upload_end`\n- renamed: event `cache-expire` to `cache_expired`", "- __removed: backward compatibility__ with older version of Node.js < 10\n- removed: `F.hash()`, alternative `String.prototype.hash()`\n- removed: `controller.hash()`, alternative `String.prototype.hash()`", "- improved Schemas and error handling\n- improved `res.filefs()` method for nonexistent files", "======= 3.2.0", "- added: `WORKER()` alias to `F.worker()`\n- added: `WORKER2()` alias to `F.worker2()`\n- added: `F.cluster.https()`\n- added: `TaskBuilder.done2([send_value])` returns `function` with wrapped `.done()`\n- added: `TaskBuilder.success2([send_value])` returns `function` with wrapped `.success()`\n- added: `TaskBuilder.next2(name)` returns `function` with wrapped `.next()`\n- added: new `RESTBuilder` aliases `.DELETE()`, `.PUT()`, `.POST()`, `.PATCH() and `.GET()`\n- added: `schema.before(key, (value, model, index) => value)` is a simple and new alternative to `schema.setPrepare()`\n- added: `SchemaInstance.$parent` returns a parent schema (if the schema is nested schema)\n- added: `SchemaOptions.redirect(url)` can perform a redirect from the schema\n- added: `OperationOptions.redirect(url)` can perform a redirect from the operation\n- added: `.ics` extension as acceptable file for the web server", "- updated: `F.worker2()` returns entire `stdout` buffer in the `callback(err, buffer)`\n- updated: `$options()` by adding `disabled` key\n- updated: `String.ROOT()` by adding a support for jComponent `AJAX()` calls\n- updated: `RESTBuilder.method(method, [data])` added `data` argument\n- updated: `String.parseDate([format])` added `format` argument\n- updated: SMTP settings contain `heloid` as `heloidentifier` (manually can be defined `HELO` or `EHLO` command)\n- updated: SMTP hostname is computed from email if SMTP is not specified", "- fixed: critical bug with security + improved security\n- fixed: system routing\n- fixed: NoSQL sorting, solved a strange problem\n- fixed: `U.request()` with `GET` method by @khaledkhalil94 (it doesn't send JSON data if `data` is null/undefined)\n- fixed: `F.wait()` in WebSocket\n- fixed: `String.capitalize(true)`\n- fixed: `REQUEST()` uploading of additional multipart/form-data (removed encoding)\n- fixed: view engine conditions defined in `<script>`\n- fixed: auto-redirects in `U.download()`\n- fixed: image streams resizing\n- fixed: `@{'%config_key'}` a problem with rendering a value with `'`", "- removed: `X-Powered-By: Total.js`", "======= 3.1.0", "- added: CSS variables support default values `border-radius: $radius || 10px`\n- added: NoSQL storage `.find(beg, end, [threads])` + `.count(beg, end, [threads])` + '.scalar(beg, end, type, field, [threads])' with multiple thread support\n- added: `U.reader()`\n- added: `bundles` supports merging files between bundle and project, project file must start with e.g. `--name.js`\n- added: `.bundlesignore` support with similiar functionality like `.gitignore`\n- added: support for `SameSite` cookie attribute\n- added: `RUN()` for executing multiple Total.js operations\n- added: a new global alias `CONF` (it's a reference to config) for `F.config`\n- added: a new global alias `FUNC` (it's a reference to functions) for `F.functions`\n- added: `DatabaseBuilder.arg(key, value)` for adding an dynamic argument\n- added: NOSQL/TABLE modify supports `!field` as boolean toggle\n- added: NOSQL/TABLE modify supports a new type `$age: 'js_code'` with some JS code\n- added: NOSQL/TABLE update supports a new type `'js_code'` with some JS code\n- added: a new config item `default-restbuilder-timeout : 10000`\n- added: a new config item `default-cors : https://www.totaljs.com, https://www.componentator.com` which allows originators for `CORS()` method\n- added: a new config item `default-request-maxkeys : 33` for restricting query max. keys\n- added: a new config item `logger : false` which enables logging for Middleware, Schemas and Operations\n- added: a new config item `bundling : shallow` which enables shallow bundling (if `bundle.json` exists then the bundles won't be extracted)\n- added: `SchemaOptions` and `OperationOptions` supports `$.cancel()` method\n- added: `CACHE(name, [value], [expire], [persistent])` alias for `F.cache.get2()` and `F.cache.set()` or `F.cache.set2()`\n- added: encryption of config values\n- added: `F.refresh()` for refreshing of internal cache\n- added: `DatabaseBuilder.each(fn)` for browsing of evaluated records\n- added: Bundles can be downloaded from URL addresses\n- added: `ONCE()` alias to `F.once()`\n- added: `image.define(value)` performs `convert -define 'value'`\n- added: Total.js JS files (+ packages) tarted with `.` (dot) or ended with `-bk` won't be processed\n- added: A new builder called `TaskBuilder` for creating custom tasks in Schemas or Operations\n- added: `WebSocket.send2(message, [comparer(client, message)], [replacer])` a new method for better sending frames\n- addde: `PATH` as a global alias for `F.path`", "- updated: `debug` mode creates a `start_name_script.pid` instead of `debug.pid`\n- updated: `NEWOPERATION()` supports `repeat`, `stop` and `binderror` arguments (more in docs)\n- updated: routing, now it supports operations in the form `ROUTE('.. * --> @save_operation @load_operation (response)')`\n- updated: `ROUTE()` supports multiple HTTP method declaration `ROUTE('GET,POST,PUT /something/', action)`\n- updated: `ROUTE()` supports dynamic schemas\n- updated: `REQUEST()` can return binary data if the content-type is not `text/*` or `application/*`\n- updated: NoSQL joins support array values\n- updated: `ROUTING(id:|search, [flags])` method\n- updated: `F.path.mkdir(path, [cache])` can cache a current satte (default: false)\n- updated: `controller.all()` can return `Array` of all WebSocketClient\n- updated: startup info by adding user name\n- updated: `LOCALIZE()` now `url` arg can be a function which replaces `F.onLocale`", "- fixed: a critical bug with storing uploaded files via `httpfile.fs()` or `httpfile.nosql()`\n- fixed: a critical bug with JavaScript minificator\n- fixed: a critical bug with NoSQL counter and freezing app\n- fixed: a critical bug with rendering of multiple async components\n- fixed: a critical bug with GZIP compression (sometimes appeared in Safari)\n- fixed: `nosql.update()` and `nosql.modify()` methods if the first argument is a function\n- fixed: `F.wait()` in the test mode\n- fixed: `LOCALIZE()` for nested directories\n- fixed: sending of error handling when WebSocketClient is starting (for example: `unauthorized`)\n- fixed: `versions` and `auto` feature with enabled `F.wait()`\n- fixed: `versions` and `auto` feature with direct link to file\n- fixed: `LOAD('release')` a release mode\n- fixed: `SchemaInstance.$clean()` for nested schemas\n- fixed: extracting `bundles` (added `/flow/` and `/dashboard/`)\n- fixed: subdomain routing for `localhost`\n- fixed: service for database cleaner\n- fixed: rendering group of components\n- fixed: RESTBuilder - JSON request without param sends an empty object\n- fixed: `$MAKE()` with `callback`\n- fixed: `String.slug()` for UTF - Chinese/Japan/Arabic/etc. chars\n- fixed: async rendering of `components`\n- fixed: RESTBuilder cache works only if the response status is `200`\n- fixed: compressing CSS with `\\t` tabs\n- fixed: `controller.autoclear()`\n- fixed: `controller.proxy()`\n- fixed: `repeat` mode in `SCHEDULE()`\n- fixed: `--inspect` argument for Workers by Tema Smirnov\n- fixed: TLS in SMTP mail sender\n- fixed: applying of versions\n- fixed: unit-tests reads only `javascript` files\n- fixed: `controller.invalid()` a problem with ErrorBuilder as a argument", "- removed: `F.config.debug`\n- removed: `controller.isDebug`", "- improved: NoSQL reader\n- improved: `UID()` -> now it changes a random hash each minute\n- improved: CORS\n- improved: rendering of components", "======= 3.0.0", "- added: (IMPORTANT) bundles\n- added: (IMPORTANT) Total.js components can have async delegate\n- added: (IMPORTANT) Total.js components support nested public files encoded in base64\n- added: (IMPORTANT) NoSQL worker\n- added: (IMPORTANT) NoSQL embedded storage for smaller big data / IoT\n- added: `debugging` supports live reloading\n- added: new schema operations: `schema.setInsert()` and `schema.setUpdate()`\n- added: `RESTBuilder.patch([data])`\n- added: `RESTBuilder.type(new-content-type)`\n- added: `CONVERT(obj, schema)` for quick converting values like Schema (more in docs.)\n- added: `Capitalize2` schema type which converts only the first char\n- added: `MailMessage.high()` sets `high` priority of the email messsage\n- added: `MailMessage.low()` sets `low` priority of the email messsage\n- added: `MailMessage.confidential()` sets `Sensitivity` header with `confidential` value\n- added: `MailMessage.attachmentnosql(db, id, [name])` sends a file from NoSQL embedded database\n- added: `MailMessage.attachmentfs(storage_name, id, [name])` sends a file from FileStorage\n- added: `SchemaBuilderEntity.$stop()` stops the async list\n- added: `SchemaOptions.stop()` alias to `$.model.$stop()`\n- added: `SchemaOptions.next()` alias to `$.model.$next()`\n- added: `SchemaOptions.output()` alias to `$.model.$output()`\n- added: `SchemaOptions.clean()` alias to `$.model.$clean()`\n- added: `SchemaOptions.response()` alias to `$.model.$response([index])`\n- added: `SchemaOptions.$async(callback, [index])` alias to `$.model.$async()`\n- added: `SchemaOptions.$get([options], [callback])` alias to `$.model.$get()`\n- added: `SchemaOptions.$insert([options], [callback])` alias to `$.model.$insert()`\n- added: `SchemaOptions.$query([options], [callback])` alias to `$.model.$query()`\n- added: `SchemaOptions.$remove([options], [callback])` alias to `$.model.$remove()`\n- added: `SchemaOptions.$save([options], [callback])` alias to `$.model.$save()`\n- added: `SchemaOptions.$update([options], [callback])` alias to `$.model.$update()`\n- added: `SchemaOptions.$workflow(name, [options], [callback])` alias to `$.model.$workflow()`\n- added: `SchemaOptions.$transform(name, [options], [callback])` alias to `$.model.$transform()`\n- added: `SchemaOptions.$operation(name, [options], [callback])` alias to `$.model.$operation()`\n- added: `SchemaOptions.$hook(name, [options], [callback])` alias to `$.model.$hook()`\n- added: `SchemaOptions.stop()` alias to `$.model.$stop()`\n- added: a new route flag type `&group` something like `roles` but groups aren't evaluated\n- added: `route.groups` with defined groups\n- added: NoSQL `database.listing([view])` which generates a listing response\n- added: `DatabaseBuilder.insert(fn(doc))` can modify a document after `update` or `modify` has `insert` mode\n- added: `DatabaseBuilder.query(code)` can contain a raw JS condition in the form e.g. `doc.age > 18 && doc.age < 33`\n- added: `DatabaseBuilder.regexp(name, regexp)` RegExp search in strings\n- added: `DatabaseBuilder.fulltext(name, regexp, [weight])` full text search in strings, more info in docs.\n- added: `DatabaseBuilder.hour(name, [compare], value)` creates a condition for hours\n- added: `DatabaseBuilder.minute(name, [compare], value)` creates a condition for minutes\n- added: `Database.find2()` performs faster and reverse reading of documents (from end to begin of the file)\n- added: `Database.stream(fn, [repository], [callback(err, repository, count)])` for streaming documents\n- added: `Database.lock(callback(next))` locks all internal DB operations\n- added: `Database.ready(callback)` executes a callback when DB is ready to use (only for special cases if you use indexes)\n- added: new directory `schemas` with a new configuration item `directory-schemas'\n- added: new directory `operations` with a new configuration item `directory-operations'\n- added: `String.crc32([unsigned])`\n- added: `U.hash('crc32')` and `U.hash('crc32unsigned')`\n- added: config `nosql-worker' for enabling worker for NoSQL embedded database (default: `false`)\n- added: config `nosql-inmemory' can contain name of databases e.g. (`users, products`) or String Array\n- added: config `nosql-cleaner` for cleaning databases from removed documents (default: `1440` === 24 hours)\n- added: config `nosql-logger` (default `true`) enables simple logs when re-indexing and cleaning\n- added: config `security.txt` for auto-generating security.txt content (more in docs)\n- added: config `default-proxy` for default web proxy server\n- added: config `allow-cache-cluster` (default `true`) allow/disallow cache synchronization\n- added: `GUID()` a global alias for `U.GUID()`\n- added: `VIEW()` a global alias for `F.view()`\n- added: `SchemaBuilderEntity.$response([index])` returns a specific response from an operation in `async` queue\n- added: `$SAVE(schema, model, [options], [callback], [controller])` performs `schema.save()`\n- added: `$INSERT(schema, model, [options], [callback], [controller])` performs `schema.insert()`\n- added: `$UPDATE(schema, model, [options], [callback], [controller])` performs `schema.update()`\n- added: `$REMOVE(schema, [options], [callback], [controller])` performs `schema.remove()`\n- added: `U.streamer2()` same functionality as `U.streamer()` but it returns `Buffer` instead of `String`\n- added: `Number.round([precision])`\n- added: `UID([type])` supports custom types, e.g. `UID('users')` or `UID('orders')`\n- added: `REQUEST()` global method, it's alias to `U.request()`\n- added: `NOW` global property, it's alias to `F.datetime`\n- added: `DatabaseBuilder.promise()`\n- added: `RESTBuilder.promise()`\n- added: `RESTBuilder.plain()` it returns a raw string from the response body\n- added: `versions` file supports `auto` value for generating auto-checksum of files\n- added: `F.load()` supports `test`\n- added: NoSQL binary supports `custom` small data attributes\n- added: CSS and JS supports a simple View Engine markup (config + resources + F.global)\n- added: `controller.split` alias to `controller.req.split`\n- added: nicer error response messages\n- added: `RESTBuilder.proxy(proxy)` for HTTP proxy\n- added: `U.request()` supports a new flag `proxy`, for example `proxy 127.0.0.1:8080`\n- added: NoSQL database a new event `change`, more in docs\n- added: `schema.define()(DEFAULT_VALUE)` added `DEFAULT_VALUE`\n- added: `TESTUSER([user])` for faking of `F.onAuthorize` delegate, targeted for unit-testing only\n- added: `G` as a global alias for `F.global`\n- added: `ERROR([name])` is an improved `F.error()` without arguments\n- added: a simple support for `.heic` and `.heif` image format\n- added: `controller.sitemap_url2()`\n- added: `controller.sitemap_name2()`\n- added: `@{sitemap_url2()}`\n- added: `@{sitemap_name2()}`\n- added: `F.syshash` contains a simple MD5 hash with OS info\n- added: `SchemaEntity.clear()` for removing all current definition\n- added: new view engine markup `@{#}` for simulating of root URL\n- added: new view engine command `@{root}` for getting sub-root path\n- added: `String.ROOT()` for replacing `@{#}` markup in strings\n- added: `U.decryptUID(value, key)` for encrypting number/string values\n- added: `U.encryptUID(value, key)` for decrypting of number/string values\n- added: `F.config['secret-uid']` as a hidden secret for encrypting/decrypting values\n- added: `F.dir(path)` for changing of root directory\n- added: `NOSQL()/TABLE().memory(count, [size])` for memory consumption, more in docs\n- added: `HttpFile.fs(storage_name, [custom], [callback])` saves a file into the FileStorage\n- added: `HttpFile.nosql(db_name, [custom], [callback])` saves a file into the FileStorage\n- added: `res.filefs(storage_name, id, [download], [headers], [callback])` returns file from FileStorage\n- added: `res.filenosql(db_name, id, [download], [headers], [callback])` returns file from NoSQL binary\n- added: `res.imagefs(storage_name, id, image_make_fn, [headers], [callback])` returns file from FileStorage\n- added: `res.imagenosql(db_name, id, image_make_fn, [headers], [callback])` returns file from NoSQL binary\n- added: new stats `F.stats.performance` contains count of `request` and `file` per minute\n- added: new method `controller.operation(name, value, [callback], [options])` for evaluating of operation", "- updated: (IMPORTANT) NoSQL binary divides files to independent directories for 1000 files per directory\n- updated: `GROUP()` by adding a new argument `url_prefix`\n- updated: `NEWSCHEMA()` supports `NEWSCHEMA('group/name')`\n- updated: `ROUTE()`, extended syntax for schemas, for example: `Schema --> @name` (more in docs.)\n- updated: `ROUTE()` supports a new HTTP method definition `ROUTE('GET /api/users/')`, `ROUTE('POST /api/users/')`, etc.\n- updated: `ROUTE()` supports a schema definition directly in the URL `ROUTE('GET /api/users/ *User --> @save')`, etc.\n- updated: `tpm` supports a new command called `bundle`, for example: `tpm bundle cms`\n- updated: `F.restore()` filter can return a new filename (for files only)\n- updated: `@{import('livereload')}` or `@{import('livereload wss://mywebsite.com')}` supports `livereload` value and it's rendered in `debug` mode only\n- updated: information after the framework is started\n- updated: `schema.define('name', null)` removes a schema field\n- updated: Chunker supports `compression`, default `true`\n- updated: Chunker supports `autoremove` processed files in `each()` or `read()` method, default `true`\n- updated: `String.parseConfig(def, [onError])` can handle errors better\n- updated: `middleware`, now Total.js supports new declaration `F.middleware(function($) {})`\n- updated: `F.wait()` HTML template\n- updated: JavaScript compressor, now optimizes multiple `var` declarations\n- updated: `CORS()` without arguments for all routes, methods and origins\n- updated: `CORS()` tries to join multiple same preferences to one\n- updated: `CORS(path)` without additional arguments allows all HTTP methods\n- updated: `U.keywords()` for Chinese/Japan characters\n- updated: `@{import()}` by adding `manifest` value linked to `/manifest.json`\n- updated: `F.use()` supports `function` instead of `middleware` name\n- updated: improved crypto algorithm\n- updated: decreased a maximum count of keys to `33` from `69` when the query string is parsing\n- updated: extended `schema.required(name, (model, workflow) => workflow.update)`, more in docs.\n- updated: `$MAKE(schema, model, [filter/workflows], ...)` supports `workflows` (array or object) instead of filter for `schema.required()`\n- updated: `OPERATION()` by adding `controller`", "- fixed: mail attachments\n- fixed: mail `message.manually()`\n- fixed: WebSocket comparing of `origin` header\n- fixed: uninstalling CORS routes\n- fixed: cache for `favicon`\n- fixed: `Date.extend()`\n- fixed: `String.isJSON()` validator\n- fixed: `String.parseDate()` now it parses date to UTC correctly\n- fixed: `Date.format()` now it formats a date as UTC correctly\n- fixed: HTML compressor with `\\r\\n` (Windows line endings)\n- fixed: schema validation\n- fixed: `U.atob()`\n- fixed: `U.btoa()`\n- fixed: schema field can be changed dynamically\n- fixed: `String.arg()`\n- fixed: `controller.href()` with Array values\n- fixed: `U.get()` a problem with path with `-`\n- fixed: `U.set()` a problem with path with `-`\n- fixed: `F.path.mkdir()` in Windows and Linux", "- replaced: config `disable-clear-temporary-directory` to `allow-clear-temp : true|false`\n- replaced: config `disable-strict-server-certificate-validation` to `allow-ssc-validation : true|false`\n- replaced: config `default-websocket-request-length` to `default-websocket-maxlength`\n- replaced: config `default-request-length` to `default-request-maxlength`\n- replaced: config `default-maximum-file-descriptors` to `default-maxopenfiles`\n- replaced: `controller.proxy()` functionality (the name remains) via `controller.proxy2()` functionality", "- removed: `F.responseFile()`\n- removed: `F.responsePipe()`\n- removed: `F.responseImage()`\n- removed: `F.responseImageWithoutCache()`\n- removed: `F.responseStream()`\n- removed: `F.responseBinary()`\n- removed: `F.responseContent()`\n- removed: `F.responseRedirect()`\n- removed: `F.response400()`\n- removed: `F.response401()`\n- removed: `F.response404()`\n- removed: `F.response408()`\n- removed: `F.response431()`\n- removed: `F.response500()`\n- removed: `F.response501()`\n- removed: `F.responseStatic()`\n- removed: `F.setModified()`\n- removed: `F.notModified()`\n- removed: `F.responseCode()`\n- removed: `F.noCache()`\n- removed: `controller.$modified()`\n- removed: `controller.$etag()`", "- improved: `debug` mode timing with improved consumption\n- improved: performance (+20%) NoSQL embedded database\n- improved: reading performance (+5%) in `U.streamer()`\n- improved: CSS compressor\n- improved: CORS processing\n- improved: internal encryption/decryption mechanism", "======= 2.9.4 (HOTFIX)", "- fixed: mail attachments\n- fixed: comparing `origin` header in WebSocket\n- fixed: unit-testing", "======= 2.9.3 (HOTFIX)", "- added: `String.arg(obj)` for a simple templating `Hello {variable}!`\n- added: new event `ON('@controllername', function() {})` -> is executed if the controller is evaluated", "- updated: RESTBuilder default headers are lower-case\n- updated: `content-disposition` header by adding `utf-8` according to [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2.2)", "- fixed: a missing property `controller.params` in WebSocket controller\n- fixed: `$ASYNC()` execution in some cases\n- fixed: `SCRIPT()` code with comments\n- fixed: a callback reference in `OPERATION()`\n- fixed: cache after route is removed\n- fixed: `409` system route\n- fixed: requests with `range` header and bad values\n- fixed: `clearSchedule()`\n- fixed: `Date.extend()` problem with months\n- fixed: NoSQL counter reading stats", "======= 2.9.2", "- added: `controller.html(body, [headers])`\n- added: `F.cluster.master(name, [data])` - for child processes, this method emits an event in master process\n- added: `F.cluster.on(name, callback(data))` - master event listener\n- added: `LOGMAIL()` global alias for `F.logmail()`\n- added: `MAIL()` global alias for `F.mail()`\n- added: own implementation of `onFinished`\n- added: `RESTBuilder.cookies(obj)` can set cookies as raw object\n- added: `RESTBuilder.cook([true/false])` enables persistent cookies\n- added: `SchemaOptions.params` which returns dynamic params from the controller's action\n- added: `SchemaOptions.done([arg])` as a callback (contains wrapped SUCCESS())\n- added: `SchemaOptions.DB()` which returns `DB(this.error)` instance (for SQL Agent)\n- added: `OperationOptions.done([arg])` as a callback (contains wrapped SUCCESS())\n- added: `OperationOptions.DB()` which returns `DB(this.error)` instance (for SQL Agent)\n- added: static method `Image.measure(type, buffer)` for measuring width/height of image\n- added: `EACHOPERATION(function(name) {})` for obtaining all registered operations\n- added: `controller.params` which returns dynamic params from the action", "- updated: `F.load()`, now supports `string` for `debug` or `release` mode\n- updated: `F.cluster.request()` can be executed from master process\n- updated: `Image.miniature()` change a default filter from `Box` to `Hamming`\n- updated: `U.request()` supports a new flag `cookies` which enables a parsing cookies from response", "- fixed: schema validation (problem with Arrays)\n- fixed: determines `x-forwarded-proto`\n- fixed: nested schema validation\n- fixed: themes static routing\n- fixed: NoSQL reader\n- fixed: NoSQL counter (sorting while reading stats)\n- fixed: loading dependencies\n- fixed: uninstalling middleware\n- fixed: reading/updating sitemap in controller", "- removed: max. sort `string` length\n- removed: `auto` appending `.css` and `.js` extension in view engine\n- removed: experimental `defer` feature", "- improved: GZIP compression\n- improved: code", "======= 2.9.1 (HOTFIX)", "- added: `controller.throw409()`, `req.throw409()`\n- added: new view aliases: `@{R.something}` for `repository`, `@{M.something}` for `model` and `@{G.something}` for `global`", "- updated: `ErrorBuilder.push()` supports `.push(name, status_code)` or `.push(name, error, status_code)`", "- fixed: sitemap language auto-setting\n- fixed: NoSQL: `builder.paginate()` a problem with zero limit (default limit will be `maxlimit`)\n- fixed: NoSQL number filtering\n- fixed: localization of ErrorBuilder in controllers", "======= 2.9.0", "- added: `WebSocketClient`\n- added: `$ASYNC(schema, callback, [index], [controlller])` alias to `SchemaBuilderEntity.$async()`\n- added: `ArrayBuffer.prototype.toBuffer()`\n- added: `AUTH(fn)` is an alias to `F.onAuthorize = fn`\n- added: `controller.success()` alias to `controller.json(SUCCESS(value))`\n- added: `CORS()` alias to `F.cors()`\n- added: `DatabaseBuilder.paginate(page, limit)`\n- added: `F.config['allow-compile']` can disable the whole compilation of static files\n- added: `F.config['default-dependency-timeout']` it's a timeout for module dependencies\n- added: `F.path.rmdir(directory/directories, callback)`\n- added: `F.path.unlink(file/files, callback)`\n- added: `LOCALIZE()` a new global alias to `F.localize()`\n- added: `MAP()` a new global alias to `F.map()`\n- added: `MERGE()` a new global alias to `F.merge()`\n- added: `MIDDLEWARE()` a new global alias to `F.middleware()`\n- added: `NOSQL('users').backups([filter(doc)], callback(err, response))` returns all backups\n- added: `SchemaOptions.invalid(name, [value], [path], [index])` alias to `$.errors.push() + callback()`\n- added: `SchemaOptions.success()` alias to `callback(SUCCESS(value))`\n- added: `controller.sitemapid` contains a sitemap identifier\n- added: `controller.sitemap_add(parent, name, url)` appends a new item into the sitemap per request\n- added: `@{sitemap_add(parent, name, url)}` appends a new item into the sitemap per request\n- added: `SchemaEntity.required('fieldname', boolean/function(model))` which can disable/enable validation for this field", "- updated: `sitemap` routing can contain an additional path, e.g. `#sitemapid/path/`\n- updated: `F.localize()` supports sitemap routing\n- updated: `F.merge()` supports sitemap routing\n- updated: `F.map()` supports sitemap routing\n- updated: `F.http(mode, [options], [middleware(listen)])` added a new argument `middleware`\n- updated: `debug.js` now reads directories according to the config (author: @luoage)\n- updated: config parser supports `config` sub-type\n- updated: `controller.$exec()` --> `callback` is by default `controller.callback()`\n- updated: `F.localize()` has enabled `compression` by default\n- updated: HTTP server is listening after the framework is completely loaded\n- updated: (IMPORTANT) HTTP cache in dynamic content and static files\n- updated: `F.prototypes()` by adding `OperationOptions`\n- updated: ErrorHandling in schemas (supports inline validation and advanced conditions)\n- updated: `F.noCache()` is obsolete", "- renamed: `allow-handle-static-files` to `allow-static-files`", "- fixed: (IMPORTANT) `DatabaseBuilder.in()`\n- fixed: (IMPORTANT) `U.ls2()`\n- fixed: (IMPORTANT) `WebSocket` implementation (author: @jozefgula)\n- fixed: `ArrayBuffer` in webosocket\n- fixed: `F.path.mkdir()` on Windows (author: @molda)\n- fixed: `F.restore()` on Windows (author: @molda)\n- fixed: `F.rmdir` removes all files and directories\n- fixed: `JSON` type in Total.js schemas\n- fixed: `MODEL()`, `MODULE()`, `INCLUDE()` now are direct aliases\n- fixed: a check for maximum length of request data\n- fixed: Date formatting with `a` value\n- fixed: empty localization in view engine e.g. `@()`\n- fixed: external static routing in view engine on Windows\n- fixed: NoSQL filtering with `or`\n- fixed: NoSQL multiple updates\n- fixed: NoSQL sorting of boolean values in larger dataset\n- fixed: responding on `range` header\n- fixed: unit testing (author: @ckpiggy)\n- fixed: `schema.setPrefix()` in nested schemas\n- fixed: sitemap localization\n- fixed: CORS custom headers\n- fixed: NoSQL date filtering", "- improved: performance and security", "======= 2.8.0", "- added: `NOSQL().restore()` restores a database (its package)\n- added: Mail options support a new property `xoauth2` (it needs to contain a `BASE64` value) for sending emails via OAuth 2.0 tokens (more in docs)\n- added: `F.path.mkdir(path)` creates all directories according to the path\n- added: `MailMessage.send2([callback])` sends a message according to the framework configuration\n- added: a new filter for NoSQL embedded `DatabaseBuilder.contains(name)`\n- added: a new filter for NoSQL embedded `DatabaseBuilder.empty(name)`\n- added: (IMPORTANT) NoSQL counter supports daily stats (NoSQL counter files will be upgraded automatically and backwards incompatible)\n- added: (IMPORTANT) NoSQL database and counter can read data from URL\n- added: NoSQL counter `db.counter.daily_sum([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.daily_max([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.daily_min([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.monthly_sum([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.monthly_max([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.monthly_min([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.yearly_sum([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.yearly_max([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.yearly_min([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.stats_sum(top, [year], [month], [day], callback)` for reading stats\n- added: NoSQL counter `db.counter.stats_max(top, [year], [month], [day], callback)` for reading stats\n- added: NoSQL counter `db.counter.stats_min(top, [year], [month], [day], callback)` for reading stats\n- added: NoSQL counter `db.counter.minimum([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.maximum([id], callback)` for reading stats\n- added: NoSQL counter `db.counter.min(id, value)` for writing stats\n- added: NoSQL counter `db.counter.max(id, value)` for writing stats\n- added: NoSQL counter `db.counter.sum(id, value)` for writing stats (alias for `db.counter.hit()`)\n- added: NoSQL counter: a new event `stats` when the stats are changed\n- added: NoSQL logging in `DatabaseBuilder.log(msg, [user])`\n- added: NoSQL backuping documents while they are updating/removing in `DatabaseBuilder.backup([user])`\n- added: `CLONE(obj)` alias for `U.clone()`\n- added: `GROUP(flags, fn)` alias for `F.group()`\n- added: `F.cache.set2()` it creates a persistent cache (persistent items are stored in a file)\n- added: new View Engine command `@{'%config'}` which reads a value from config directly\n- added: `F.config['allow-filter-errors']` for filtering network unhandled errors\n- added: `REDIRECT()` alias for `F.redirect()`", "- updated: (IMPORTANT) packages compress/decompress function supports streaming data\n- updated: (IMPORTANT) `NOSQL().backup()` !!! was changed !!!!\n- updated: `controller.view(name/url, [model], [headers], [partial])` can render a view from URL address\n- updated: `F.backup()` argument `path` can contain `String Array` file list\n- updated: `controller.viewCompile(body, model, [headers], [partial], [cacheKey])` add a cache key\n- updated: `image.command(arg, value, [priority], [escape])` a `priority` argument can be `escape` when it contains `boolean` value\n- updated: `U.getExtension()` returns lower-case extensions\n- updated: `total.js/debug` watchs `/workflows` file\n- updated: file `/workflows` supports custom `options`, more in docs\n- updated: `Array.random()` algorithm (+70% faster than older)\n- updated: `RESTBuilder.file(name, filetarget, [filename])` can contain `filename` instead of buffer\n- updated: `U.streamer(beg, [end], onItem(item, index), [skip], [stream])` added a new argument `stream` for flushing buffer\n- updated: `ErrorBuilder.addTransform(name, callback(isResponse))` by adding new argument `isresponse`\n- updated: `sorting` (framework + NoSQL embedded), now supports `internationalization`\n- updated: `total.js/debugger` by adding a new option `options.watch = ['directory']`\n- updated: `U.streamer()` supports \"cancelation\", just return `false`\n- updated: CSS auto-prefixer, added: `repeating-linear-gradient`, `radial-gradient`, `repeating-radial-gradient` and removed `-o` prefix", "- fixed: (IMPORTANT) long messages in WebSocket\n- fixed: (IMPORTANT) `controller` param in schemas\n- fixed: moved executing of `MailMessage.callback()` to better place\n- fixed: mail auth when `options.user` and `options.password` are blank\n- fixed: JS/CSS/HTML blocks\n- fixed: `F.prototypes()`\n- fixed: `F.decrypt()` a problem with parsing JSON and date formats\n- fided: `debug.js` sometimes was created a problem with output informations", "- improved: Date formatting (+50%)\n- improved: NoSQL performance (around 60% in some cases)", "======= 2.7.0", "- added: __IMPORTANT__ new unit-testing mechanism\n- added: __IMPORTANT__ `F.prototypes(function(proto) {})` for extending all internal prototypes\n- added: `HttpFile` is set in `global` for extending of prototype\n- added: `file.move()` a new alias for `file.rename()`\n- added: `SchemaBuilderEntity.$controller(new_controller)`\n- added: `EMPTYCONTROLLER` is a global variable\n- added: new alias `NOSQL.set()` and `NOSQL.get()` for `NOSQL.meta()`\n- added: `RESTBuilder.file(name, filename, [buffer])` supports uploading files\n- added: `RESTBuilder.mobile()` adds `iPhone` phrase into the `User-Agent` header\n- added: `RESTBuilder.robot()` adds `Bot` phrase into the `User-Agent` header\n- added: a small protection for multipart data\n- added: a new global aliases `ROUTE()` --> `F.route()`, `FILE()` --> `F.file()` and `WEBSOCKET()` --> `F.websocket()`", "- updated: __IMPORTANT__ components (framework can render css/js from specific group)\n- updated: `F.cluster` each operation checks whether cluster is activated\n- updated: default IP to `0.0.0.0`\n- updated: `Date.prototype.format()` with `ddd` renders name of day with 2 capital letters", "- fixed: new schemas with defined callback `function($)`\n- fixed: loading of `config-test` file (added rewriting of existing values)\n- fixed: Total.js version in `debug.js`\n- fixed: cluster initialization", "- improved: `cors` in `F.restful()` and `F.restful2()`\n- improved: `auto-vendor-prefixes`\n- improved: parsing files from multipart data", "======= 2.6.2 (HOTFIX)", "- fixed: a critical bug with `debug.js`\n- fixed: `try/catch` block from parsing of WebSocket message", "======= 2.6.1 (HOTFIX)", "- fixed: timeout in `RESTBuilder` and `U.request()`\n- fixed: `F.merge()` a problem with `.js` or `.css` extension in some directory", "======= 2.6.0", "- added: `F.config['default-errorbuilder-status']` a default HTTP status for all error builders default `200`\n- added: `F.config['default-listenpath']` starts a UNIX socket server listening for connections on the given path\n- added: `F.listenpath` contains `default-listenpath` location\n- added: `F.custom(mode, http, request_prototype, response_prototype, options)` a new mode for overwriting default HTTP server\n- added: `schema.inherit([group], name)` can inherit all values from another schema\n- added: NoSQL synchronization for cluster (more in docs)\n- added: cache synchronization for cluster (more in docs)\n- added: `F.cluster` (more in docs)\n- added: Total.js `debug` script `require('total.js/debug')` instead of `debug.js` file\n- added: a support for `async` attribute when `<script async src=\"` tag is generating, e.g. `@{import('async default.js')}`", "- updated: `F.http(type, options)` supports `options.listenpath` for HTTP server (a direct shortcut for `default-listenpath`)\n- updated: `F.script` returns error if compilation fails\n- updated: `debug.js` supports `inspector`\n- updated: NoSQL embedded database sorting (increased read performance about 30%)\n- updated: RESTBuilder parsers JSON date string as `Date` object\n- updated: `favicon()` generates `<link rel=\"icon\"` instead of `<link rel=\"shortcut icon\"`", "- fixed: `controller.send()` bad declaration of `connection.id` for `id` and `blacklist` arguments\n- fixed: `totaljs --translate` problem with `node_modules` and `.git` directory\n- fixed: a waiting mode in `GETSCHEMA()`\n- fixed: cache `instance.cache()` in RESTBuilder\n- fixed: NoSQL filtering (critical)\n- fixed: a bug ImageMagick/GraphicsMagick when the path contains spaces (critical)\n- fixed: `controller.memorize()` didn't work (critical)\n- fixed: dynamic params when `controller.transfer()` is performed", "======= 2.5.0", "- added: a missing property for WebSocket controller `controller.mobile`\n- added: `EMIT()` alias for `F.emit()`\n- added: `ON()` alias for `F.on()`\n- added: `OFF()` alias for `F.removeListener(eventName, listener)` or `F.removeAllListeners([eventName])`\n- added: `controller.components()` adds script/css tag into the head\n- added: `@{components([group], [settings])}` renders all components together from selected group\n- added: a new alias `WAIT()` alias for `U.wait()`\n- added: `res.status(code)` for express middleware\n- added: `F.clearSchedule(id)` for removing existing schedules\n- added: a support for WebSocket compression\n- added: removing `.package` files from `tmp` directory\n- added: a new schema implementation (more in docs)\n- added: `F.restful2()` has simplified route mechanism (it doesn't use \"{id}\" param for insert(POST)/update(POST)/delete(DELETE) method with except \"GET\" method)\n- added: `res.binary(buffer, contentType, [type], [download], [headers])`\n- added: a new route flag `novalidate` (a prevention for Schema validation)\n- added: `U.upload(files, url, [callback], [cookies], [headers], [method], [timeout])` for multiple uploading files\n- added: `RESTBuilder.redirect(true/false)` enables/disables auto-redirect (default: enabled)\n- added: new schema aliases (`$QUERY()`, `$GET()`, `$WORKFLOW()`, '$TRANSFORM()' and `$OPERATION()`)\n- added: `allow-head` (default: false) adds `head` method into the each route automatically\n- added: `F.config['allow-defer']` enables deferring functions with `DEFER` keyword (default: false)\n- added: `DEFER` feature\n- added: `F.config['allow-debug']` starts a mini debugger\n- added: `res.image_nocache()` alternative to `F.responseImageWithoutCache`\n- added: `req.localize()` performs localization (executes `F.onLocale`)\n- added: `image.limit(type, value)` creates a memory/map/disk/etc. limitation for GM or IM\n- added: `default-image-consumption` for GM/IM memory limitation (default value `30%`)\n- added: `F.useSMTP(smtp, [options], [callback(err)])` rewrites current SMTP settings", "- updated: `F.http('debug/release/test', { debug: true })` can start a mini debugger\n- updated: `F.route()`, `F.websocket()` and `F.file()` --> now returns `FrameworkRoute` instance instead of `Framework` instance (more in docs)\n- updated: `F.load(debug, [types], [path])` supports a new type `service` which enables `F.on('service')`\n- updated: Components (now doesn't have to has `html` body)\n- updated: A component implementation can contain `exports.group = 'name';`\n- updated: framework loads all dependencies in order\n- updated: routes (web/websockets/files) can have an identifier in this form `F.route('/', ['id:custom_dentificator']);\n- updated: `UNINSTALL(type, url/id/fn)` supports new types `web`, `websocket` and `file`, e.g. `UNINSTALL('web', 'id:custom_identifier')`\n- updated: `U.request()`, added a new flag: `raw` (sends raw data)\n- updated: `F.schedule()` returns an identifier\n- updated: `U.clone()` supports `buffer` properties\n- updated: `setTimeout2(name, fn(param), timeout, [limit], [param])` added a new argument `limit` and `param`\n- updated: `F.script()` --> `now` argument (in the script body) is function `now()` which it still returns `new Date()`\n- updated: `F.script(body, value, callback(err, response, param), [param])` --> `param` argument is a helper\n- updated: middleware `next(false)` cancels calling of next middleware and controller\n- updated: `OPERATION(name, value, [callback(err, response, param)], [param])` added a new (helper) argument `param`\n- updated: Mail error handling (added Message instance)\n- updated: `U.request()` add a new flag `noredirect`\n- updated: `F.exists(req, res, [max], callback(next, filename, req, res))` added a new arguments into the callback `req` and `res`\n- updated: `F.memorize()` uses `themeName` as a part of the cache key\n- updated: `debug.js` (missing `startup` directory)", "- renamed: configuration `mail.address.from` for `mail-address-form`\n- renamed: configuration `mail.address.reply` for `mail-address-reply`\n- renamed: configuration `mail.address.copy` for `mail-address-copy`\n- renamed: configuration `mail.smtp` for `mail-smtp`\n- renamed: configuration `mail.smtp-options` for `mail-smtp-options`", "- fixed: config `static-accepts` (it didn't work)\n- fixed: routing with `upload` flag\n- fixed: workers timeout\n- fixed: modificators by George Okojie Davis\n- fixed: NoSQL comparing dates `equal` in `where` condition\n- fixed: a problem with `booting` packages if are used custom paths (by @harry-stot)\n- fixed: JavaScript compression\n- fixed: `allow-compile-style` for inline CSS in views", "- improved: events\n- improved: parsing data from requests\n- improved: mechanism of components\n- improved: performance\n- improved: responding\n- improved: mail attachments", "======= 2.4.0", "- added: `components` more in docs\n- added: `X-Powered-By` header again with option to change/remove it in the framework config `default-xpoweredby : Total.js`\n- added: `UPTODATE(type, url, [options], interval, [callback(err)])` more in docs\n- added: `F.on('uptodate', function(type, name) {})` new event for up-to-date dependencies\n- added: `F.stats.other.mail` with a count of sent emails\n- added: `F.stats.response.errorBuilder` with count of sent ErrorBuilders\n- added: `F.stats.response.image` with count of processed images via GM or IM\n- added: `F.stats.request.schema` with count of request to SchemaBuilder\n- added: `String.prototype.parseTerminal([fields], fn(values, index, count, realIndex), [skipLines], [takeLines])`\n- added: `TRACE(message, [name], [url], [ip])` is an alias for `F.trace()`\n- added: `F.config['trace-console']` (default: `true`) shows tracing on the console\n- added: `F.convert(name, type/function(val))` registers a new convertor (convertors uses QueryParser (GET/POST))\n- added: `F.convert(obj)` performs convertor for an object\n- added: `F.download(url, filename, [callback])` a new alias for `F.snapshot()`\n- added: `$$$([group], name)` for `GETSCHEMA([group], name)`\n- added: configuration files supports options for all dependencies `module#mymodulename (Object) : { name: 'A custom options for dependency' }`\n- added: `U.chunker()` added a new property `chunker.pages` with count of all stored pages\n- added: `U.chunker()` added a new property `chunker.count` with count of all stored items\n- added: `NEWOPERATION(name, fn(error, callback(response), value))` - registers a new operation (same as schemas)\n- added: `OPERATION('name', function(err, response))` - executes an operation (same as schemas)\n- added: `.flac` file extensions\n- added: a new method for `MailMessage` object `message.unsubscribe('your URL or email address')`", "- updated: new error message `The field \"@\" is invalid.`\n- updated: `NOSQL().insert(doc, [unique])`\n- updated: `quicksort` algorithm has been replaced for `shellsort` (increased performance of sorting about 10-15%)\n- updated: `NOSQL().counter.monthly(true, ...)` shows all stats by ID\n- updated: `NOSQL().counter.yearly(true, ...)` shows all stats by ID\n- updated: `dependencies` supports up-to-date features e.g. `module (1 day) : https://......js`\n- updated: `F.findConnections([path])` a `path` argument is optional\n- updated: `U.streamer(beg, [end], function, [skip])` add a new argument `skip`\n- updated: deprecated methods in Node.js v7\n- updated: `String.parseJSON([date])` added `date` argument (date fields will be converted to `datetime`)\n- updated: `F.script()` can compile code to function e.g.: `F.script('next(a + b)')` returns a compiled function\n- updated: `String.captialize([onlyFirst])` add a new argument `onlyFirst`\n- updated: `F.onParseQuery(value, req)` add a new argument `req`\n- updated: `F.onParseXML(value, req)` add a new argument `req`\n- updated: `F.onParseJSON(value, req)` add a new argument `req`\n- updated: `RESTBuilder.url()` without argument returns a current URL\n- updated: `RESTBuilder.exec(function(err, value, response))` when the `error` exists the `value` is still `EMPTYOBJECT`\n- updated: addded a new argument `replacer` to `controller.send(message, [id], [blacklist], [replacer])` and `client.send(message, [raw], [replacer])`", "- removed: behaviours\n- removed: restrictions\n- removed: `TransformBuilder`\n- removed: `F.config['allow-compatibility']` (not used)\n- removed: `controller.date()` method has been useless\n- removed: dynamic view compilation through `.view()` method\n- removed: `contorller.proxy()` in WebSocket controller", "- fixed: JS minificator\n- fixed: global alias `I` for isomorphic code\n- fixed: streaming files in `debug` mode (removed cache)\n- fixed: (critical) a bug with authorization in WebSocket\n- fixed: `nosql_builder.join()` a problem with using `nosql_builder.first()` by @yexing (Xing Ye)\n- fixed: `String.parseInt2()` - a possible NaN value\n- fixed: `String.parseFloat2()` - a possible NaN value\n- fixed: `F.snapshot()`\n- fixed: HTML compression (a fixed problem with HTML comments)\n- fixed: restarting framework (missing cleaning of `F.temporary`)\n- fixed: `U.isDate()` a problem with older dates than 1970, reported by @docgit", "- improved: code\n- improved: memory consumption for static files\n- improved: CSS compression\n- improved: CPU and memory consumption\n- improved: performance\n- improved: updating of `F.datetime`\n- improved: `uninstall` dependencies\n- improved: installing 3rd-party dependencies (framework compares same contents)", "======= 2.3.0", "- added: support for `/workflows` file (more in documentation)\n- added: `ShcemaBuilderEntity.$exec(name, callback)` (more in documentation)\n- added: `SchemaBuilder` supports new types `enum` and `keyvalue`\n- added: `controller.$exec(name, [options], [callback])` (more in documentation)\n- added: a new argument `description` to each SchemaBuilder `set` + `add` method e.g. `.setSave()`, `.addWorkflow()`, etc..\n- added: `SchemaBuilder.meta` contains all registered handlers with their descriptions\n- added: a property `controller.schema`\n- added: `F.viewCompile(body, [model], [layout], [repository], [language])` - dynamic views\n- added: `controller.viewCompile(body, [model], [headers], [partial])` - dynamic views\n- added: `{viewCompile(body, [model])}` - dynamic views\n- added: `Controller` is a global variable for extending prototype\n- added: `F.validators` with Regular Expressions\n- added: View Engine supports `@{continue}` and `@{break}` command for looping\n- added: `URLBuilder.make(fn)`\n- added: `NOSQLMEMORY(dbName, [viewName])` enables in-memory database collection\n- added: NoSQL `nosql.upsert(doc)` inserts a new document where document doesn't exist in DB\n- added: NoSQL `nosql.release()` for releasing of in-memory DB (framework clears unused in-memory databases automatically)\n- added: NoSQL `nosql.scalar(type, dbName, [view])` performs scalar operation by type: `sum`, `min`, `max`, `avg`, `count` or `group`\n- added: NoSQL `nosql.binary.all(callback)` browses all stored files\n- added: NoSQL `nosql.binary.clear(callback)`removes all stored files\n- added: NoSQL `DatabaseBuilder.random()`\n- added: NoSQL `DatabaseBuilder.join(field, dbName, [view])` returns `DatabaseBuilder` with updated `.where(field_JoinedDB, field_currentdb)` method (it supports `.fields()` too)\n- added: NoSQL `DatabaseBuilder.join()` supports scalar operation too, e.g. `nosql.join(...).scalar('count')`\n- added: NoSQL `DatabaseBuilder.scalar(type, [field])` - types: `sum`, `min`, `max`, `avg`, `count` or `group`\n- added: NoSQL `DatabaseBuilder.month(field, [operator], value)` filters `Date` fields according its month number\n- added: NoSQL `DatabaseBuilder.year(field, [operator], value)` filters `Date` fields according its year number\n- added: NoSQL `DatabaseBuilder.day(field, [operator], value)` filters `Date` fields according its day number\n- added: NoSQL events (documents): `insert`, `update`, `modify` and `remove`\n- added: NoSQL events (binary): `insert`, `remove` and `clear`\n- added: NoSQL events (counter): `hit`, `remove` and `clear`\n- added: a new alias `NOBIN(dbName)` witch it returns `NOSQL(dbName).binary` (a binary instance)\n- added: a new alias `NOCOUNTER(dbName)` witch it returns `NOSQL(dbName).counter` (a counter instance)\n- added: `F.kill(signal)` for killing an instance of the framework\n- added: `I` alias for `isomorphic code on server-side and client-side together by hhhaker6@gmail.com <https://github.com/Creeplays>\n- added: `F.script(body, value, callback(err, value))` evaluates script securly in safe scope (more in documentation)\n- added: new alias `SCRIPT()` for `F.script()`\n- added: `HttpFile.rename(filename, [callback(err)])` moves file to another directory", "- updated: `F.on('exit', function(signal) {})` added a signal code\n- updated: SchemaBuilderEntity contains new argument `controller`, e.g. `.setSave(function(error, model, options, callback, controller) { ..`\n- updated: removed all validators of email addresses from FrameworkMail\n- updated: `GETSCHEMA([group], name, [callback(err, schema)])` can wait for a schema\n- updated: `F.localize()` supports modificators as `static` type\n- updated: `F.modify()` supports a new type `static`, it's group of `.html`, `.txt` and `.md` files\n- updated: `U.trim(obj, [clean])` supports a new argument `clean` (default `false`) and when it's `true` and a value is `''` then it sets the value to `undefined`\n- updated: `nosql.update(docToUpdate, [docToInsert])` when the document for updating doesn't exist then database performs insert\n- updated: `nosql.modify(docToUpdate, [docToInsert])` when the document for updating doesn't exist then database performs insert\n- updated: `nosql.binary` stores a creation date as meta info", "- fixed: Image.stream()\n- fixed: global variable `Image` (in a single library)\n- fixed: JavaScript compressor (problem with Regular Expressions)\n- fixed: custom paths in `F.model()` and `F.source()`\n- fixed: NoSQL removing documents (problem with different filters in one queue)\n- fixed: fix view compiler error message\n- fixed: `String.prototype.capitalize`", "- removed: `nosql` doesn't support cache (`DatabaseBuilder.cache` is obsolete)\n- removed: `F.refresh()` the method was useless", "- replaced: `Array.randomize()` for `Array.random()`", "- improved: code", "======= 2.2.0", "- added: `controller.proxy2(url, [callback], [headers], [timeout])` creates a proxy between current request and new URL\n- added: `Image.watermark(filename, [x], [y], [width], [height])` creates a watermark\n- added: hidden hack `res.noCompress = true` disables compilation of `.js` or `.css`\n- added: `RESTBuilder` for creating REST requests (more in docs)\n- added: new config item `allow-cache-snapshot` - to prevent cache when the framework is restarted", "- updated: `SINGLETON(name, [def = {}])` about `def` argument\n- updated: `debug.js` adds timestamps\n- updated: `F.redirect()` can contain a relative URL of file\n- updated: NoSQL embedded parser, dates are parsed as date object\n- updated: `Pagination.next()`, `Pagination.prev()`, `Pagination.last()` and `Pagination.first()` supports new arguments `.html([link_inner_html], [class_name])`\n- updated: `F.worker()` supports packages `F.worker('@eshop/myworker-script')`\n- updated: `FrameworkImage` when the instance contains no command then `.minify()` method is performed automatically for preventing of empty response\n- updated: `F.config['static-accepts']` removed dots from all extensions", "- improved: `@{href(key, value)}` performance\n- improved: Total Package Manager `$ tpm --help`\n- improved: FrameworkImage command building", "- fixed: (critical) NoSQL `nosql.modify()` and problem with updating `undefined` values\n- fixed: (critical) security with GM and IM --> 10000x thanks for Luis Figueiredo <luisf@hexasoftware.com>\n- fixed: `Image.stream()` and `Image.pipe()`", "- renamed: `F.onLocate` renamed to __`F.onLocale`__", "======= 2.1.0", "- added: `F.sitemap_add(string)` for adding entries to sitemap by Martin Smola <https://github.com/molda>\n- added: SchemaBuilderEntity `schema.addHook(name, fn(error, model, options, callback))`\n- added: SchemaBuilderEntity `schema.hook(name, model, [helper], callback)`\n- added: `controller.$hook(name, [helper], callback)`\n- added: `String.parseInt2()` the method searchs number and converts it to integer\n- added: `String.parseFloat2()` the method searchs number and converts it to float\n- added: `@{title2('this content will be added to end of current title')}`\n- added: `String.parseInt2()` the method searchs number and converts it to integer\n- added: `String.parseFloat2()` the method searchs number and converts it to float\n- added: `@{absolute(url, [hostname])}` for importing links with absolute URL by George Okojie Davis <https://github.com/binarygeotech>\n- added: `sitemap_replace(name, title, url)` can change sitemap `title` and `url` onetime\n- added: new JavaScript minificator algorithm because of Douglas Crockford \"Good, not Evil\"\n- added: NoSQL supports counter for e.g. views or downloads, etc., more in documentation\n- added: new routing mechanism `F.mmr(url, action)` for streaming `multipart/x-mixed-replace` types (client-->server)\n- added: `controller.mmr(filename, [stream], callback)` for streaming `multipart/x-mixed-replace` (server-->client)\n- added: `setTimeout2(key, fn, timeout)` resets old and creates a new `setTimeout` according to the `key`\n- added: `clearTimeou2(key)` resets existing timeout\n- added: `dnscache` into the `controller.pipe()` and `F.responsePipe()`\n- added: `CREATE([group], name)` the methods create an empty object according to the schema\n- added: `F.group(flags, fn)` for extending routes (web, websocket, file) flags\n- added: `Number.prototype.filesize([decimals], [type])` formatting file sizes\n- added: `binary` importing CSV `-csv`\n- added: `controller.autodestroy([callback])` only for websocket", "- updated: `framework.view()`, `controller.view()` and `@{view()}` supports `=theme/viewname`\n- updated: sitemap routing supports localization\n- updated: `F.cache.fn(name, fnCache, fnCallback(value, isFromCache))` - added argument `isFromCache`\n- updated: `F.use(name, url, types, [first])` - `first` (default: `false`) argument adds a new middleware to the beginning of a route middleware\n- updated: `String.toSearch()` - removes duplicates characters + better performance\n- updated: `String.decode()` - improves decoding by Tom Spaccialbelli <https://github.com/harry-stot>", "- fixed: (critical) NoSQL views\n- fixed: (critical) view compilation in release mode (problem with just-in-time rendering)\n- fixed: (critical) `F.eval()`\n- fixed: (critical) parsing Date instance as Date instance in SchemaBuilder\n- fixed: `F.resize()` additional path `~`\n- fixed: `controller.memorize()` threw a timeout when the action contains some error in the memorize scope\n- fixed: `F.sitemap()` fixed problem with `me` argument\n- fixed: SchemaBuilderEntity preparing and validation\n- fixed: QuickSort algorithm (problem with dates)\n- fixed: `TRY()` scope\n- fixed: problem with resources in views\n- fixed: CSS compressor\n- fixed: CORS\n- fixed: problem with SUCCESS() and async schemas\n- fixed: killing the process\n- fixed: HTML compressor in views", "======= 2.0.1", "- added: binary supports webserver `totaljs 8000` starts webserver on 8000 port and the current directory will be a public directory\n- added: configuration supports new subtype (`env` or `environment`) for binding values from `process.env`\n- added: `SchemaBuilderEntity.$next(type, [name], helper)` --> adds a new operation (type: `workflow`, `transform`, `operation`, `save`, `read`, `query`, `remove`) to async list as next step\n- added: `SchemaBuilderEntity.$push(type, [name], helper)` --> adds a new operation (type: `workflow`, `transform`, `operation`, `save`, `read`, `query`, `remove`) to async list as last step\n- added: `SchemaBuilderEntity.$index(index)` can changed `obj.$async()` index (the index can be string e.g. `+1` or `-1`)\n- added: `SchemaBuilderEntity.$callback(fn)` can changed `obj.$async()` callback\n- added: `SchemaBuilderEntity.$repository(name, [value])` can get / set temporary value", "- added: `SchemaBuilderEntity.$output()` sets the current `callback(value)` as output/result for `obj.$async(function(err, output))`", "- updated: when the config contains `directory-temp` with empty value then the framework uses system temporary directory\n- updated: `U.reduce()` supports array", "- fixed: binary `totaljs`, fixed problem with creating localized texts\n- fixed: `F.responseFile()` problem with cached filename, extension was broken when the framework reads the file from cache\n- fixed: preparing values with subtype for array in SchemaBuilder\n- fixed: generation UID\n- fixed: problem with uninstalling middleware\n- fixed: email validation, a problem with e.g. `blabla@somedomain.business` by @VarunBatraIT", "- improved: view engine rendering\n- improved: view engine memory consumption", "======= 2.0.0", "- added: new NoSQL version v4.0.0 is fully optimized for total.js\n- added: `controller.invalid([status])` creates the ErrorBuilder instance and it responds in the next tick\n- added: `controller.sitemap_url([id])` returns an URL from the sitemap\n- added: `controller.sitemap_name([id])` returns a name/title from the sitemap\n- added: `controller.sitemap_change(id, property, newvalue)` can change a current value in the sitemap\n- added: `controller.sitemap_navigation([parent], [langauge])` can get list of all items according to the parent\n- added: `@{sitemap_url([id], [arg1], [arg2], [argN])}` returns an URL from the sitemap\n- added: `@{sitemap_name([id], [arg1], [arg2], [argN])}` returns a name/title from the sitemap\n- added: `@{sitemap_change(id, property, newvalue)}` can change a current value in the sitemap\n- added: `@{sitemap_navigation([parent], [language])` can get list of all items according to the parent\n- added: `/startup/` all scripts in this directory are executed only one (then are renamed automatically)\n- added: `F.route()` supports a new flag: `cors` (creates a cors route) and `credentials` (enables cookies for cors)\n- added: `ErrorBuilder.plain()` returns all errors as a simple string\n- added: `Array.findItem()` alias to `Array.find()`\n- added: `Number.async(fn(index, next), callback)` for asynchronous operations\n- added: `UID()` for generating unique identifiers (contains minimum 18 chars)\n- added: `F.restart()` for restarting app\n- added: `F.on('restart')`\n- added: quicksort algorithm for sorting arrays\n- added: `Array.quicksort(property_name, [asc], [maxlength])` for sorting arrays\n- added: `String.removeTags()` by @harry-stot\n- added: F.nosql(name) + NOSQL(name) --> alias for NoSQL embedded database (it can be used with e.g. SQL Agent)\n- added: modificators can handle `INSTALL('view', ...)`\n- added: `String.isPhone()` for phone number validation\n- added: `String.isUID()` for UID() validation\n- added: `String.isZIP()`\n- added: `Pagination.html(max, format)` returns `String`\n- added: `Pagination.json(max, format)` returns `String`\n- added: new schemabuilder types `Email` (string, maxlength 120), `Phone` (string, maxlength 20), `Zip` (string, maxlength 10), `Capitalize` (string), `Lowerize` (string), `Upperize` (string), `UID` (string, minlength 18, maxlength 20), `Url` (string, maxlength 500), `JSON` (string)\n- added: `SchemaBuilderEntity.fields` and it contains all field names in array.\n- added: `Mail.send(smtp, options, messages, [callback])` messages must be array\n- added: `Mail.send2(messages, [callback])` sends messages according to the framework configuration\n- added: `Mail.try(smtp, options, callback)` tries to open a SMTP\n- added: `F.datetime` contains current datetime and each 1 minute is the value increased\n- added: `F.stats.other.restart` contains a new property with count of restarting\n- added: `F.config.trace` for enable/disable tracing, `Boolean`, in a debug mode: `true`, release mode: `false`\n- added: `F.trace(message, [name], [uri], [ip])`\n- added: `controller.trace(message)`\n- added: `req.split` contains splitted url\n- added: `F.touch(url/req)` for clearing internal cache of cached static files (it works only in release mode)\n- added: `F.path.exists(path, callback(exist, size, isFile))` for check of existing file\n- added: `U.chunker(name, [max])` creates the chunker (for streaming some items)\n- added: `F.worker2(name, [args], [callback], [timeout])`\n- added: `SchemaBuilderEntity.allow('fieldname1', 'fieldnameN')` - allows other keys out of defined fields\n- added: `global.EMPTYOBJECT`\n- added: `global.EMPTYARRAY`\n- added: `global.SINGLETON(name)` returns a singleton object instance\n- added: `controller.referrer` returns a value from `req.headers['referer']`\n- added: `controller.author(value)` can change `<meta name=\"author\"`\n- added: `@{author(value)}` can change `<meta name=\"author\"`\n- added: view engine supports looping with objects `@{foreach m in model} key: @{m.key} and value: @{m.value} @{end}`", "- updated: subdomain routing supports wildcard routing `F.route('[*]/', 'homepage')` (`F.websocket()` is supported too)\n- updated: `F.route(url, ...)` - `url`can be String Array with multiple relative paths by @Harry-Stot\n- updated: `F.file()` supports flags instead of middleware and the flags supports extensions `['.jpg', '.png']`. The `name` argument has been removed.\n- updated: `F.localize()` supports flags and the `name` argument has been removed\n- updated: `F.sitemap()` returns object with a new field: `wildcard: {Boolean}`\n- updated: `F.problem()`, `F.change()`, `controller.problem()` and `controller.change()` write logs to the file\n- updated: `F.mail()` and `controller.mail()` subject is translated according to the language\n- updated: `F.file(fnValidation/relative_path, fnExecute, [flags])` the file routing is completely changed\n- updated: `export.booting` can contain `root` attribute for `package` applications\n- updated: `Array.orderBy()` added quicksort algorithm\n- updated: `Date.format()` supports day names `ddd` (short) and `dddd` (full)\n- updated: `String.removeDiacritics()` supports multiple languages (by @Harry-Slot)\n- updated: (IMPORTANT) `U.getExtension(filename)` --> returns extension without `.` dot\n- updated: (IMPORTANT) `F.resize(url, action(image), [flags])` new resize routing\n- updated: `F.resize()` flags can contain http/https `path` e.g. `F.resize('/img/*.*', (image) => image.minify(), ['https://www.totaljs.com/img/']);`\n- updated: `U.GUID()` supports better charset by Guy Fraser\n- updated: `Date.add(number)` supports number increase/decrease in milliseconds\n- updated: `U.send(name, stream, url, callback, [cookies], [headers], [method], [timeout])` supports cookies and timeout\n- updated: `U.request()` supports a new flag `< 200` (kB), it means that the method stores a content with maxixmum size 200 kB.\n- updated: `ErrorBuilder` instance contains a new property `instance.unexpected` when is `instance.push()` a classic Error's instance.\n- updated: configuration files + resources support types like String, Number, Array, Date, etc. via `key (type) : value`\n- updated: `F.use(name, [url], [types])` - now supports new attributes `url`, and `types`", "- fixed: `Websocket.destroy()`\n- fixed: Too many open files with `F.log()` and `F.logger()`\n- fixed: `String.isJSON()` the problem with `\\n` character\n- fixed: `FrameworkImage.save()` problem with streams\n- fixed: `CLEANUP(stream)` method\n- fixed: `controller.memorize()` problem with `controller.content()`\n- fixed: `multipart/form-data` parser\n- fixed: `Array.async()` without arguments\n- fixed: view inline helpers\n- fixed: `FrameworkImage.save()` doens't work when it doesn't contain any operation\n- fixed: Windows paths\n- fixed: problem with `websocket.destroy()`\n- fixed: `F.cors()`\n- fixed: WebSocket initialization (critical)\n- fixed: Mail sender (problem with ZOHO SMTP)\n- fixed: `Number.add()` problem with percentage\n- fixed: `U.isDate()` by Guy Fraser\n- fixed: `U.parseXML` problem with `CDATA`\n- fixed: `U.join()` problem with Windows path by Martin Smola\n- fixed: uploading files (problem with unexpected closed requests)\n- fixed: `F.assert()` a problem with external URL address", "- renamed: event `route-add` to `route`\n- renamed: `F.versionNode` to `F.version_node`", "- removed: (IMPORTANT) `X-Powered-By` header\n- removed: `SCHEMA()`\n- removed: composer from `SchemaBuilderEntity`\n- removed: rules from `SchemaBuilderEntity`\n- removed: obsolete code\n- removed: `controller.async()`\n- removed: `framework.async()`\n- removed: `Utils.validate()`\n- removed: `Utils.isEmail()`\n- removed: `Utils.isURL()`\n- removed: `Utils.isValid()`\n- removed: `Utils.isNullOrEmpty()`\n- removed: `controller.global` property by Guy Fraser (a problem with referrencing)\n- removed: `controller.database()`, use `F.database()`\n- removed: `controller.functions()`\n- removed: `controller.models()`", "- improved: Controller initialization by Guy Fraser\n- improved: SMTP sender\n- improved: redirecting\n- improved: Array.orderBy(), added quicksort algorithm\n- improved: ErrorBuilder\n- improved: `WebSocket.send()` for JSON communication\n- improved: code (a lot)\n- improved: preparing `SchemaBuilderEntity`\n- improved: performance\n- improved: a lot of code by Guy Fraser", "======= 1.9.7", "- added: `F.web()` --> alias to F.route()\n- added: `F.cors(url, flags, credentials)`\n- added: `config['default-response-maxage']`, default value `11111111`\n- added: `U.get(obj, path)` reads a value from `obj` by path\n- added: `U.set(obj, path, value)` sets a value into `obj` by path\n- added: (IMPORTANT) `config['default-root']` can replace root relative path\n- added: `FrameworkImage` --> `instance.make(function(image) {})`\n- added: `FrameworkImage` supports middleware `FrameworkImage.middleware(extension, fn)`\n- added: `controller.$get([helper], callback)` or alias `controller.$read([helper], callback)` - schema must be defined in the route\n- added: `controller.$remove([helper], callback)` - schema must be defined in the route\n- added: `controller.$save([helper], callback)` - schema must be defined in the route\n- added: `controller.$query([helper], callback)` - schema must be defined in the route\n- added: `controller.$transform(name, [helper], callback)` - schema must be defined in the route\n- added: `controller.$workflow([name, [helper], callback)` - schema must be defined in the route\n- added: `controller.$operation(name, [helper], callback)` - schema must be defined in the route\n- added: `controller.$async(callback, [index])` - schema must be defined in the route\n- added: new `F.route()` flag `binary` (works only with `raw` flag)\n- added: `U.ls2()` --> returns additional information about files (stat Object);\n- added: `Pagination` is a global variable\n- added: `SchemaBuilder.workflow2(name, options, callback)` skips preparing and validation\n- added: `SchemaBuilder.transform2(name, options, callback)` skips preparing and validation\n- added: `SchemaBuilder.operation2(name, options, callback)` skips preparing and validation\n- added: `ErrorBuilder.exception(message)` - adds a new exception message\n- added: `F.findConnection()` finds a websocket connection\n- added: `F.findConnections()` finds websocket connections", "- updated: (IMPORTANT) Array.async([NEW: threadCount (Number)], [callback]) supports `threads`\n- updated: (IMPORTANT) Array.wait(onItem(item, index), [callback], [threadCount]) supports `threads`\n- updated: (IMPORTANT) U.streamer(beg, [end], callback) --> supports \"end\" delimiter\n- updated: Date.format(format, [resource_name]) supports name of months via `MMM` (short) and `MMMM` (full)\n- updated: Resources support months e.g. `January : Január`\n- updated: `F.merge()` supports directories, e.g. `F.merge('app.js', '/js/*.js')`\n- updated: NoSQL embeddded version\n- updated: `U.ls()` --> [filter] can be `string` or `RegExp`\n- updated: `@{meta(title, [description], [keywords], [image])}` and `@{keywords(value)}` keywords can be String Array\n- updated: `@{section name}` can be used in the view more times\n- updated: `U.request()` flags supports `number` for timeout and encoding `utf8`, `ascii`, etc.\n- updated: `F.restfull()` each action support SchemaBuilder", "- fixed: (IMPORTANT) Expires headers - problem with Russian timezone, reported by [Андрей Владимирович](https://github.com/anddesigner)\n- fixed: (IMPORTANT) SchemaBuilder validation\n- fixed: (IMPORTANT) view caching\n- fixed: (IMPORTANT) U.keywords()\n- fixed: @{checkbox} value binding\n- fixed: dynamic views translator caching\n- fixed: URL search string in `F.redirect()` (doesn't work on local relative address)\n- fixed: binary / executable for Windows\n- fixed: SUCCESS()\n- fixed: Schema Validation is performed after F.onAuthorize().\n- fixed: checking of maximum request length\n- fixed: regexp routing\n- fixed: F.restrictions.allow()\n- fixed: `U.request()` and fixed `head` method, callback returns headers when is `head` method used\n- fixed: Pagination by DusanDragula\n- fixed: View inline helpers - reported by [Андрей Владимирович](https://github.com/anddesigner)\n- fixed: `Array.findIndex` - reported by [Liao San-Kai](https://github.com/liaosankai)\n- fixed: `WebSocket.send()` problem with `[id]` and `[blacklist]`", "- improved: performance in `Expires Header`", "======= 1.9.6", "- added: MailMessage.manually() and removes auto-sending mail --> works only with `F.mail()` and `controller.Mail()`.\n- added: view engine supports now `@{'route-to-static-file.jpg'}`\n- added: `U.clone(obj, [skip])`\n- added: `U.parseTheme(path)` --> parses theme name\n- added: `@{href}` or `@{href(obj)}` or `@{href(key, value)}` --> query string manipulation (more in documentation)\n- added: `.jsx` content-type\n- added: `robot` flag into the routing (for search engines)\n- added: property `req.robot`\n- added: property `controller.robot`\n- added: property `controller.mobile`\n- added: support for default theme name, e.g. `=?/index` (the framework replaces `?` for `default-theme`)\n- added: String.localeCompare2(value) --> same as localeCompare() but this method works with diacritics\n- added: F.register(filename); --> the methods registers new e.g. resource (it solves the problem with resources in packages)", "- updated: (IMPORTANT) controller.isSecure was renamed to controller.secured\n- updated: (IMPORTANT) req.isSecure was renamed to req.secured\n- updated: (IMPORTANT) Array.wait(onItem, onCallback, [NEW: threadCount (Number) or removeItemFromArray (Boolean)]) supports `threads`\n- updated: `F.mail()` supports themes with view nema like this `=default/someview'`\n- updated: `@{import()}` supports movies and images\n- updated: `@{import()}` can contain schema name in the path like this `=YOURTHEME/somefile.js`\n- updated: `F.route('/', '=themeName/viewname')` supports inline themes\n- updated: `F.resize()` added new options parameter --> `direction` (top, center or bottom)\n- updated: SUCCESS(), now supports function as first argument and the method returns wrapped function too", "- fixed: problem with views path (`./some/path/in/hdd/` routed view anywhere)\n- fixed: static file routing (`@{import()}`, `@{routeScript}`, etc..)\n- fixed: miss `Sec-WebSocket-Protocol` by Liao San-Kai\n- fixed: `MailMessage.send()` --> `options` argument is optional\n- fixed: problem with UTF8 in U.request() by Ivan Marchukov\n- fixed: WebSocket parser\n- fixed: WebSocket closing message (problem with UTF8)\n- fixed: U.getExtension()\n- fixed: problem with WebSocket `destroy`\n- fixed: sync2() doesn't work\n- fixed: problem with themes in controller.memorize()\n- fixed: problem with timeout in controller.memorize()\n- fixed: fixed unitialized memory block in `mail` (by ChALkeR)\n- fixed: problem with static files (directories with extensions)", "- removed: all `controller.current...()` methods\n- removed: all `@{current...()}` methods\n- removed: (IMPORTANT) `framework.fs`\n- removed: (IMPORTANT) `controller.fs`", "- improved: (IMPORTANT) SchemaBuilder by Ivan Marchukov\n- improved: (IMPORTANT) ViewEngine performance about 15%\n- improved: request cookie parsing", "======= 1.9.5", "I had to skip v1.9.4 version because of NPM (my mistake).", "- added: (IMPORTANT) new feature: THEMES\n- added: `@{theme}` --> return String\n- added: `F.onTheme` delegate\n- added: `controller.theme(theme_name)` --> select theme;\n- added: `config['default-theme']`\n- added: `U.keywords(content, [forSearch], [alternative(true|false|soundex)], [max_count(200)], [max_length(20)], [min_length(2)]);`\n- added: `String.prototype.keywords([forSearch], [alternative(true|false|soundex)], [max_count(200)], [max_length(20)], [min_length(2)])`\n- added: `String.prototype.soundex()`\n- added: `F.wait(name, [enable])` the server waits for pending task and it responds via 503 status code\n- added: `U.parseQuery()` and `String.parseQuery()`\n- added: `U.join(path1, path2, path3)`\n- added: `U.getName(path)`\n- added: `F.on('error400')`\n- added: `F.on('error401')`\n- added: `F.on('error403')`\n- added: `F.on('error404')`\n- added: `F.on('error408')`\n- added: `F.on('error431')`", "- updated: (IMPORTANT) F.onAuthorization() was renamed to F.onAuthorize()\n- updated: `Date.format()` supports `w` and `ww` for week number\n- updated: `Date.add()` supports `w`, `ww`, `week`, `weeks`\n- updated: MailMessage supports display name `mail.from('Name <vali@demail>');`\n- updated: MailMessage supports display name `mail.to('Name <vali@demail>');`\n- updated: MailMessage supports display name `mail.to(email, [name], [clear]);`\n- updated: MailMessage supports display name `mail.cc('Name <vali@demail>');`\n- updated: MailMessage supports display name `mail.cc(email, [name], [clear]);`\n- updated: U.resolve(url, [callback]) --> `callback` is optional", "- fixed: HTTP cache for HTML 5 offline manifest files\n- fixed: async() error handling\n- fixed: NoSQL embedded paths\n- fixed: problem with empty SMTP options\n- fixed: ErrorBuilder default transformation to JSON\n- fixed: Error handling\n- fixed: SchemaBuilder request auto-validation\n- fixed: String.isJSON()\n- fixed: F.responsePipe() --> problem with transmitted headers\n- fixed: evaluating of @{helpers.helper_name()}\n- fixed: HTML minification of UTF8 characters\n- fixed: U.isEqual()\n- fixed: FrameworkImage.save() in Windows by LiaoTzukai\n- fixed: SchemaBuilder prefix by Dušan Dragula", "- improved performance of the response\n- improved total performance\n- improved view engine performance", "======= 1.9.3", "- added: (IMPORTANT) merging supports BLOCKS (.js,.css), e.g. F.merge('merge.js', 'fileA.js#management,common', 'fileB.js#management')\n- added: (IMPORTANT) a route with schema binding can contain filter e.g. `*Schema#update` or `*Group/Schema#create` --> the framework validates only fields by filter\n- added: TRANSFORM([transform], obj)\n- added: NEWTRANSFORM(name, fn, [isDefault]) --> alias for TransformBuilder.addTransform()\n- added: packages can be stored as directories (recommended for debug mode only)\n- added: F.localize(name, url, [middleware], [options], [minify]) --> minify argument\n- added: email supports calendar (.ics) request sending\n- added: SchemaBuilderEntity.make(function(schema))\n- added: F.install() supports packages mapping\n- added: Support for unicode routing\n- added: Packages can be loaded in framework structure (/controllers/, /modules/) `exports.booting = true`\n- added: route flags can contains object --> the object is an additional options for middleware\n- added: Utils.btoa(str) --> returns base64\n- added: Utils.atob(str) --> returns binary\n- added: global.TRY(fnScope, [fnError]) --> creates safe scope (more in documentation)\n- added: Utils.getExtension(filename)\n- added: @{head} can be imported as @{import('head')}\n- added: @{meta} can be imported as @{import('meta')}\n- added: controller.cookie('KEY') --> for reading\n- added: controller.cookie('KEY', 'VALUE', expire, [options]) --> for writting\n- added: framework.onParseQuery(function(value)) --> for parsing values from the requests\n- added: framework.onParseXML(function(value)) --> for parsing values from the requests\n- added: framework.onParseJSON(function(value)) --> for parsing values from the requests", "- updated: (IMPORTANT) F.onValidation() was renamed to F.onValidate()\n- updated: (IMPORTANT) SchemaBuilderEntity.onValidation() was renamed to SchemaBuilderEntity.onValidate()\n- updated: (IMPORTANT) SchemaBuilderEntity.setValidation() was renamed to SchemaBuilderEntity.setValidate()\n- updated: CSS compressor removes comments\n- updated: F.restrictions.allow('IP') --> does not have to be full IP\n- updated: F.restrictions.disallow('IP') --> does not have to be full IP\n- updated: String.startsWith() and String.endsWith() according to ES6 but with the backward compatibility\n- updated: String.parseDate() supports JSON format and classic date serialization\n- updated: U.request() --> response always returns string\n- updated: debug.js --> now watchs packages", "- fixed: framework starting path (fixed problem with PM2 module)\n- fixed: controller.memorize() - prevention for multiple requests\n- fixed: routing (POST request without content-type is considered as `application/x-www-form-urlencoded`)\n- fixed: sync2()\n- fixed: U.minifyHTML() - now compresses JS and CSS in HTML\n- fixed: Async.cancel()\n- fixed: email attachments\n- fixed: throwing error in global middleware\n- fixed: Pagination.last()\n- fixed: CSS auto-vendor-prefixes\n- fixed: `tpm` binary (bug in creating packages on Windows)\n- fixed: controller generators\n- fixed: F.install() --> problem with names via URL import\n- fixed: F.map() on Windows (problem with paths)\n- fixed: HTML compression in views\n- fixed: U.Async() object (problem with waitingFor)\n- fixed: F.map(), problem in Windows\n- fixed: CLEANUP(stream, [callback]);\n- fixed: HTTP CACHE", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/blocks", "======= 1.9.2 (HOTFIX)", "- added: support for node +v4.0.0", "- updated: F.load(.., ..., [path]) path arguments supports '..' for parent directory\n- updated: PageBuilder (+added properties: `nextPage`, `prevPage`, `firstPage`, `lastPage`) by [Liao San-Kai](https://github.com/liaosankai)\n- updated: NoSQL", "- fixed: U.request() --> `DELETE` method has `application/x-www-form-urlencoded` as default content type\n- fixed: routing with `delete` flag\n- fixed: F.worker()\n- fixed: WebSocket event handlers\n- fixed: sync2()\n- fixed: @{place}\n- fixed: @{section}\n- fixed: controller.memorize() - problem with different layouts", "- improve: routing performance with F.onAuthorization()", "======= 1.9.1 (HOTFIX)", "- added: new sitemap system\n- added: a default schema validator is F.onValidation()\n- added: ErrorBuilder.setContentType() --> default application/json\n- added: View engine supports `else if`\n- added: U.parseBoolean(val, [def])\n- added: F.backup(filename, path, [callback], [filter]) --> backup some path to one file\n- added: F.restore(filename, target, [callback], [filter]) --> restore backup file (but not evaluating)\n- added: MailMessage supports custom headers `message.headers = { key: 'value' }`\n- added: @{notranslate} --> disables view translation\n- added: F.mode('debug') or F.mode('release') --> changes a mode of the framework\n- added: EACHSCHEMA([group], prepare(group, name, schema))", "- updated: MailMessage.bcc(email, [clear]) --> added clear\n- updated: MailMessage.cc(email, [clear]) --> added clear\n- updated: MailMessage.reply(email, [clear]) --> added clear", "- fixed: uploading files\n- fixed: prevention for mail double callback calling (by Andrea Sessa)\n- fixed: worker messaging\n- fixed: problem with schema parser (by Andrea Sessa)\n- fixed: F.load() --> \"versions\" is configurable\n- fixed: \"raw\" receiving of data\n- fixed: U.request(), the problem with default method\n- fixed: F.exists() - problem with URL query string\n- fixed: framework startup path\n- fixed: Date.format()\n- fixed: Assertion Testing", "======= 1.9.0", "- added: (IMPORTANT) ISOMORPHIC using\n- added: (IMPORTANT) new flag `mobile` (mobile routing), you can create a route to mobile device\n- added: (IMPORTANT) new flag `delay` for long time operations (it removes timeout)\n- added: readonly `req.mobile` -> returns `boolean`\n- added: new view tag: @{mobile} –> returns `boolean`\n- added: new view tag: @{isomorphic} –> returns `Object` with isomorphic objects\n- added: `config['disable-clear-temporary-directory'] = false` (after start)\n- added: `config['allow-compatibility'] = false` - a backward compatibility mode\n- added: `config['default-timezone']`\n- added: `config['directory-isomorphic']`\n- added: `config['directory-private']`\n- added: `F.path.private([filename])`\n- added: `F.path.isomorphic([filename])`\n- added: `Controller.ping()` for WebSocket\n- added: `global.DB()` --> same as `global.DATABASE()`\n- added: `global.isomorphic` --> returns `framework.isomorphic` --> returns isomorphic objects\n- added: `global.is_client` and `global.is_server` for isomorphic\n- added: cache for HTTP routing\n- added: RegExp routing `F.route('/{/^\\\\d+$/}', ...)`\n- added: `F.responseBinary(req, res, contentType, buffer, [type], [download], [headers])`\n- added: `SchemaBuilderEntity.filter(custom, [model], [reverse])`\n- added: `SchemaBuilderEntity.trim = true`(enable/disable trim strings (default: true))\n- added: `Number.prototype.add(value, [decimals])` -> supports percentage\n- added: `Date.prototype.toUTC([ticksOnly])`\n- added: `Date.prototype.extend()` -> extend current datetime about new date or time (more in documentation)\n- added: `F.stats.request.mobile`, `F.stats.request.desktop`\n- added: `res.setHeader('Vary', 'Accept-Encoding, User-Agent')` for same url addresses and different devices (desktop vs mobile)\n- added: binary - `total --translatecsv`\n- added: controller.jsonp(method_name, obj, [headers], [beautify], [replacer]);\n- added: CSS variables likes sass, example: `$color: red;`\n- added: CSS nesting\n- added: modificators for dynamic modification before compilation: views, styles and scripts\n- added: TransformBuilder\n- added: F.load(debug, load_types, [path]);\n- added: F.isWorker (is true when is called F.load())\n- added: F.isCluster (is true when the framework is running in the cluster)\n- added: F.logmail(address, [subject], body, [callback]) --> send e-mail message as plain text\n- added: Array.unique([property]) by Andrea Sessa\n- added: Array.pair(array, property, fn(itemA, itemB), [remove]) - pair arrays\n- added: String.base64ToBuffer();\n- added: terminal -> `tpm unpack [package_name] [optional: target_directory]`\n- added: versions is applied to raw HTML\n- added: versions supports auto-mapping\n- added: sync2(), e.g. sync2(fn), diff with v1: sync(fn)() and v2: sync2(fn)\n- added: \"dependencies\" file for installing dependencies (modules, packages, etc.)\n- added: @{nocompress html}, @{nocompress js}, @{nocompress css}, @{nocompress all}\n- added: req.authorize(callback(err, userprofile, isAuthorized))\n- added: res.content(code, body, type, [compress]) -> alias for F.responseContent()\n- added: F.localize(name, path, [middleware], [options]) - auto translating static files\n- added: F.listener(req, res) -> for multiple server listeners\n- added: F.restful(url, flags, onQuery, onGet, onSave, onDelete) -> creates routing\n- added: F.onSchema(req, group, name, callback(err, body)) -> for custom schemas\n- added: @{import(filename1, filename2, filenameN)}\n- added: SchemaBuilderEntity.setError(function(error, model, type, name));\n- added: F.snapshot(url, filename, [callback]);\n- added: CLEANUP(stream, [callback]) - clean up readable streams\n- added: configs directory\n- added: F.behaviour(url, flags);\n- added: behaviour: disable-measuring (default: false)\n- added: behaviour: disable-middleware (default: false)", "- updated: (IMPORTANT) routing: `json` flag is not required for receiving incomming data as JSON\n- updated: `F.mail(address, subject, view, [model], [callback], [language])` added language\n- updated: `F.view(name, model, [layout], [repository], [language])` added language\n- updated: `F.route(url, ...)`, `F.websocket(url, ...)` --> URL can be function(url, req, [flags])\n- updated: `versions` affects F.map() and F.merge()\n- updated: `controller.mail(address, subject, view, [model], [callback], [language])` added language\n- updated: `config['allow-performance']` is set to true\n- updated: (IMPORTANT) `F.map(url, filename/directory, [filter])` supports mapping directories\n- updated: (IMPORTANT) arguments order `SchemaBuilderEntity.setValidate(function(name, value, path, model, schema){})`\n- updated: (IMPORTANT) `U.extend(target, source, [rewrite]);` --> rewrite is by default: __true__\n- updated: `SchemaBuilderEntity.setPrepare(function(name, value, index, model){})` --> __model__ is new\n- updated: `SchemaBuilderEntity.define(name, value, required, [custom])` --> __custom__ is new\n- updated: HTML compressor\n- updated: favicon `(removed rel=\"icon\")`\n- updated: binary `tpm create [package] [directory]` (added argument [package], [directory])\n- updated: better handling middleware errors and added prevention of \"memory leak\"\n- updated: (IMPORTANT): Websocket ping is set to 3 minutes\n- updated: framework responds for bad requests with HTTP 403\n- updated: Mail (added support for Office365)\n- updated: Date.prototype.add() supports e.g. Date.prototype.add('25 days')\n- updated: String.prototype.params() -> supports double \"{{\"\n- updated: F.schedule(date, [repeat], fn) --> added [repeat]\n- updated: `F.responseStream()` and `controller.stream()` added [nocompress] argument\n- updated: binary `tpm` supports install package from different URL", "- removed: XSS check", "- fixed: `controller.binary(buffer, contentType, [download], [headers])`\n- fixed: routing `DELETE`\n- fixed: `binary` (creating empty-project, bad record with smtp options)\n- fixed: calling generator action\n- fixed: `binary --translate` (filenames)\n- fixed: SchemaBuilderEntity prepare (problem with nullable Boolean)\n- fixed: (IMPORTANT) 431 system route\n- fixed: F.log(), F.logger() –> problem with objects, reported by Nikita Shmidt\n- fixed: Number formatting (problem with negative numbers)", "- improved: performance +15%\n- improved: code optimalization\n- improved: Date.prototype.format()\n- improved: String.prototype.format()\n- improved: Number.prototype.pluralize()\n- improved: view debugging", "__IMPORTANT:__\n`exports.install = function(framework) {}` framework variable is removed but with backward compatibility (`config['allow-compatibility']`).", "======= 1.8.0", "source-code: \"tabs\" instead of \"spaces\"", "- added: SchemaBuilderEntity->setPrepare(function(name, value, index))\n- added: SchemaBuilderEntity–>setPrefix(prefix)\n- added: SchemaBuilderEntity->setResource(resourcename)\n- added: auto-trim strings in SchemaBuilderEntity\n- added: Controller.route;\n- added: ErrorBuilder is a global class\n- added: F.on('upload-begin', function(req, file) {})\n- added: F.on('upload-end', function(req, file) {})\n- added: config['static-accepts']: woff2\n- added: F.logger(filename, arg1, ...), controller.logger(...), @{logger(...)}\n- added: (IMPORTANT) F.exists(req, res, callback(next, filename))\n- added: callback: F.responseFile(), controller.file(), response.file()\n- added: callback: F.responseImage(), controller.image(), response.image()\n- added: callback: F.responseImageWithoutCache()\n- added: callback: F.responseStream(), controller.stream(), response.stream()\n- added: callback: F.responseStatic(), response.continue()\n- added: Array.prototype.findIndex(cb, [value]) returns Number\n- added: Array.prototype.toObject([name]) returns Object\n- added: Array.prototype.limit(max, fn(items, next), [callback])\n- added: Array.prototype.compare(propName, arr, comparer)\n- added: Image.geometry(w, h, options)\n- added: Image.thumbnail(w, h, options)\n- added: Image.filter(type)\n- added: `config['default-maximum-file-descriptors'] = 0` (0 = the watcher is disabled)\n- added: `config['default-interval-clear-dnscache'] = 2880` for clearing DNS cache of Utils.request(), Utils.download()\n- added: Utils.resolve(url, callback(err, uri)) DNS cache\n- added: Utils.clearDNS() clears DNS cache\n- added: Utils.isObject()\n- added: String.prototype.parseJSON()\n- added: Date.prototype.diff([date], type)\n- added: framework.onCompileView(name, content, model)\n- added: framework.on('cache-set', function(name, value, expire))\n- added: `@{compile handlerbars}CONTENT TO COMPILE@{end}`\n- added: `@{compile}CONTENT TO COMPILE@{end}`\n- added: Utils.streamer(delimiter, function(value, index)) returns function\n- added: HEAD method support for (controller.json(), .view(), .plain(), .file(), .stream())\n- added: global.NEWSCHEMA([group], name) for creating new schemas (more in docs)\n- added: global.GETSCHEMA([group], name) for getting new schemas (more in docs)\n- added: global.FINISHED(res/stream, callback) --> real end of the stream\n- added: global.DESTROY(stream) --> destroys the stream\n- added: (IMPORTANT) node.js generators for the routes", "- updated: (IMPORTANT): for evaluation multiple roles in routing (@role) framework validates only one role\n- updated: GZIP compression for static files (added .md, .json)\n- updated: request schema parser and XML parser -> better handling errors\n- updated: wrapped decodeURIComponent for prevention of parsing\n- updated: removed HTTP cache in DEBUG mode\n- updated: Image.miniature(w,h,color,[filter]) --> added filter\n- updated: binary supports translation files `--translate my-localization.txt`\n- updated: framework.mail() --> returns MailMessage\n- updated: controller.mail() --> returns MailMessage\n- updated: SchemaBuilderEntity.$async(callback, [return-only-this-index])\n- updated: translation @(#KEY) (direct reading) or @(TEXT TO TRANSLATE) (hash reading)\n- updated: Utils.request(), Utils.download() supports `dnscache` flag for caching host IP\n- updated: SchemaBuilderEntity.validation()\n- updated: F.cache.set(key, value, expire, [sync])\n- updated: NoSQL\n- updated: (IMPORTANT): Websocket ping is disabled by default", "- fixed: Image.resize()\n- fixed: F.usage() --> fixed queue pendings\n- fixed: (CRITICAL) SchemaBuilderEntity preparing (problem with prototypes)\n- fixed: (CRITICAL) a package or module installation from the URL address\n- fixed: (CRITICAL) response content-length\n- fixed: framework.redirect()\n- fixed: HTTP cache (added longer time)\n- fixed: auto JSON parsing in `json` request\n- fixed: Pagination.last() (Nikita Shmidt)\n- fixed: loading packages\n- fixed: callback error in MailMessage\n- fixed: TPM restore package\n- fixed: Utils.request() --> double calling of callback()\n- fixed: routing with `get` and `json` flag together", "- replaced: (IMPORTANT) `uri` to `url` in F.problems, F.changes, F.errors (saves memory)", "- improved: U.removeDiacritics() -> increase about 30%\n- improved: handling files\n- improved: auto-image-resizer (routes)\n- improved: Image.miniature() -> increase about 50%\n- improved: U.queue()\n- improved: (IMPORTANT) SchemaBuilder validation and preparation", "__GENERATORS__:", "- added: Image.$$save(filename, [writer])\n- added: Image.$$measure();\n- added: Image.$$identify();\n- added: Utils.$$request();\n- added: Utils.$$download();\n- added: Utils.$$send();\n- added: Utils.$$wait();\n- added: Utils.$$resolve();\n- added: HttpFile.$$copy()\n- added: HttpFile.$$read()\n- added: HttpFile.$$md5()", "======= 1.7.2", "- added: Array.prototype.extend(obj, [rewrite])\n- added: SchemaBuilderEntity->constant(name, [value])\n- added: Utils.minifyHTML(value);\n- added: Utils.minifyScript(value);\n- added: Utils.minifyStyle(value);\n- added: FrameworkImage.measureSVG(buffer);\n- added: auto-parsing SVG width/height\n- added: framework.translator([language], text);\n- added: TRANSLATOR\n- added: SUCCESS(boolean, [value]) returns { success: boolean, value: [value] }\n- added: framework.onLocate(req, res) --> this method sets the current localization\n- added: new installation event framework.on('module#name');\n- added: new installation event framework.on('controller#name');\n- added: new installation event framework.on('model#name');\n- added: new installation event framework.on('definition#name');\n- added: new installation event framework.on('config#name');", "- updated: CSS compressor (better compression)\n- updated: Utils.Request() supports head method", "- fixed: binary `total --diff`\n- fixed: debug.js (fixed port)\n- fixed: F.onCompileStyle and F.onCompileJavaScript (problem with filename)\n- fixed: Number.prototype.pluralize()\n- fixed: WebSocket message parsing\n- fixed: (CRITICAL) mail sender (problem with CRLF in BASE64)\n- fixed: (CRITICAL) `../src/node_http_parser.cc, line 392.`\n- fixed: the framework duplicates width/height in upload auto-parser\n- fixed: JPG width/height auto-parser", "======= 1.7.1 (HOTFIX)", "This version will work on `io.js` without problems.", "- added: framework.schedule(date/string/number, fn);\n- added: (IMPORTANT) a prevention for the HeaderSent exception\n- added: new option `sleep` for framework.http() & framework.https()\n- added: request.ip caching\n- added: framework.useConfig(filename-configuration)", "- updated: String.toSearch() removes non-word characters\n- updated: Utils.trim() supports arrays", "- fixed: framework.versionNode (updated for io.js)\n- fixed: (CRITICAL) if the controller middleware does not exist framework throws exception correctly\n- fixed: Utils.validation() (for Arrays)\n- fixed: authorization routing\n- fixed: (CRITICAL) request with multipart content-type (+fixed problem XSS)\n- fixed: (CRITICAL) controller.memorize() in JSON output\n- fixed: (CRITICAL) uploading files, problem with the filename/name field (if it contained `;`)", "- removed: mmr", "======= 1.7.0", "Framework supports a backward compatibility.\nFramework supports: one file only (all libraries in one JS file)\nFramework loads modules, packages, models, definitions, controllers", "- added: SCHEMA(name), returns group of schemas\n- added: Builders.Schema() - schema supports onGet, onSave, onRemove, onQuery\n- added: Builders.Schema() - schema supports workflows\n- added: Builders.Schema() - schema supports composer\n- added: Builders.Schema() - schema supports transformations\n- added: Builders.Schema() - schema supports grouping `Builders.schema('group').get('schema_name)`\n- added: Builders.Schema() - schema supports rules\n- added: Builders.Schema().make(obj, callback(err, model)) - make object with $save, $remove, $compose, etc.\n- added: framework.mail() - is alias for controller.mail()\n- added: framework.view(name, [model], [layout], [repository]) - is alias for controller.view()\n- added: validate handler contains new parameter model -> (name, value, path, schema, model)\n- added: String.prototype.replaceAt(index, character)\n- added: String.prototype.parseXML()\n- added: String.prototype.toSearch()\n- added: async queue - Utils.queue(name, maximumCalls, fn) (for e.g. EMFILE, too many open files)\n- added: Utils.isEqual(obj1, obj2, [properties])\n- added: ErrorBuilder.prototype.push()\n- added: ErrorBuilder.prototype.transform()\n- added: ErrorBuilder.prototype.output()\n- added: ErrorBuilder.prototype.setTransform(name) - set default transform\n- added: ErrorBuilder.addTransform(name, fn, [isDefault]) - add transform\n- added: ErrorBuilder.setDefaultTransform() for all ErrorBuilders\n- added: Pagination.addTransform(name, fn, [isDefault]) - add transform\n- added: Pagination.setDefaultTransform(name) for all Paginations\n- added: Pagination.prototype.transform()\n- added: Pagination.prototype.setTransform(name) - set default transform\n- added: Pagination.prototype.first()\n- added: Pagination.prototype.last()\n- added: Pagination.prototype.isFirst\n- added: Pagination.prototype.isLast\n- added: framework.config['allow-custom-titles'] - (default: false)\n- added: new option into Mail: rejectUnauthorized (for TLS)\n- added: @{log()} and @{LOG()} into views\n- added: @{console} (.log, .info, etc.) into views\n- added: framework.on('controller-render-head', function(controller) {})\n- added: framework.on('controller-render-meta', function(controller) {})\n- added: framework.on('init')\n- added: framework.merge('/merge.js', '/js/file1.js', '/js/file2.js')\n- added: framework supports X-Forwarded-Protocol header\n- added: FrameworkImage supports buffer\n- added: auto-vendor-prefixes: box-sizing\n- added: new flag `noxhr` or `-xhr` because all route contains +xhr as default\n- added: config['default-errorbuilder-resource-name']\n- added: config['default-errorbuilder-resource-prefix']\n- added: config['allow-handle-static-files']\n- added: FrameworkCache.get() alias for FrameworkCache.read()\n- added: supports creating route without action (framework wraps action)\n- added: .md (markdown) into static-accepts\n- added: (modules, models, sources and controllers) exports.id instead of export.name\n- added: framework.map(url, new_filename)\n- added: framework.config['directory-packages'] for packages\n- added: (IMPORTANT) PACKAGES (same as modules but package can contain many files in one file)\n- added: framework.stats.request.request (requests count)\n- added: FrameworkImage.miniature(w, h, bgColor)\n- added: Array.first([def])\n- added: Array.last([def])\n- added: framework.routing(name)\n- added: global --> ROUTING(name)\n- added: global --> NOOP() empty function (exists: noop(), Utils.noop())\n- added: global --> DEBUG boolean property (is the framework in debug mode?)\n- added: global --> RELEASE boolean property (is the framework in release mode?)\n- added: global --> TEST boolean property (is the framework in test mode?)\n- added: global --> F object property (is alias for \"framework\")\n- added: routing supports schemas `*custom-schema/User` and we can define it in flags\n- added: String.prototype.parseBool()\n- added: String.prototype.parseJSON()\n- added: framework.responseImagePrepare(req, res, fnPrepare, fnProcess, [headers])\n- added: response.throw400([problem])\n- added: response.throw401([problem])\n- added: response.throw403([problem])\n- added: response.throw404([problem])\n- added: response.throw408([problem])\n- added: response.throw431([problem])\n- added: response.throw500([error])\n- added: response.throw501([problem])\n- added: response.redirect(url, [permanent])\n- added: view supports localization\n- added: assertion testing --> framework sets global.assert = require('assert')\n- added: module/controller supports dependencies --> exports.dependencies = ['moduleA', 'moduleB'];\n- added: framework.dependencies (this object contains all installed total.js dependencies)\n- added: controller.translate([text]);\n- added: framework.translate([language], text)\n- added: @{body.} instead of @{post.}\n- added: @{query.} instead of @{get.}\n- added: @{files} uploaded files\n- added: .manifest to accept list\n- added: BINARY added --diff for creating difference between two resources", "- updated: framework.resize(), added: options.cache (true/false, default: true)\n- updated: the route flag can contian number (TIMEOUT for current route)\n- updated: (IMPORTANT) framework doesn't remove subdirectories with files in temporary directory\n- updated: (IMPORTANT) all models are loaded after is the framework loaded\n- updated: framework.redirect(url, redirectTo, [permanent]) supports relative redirects\n- updated: Utils.request(), timeout is possible to add as cookie, headers or encoding\n- updated: Utils.request() returns EventEmitter (begin, end, data(chunk, percentage))\n- updated: Utils.request() supports auto-redirect if response status code is 301\n- updated: Utils.download() returns EventEmitter (begin, end, data(chunk, percentage))\n- updated: Controller.proxy() - returns EventEmitter (begin, end, data(chunk, percentage))\n- updated: Array.wait(fnItem, fnCallback, removeItems) - default: function doesn't remove items\n- updated: Builders.UrlBuilder() -> toString([skipEmpty])\n- updated: Number.format([decimals], [separator], [decimalSeparator])\n- updated: Date.format([format]) - format is optional, function returns ISO format without \"Z\"\n- updated: response.send(), response.json() - supports ErrorBuilder\n- updated: framework.error() (returns a wrapped delegate if error is undefined)\n- updated: controller.baa([message]) - read documentation\n- updated: Array.where(), Array.find(), Array.remove() - added a new functionality\n- updated: @{view(name, [model], [expire], [expire-key])}\n- updated: @{cookie(name)} --> read cookie\n- updated: framework.mail(address, subject, view, model, callback, replyTo) - added: replyTo\n- updated: controller.view(name) can execute without name (controller.viewname contains name according to URL)\n- updated: @{post} is deprecated\n- updated: @{get} is deprecated\n- updated: String.encode(), String.decode()\n- updated: (IMPORTANT) changed the arguments in callback for workflow, compose, transform\n- updated: BINARY total --translate SOME TEXT create translate identifier", "- renamed: config['directory-angular'] to config['directory-public-virtual']\n- renamed: config['allow-compress-html'] to config['allow-compile-html']\n- renamed: (IMPORTANT) default view layout from `_layout` to `layout`\n- renamed: Utils.parseDateExpire() -> Utils.parseDateExpiration()", "- removed: JS CSS\n- removed: (IMPORTANT) view markup for Angular.js from the core (it will be a module)\n- removed: Controller.fileAsync()\n- removed: Controller.await()\n- removed: Controller.wait()\n- removed: Controller.run()\n- removed: Controller.complete()\n- removed: Controller.jsonAsync()\n- removed: Controller.viewAsync()\n- removed: Controller.redirectAsync()\n- removed: framework.run()", "- fixed: LOG()\n- fixed: view engine rendering (fixed problem with undefined and null values)\n- fixed: buffer exceeded if a framework receives a data\n- fixed: if path starts '/' then is view loaded directly from /views/ directory\n- fixed: xml parser\n- fixed: problem with parsing a bad JSON datas - framework.decrypt();\n- fixed: String.prototype.parseDate()\n- fixed: path in framework.resize()\n- fixed: framework.responseImageWithoutCache()\n- fixed: appending .js or .css through @{head()}\n- fixed: WebSocket authorization\n- fixed: WebSocketClient.req\n- fixed: routing (+ asterix routing)\n- fixed: controller.cancel() (after framework.emit('controller', ...))\n- fixed: view helpers (calling without arguments)\n- fixed: dynamic cache of views\n- fixed: mail sending\n- fixed: clearing temporary directory\n- fixed: parse JSON by the JSON route\n- fixed: paths in Windows\n- fixed: subject encoding in mail (supports UTF-8)\n- fixed: sender name encoding in mail (supports UTF-8)\n- fixed: Utils.trim()\n- fixed: Utils.validation() (problem with schema array)\n- fixed: Response.cookie()\n- fixed: String.prototype.format() --> null/undefined --> returns empty string\n- fixed: Utils.request() problem with unicode\n- fixed: framework.assert() problem with unicode\n- fixed: XML parsing", "- improvements: routing performance", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/static-file-merge\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/framework-schema-and-validation", "======= 1.6.2 (HOTFIX)", "- updated: obtaining `req.xhr` before middleware", "======= 1.6.1 (HOTFIX)", "- added: `ErrorBuilder.errors` list of errors\n- added: transform-style, perspective, backface-visibility into the CSS auto-vendor-prefixes\n- added: WebSocket supports global middleware\n- added: WebSocketClient.isWebSocket (for middleware instead of Response)", "- updated: assertion testing (author: @toshipon)", "- fixed: controller.callback([view_name]), supports NoSQL Embeded Database\n- fixed: WebSocket auto-ping\n- fixed: (debug mode) caching of static files\n- fixed: global middleware (fixed exception in exception)\n- fixed: Mail (problem with secure option, author: @asessa)\n- fixed: binary (if debug.pid exists then is deleted and created again)", "- improvements: framework (comparison of undefined)", "======= 1.6.0", "- added: framework.http(mode, [options]) - mode: test, debug or development, release or production\n- added: framework.https(mode, [options]) - I recommend to use NGINX as HTTPS proxy\n- added: middleware delegate: function(req, res, next, [options], [controller]) { next(); }\n- added: middleware to framework.websocket(url, funcInitialize, [flags], [protocols], [allow], [maximumSize], [middleware])\n- added: middleware to framework.file([name], [fnValidation], [fnExecute], [middleware])\n- added: middleware to framework.use(name), this is global middleware\n- added: middleware can add as flag: '#middleware1', '#middleware2'\n- added: Response.controller, link to the current controller (if exists)\n- added: Response.send([code], body, [contentType])\n- added: Response.json(obj);\n- added: Response.file(filename, [downloadName], [headers])\n- added: Response.stream(contentType, stream, [downloadName], [headers])\n- added: Response.continue();\n- added: Response.req (current request)\n- added: Request.query;\n- added: Request.body;\n- added: Request.files;\n- added: controller.middleware(names, [options], [callback])\n- added: controller.body --> is same as Controller.post\n- added: controller.query --> is same as Controller.get\n- added: controller.isController (for middleware)\n- added: controller.json(obj, [beautify], [replacer]) and ErrorBuilder.json([beautify], [replacer]), author: bir <https://github.com/bir>\n- added: utils.wait(fnValid, fnCallback, [timeout(default: 5000 ms)], [interval(default: 500 ms)])\n- added: new flag: 'xml' in controller.route()\n- added: new flag: 'xml' in utils.request()\n- added: new flag: 'xml' in framework.assert()\n- added: assertion testing: exports.usage = function() {} for custom results of test\n- added: assertion testing: exports.disabled = true for disabling current test\n- added: assertion testing: priority (example: exports.priority = 1)\n- added: routing supports multiple HTTP-VERBS/METHODS together (author: bir <https://github.com/bir>)\n- added: routing supports options for middleware, author: bir <https://github.com/bir>\n- added: config-test (new config file)\n- added: config['default-interval-clear-resources'], default 20 (minutes)\n- added: config['default-interval-clear-temporary'], default 3 (minutes)\n- added: config['default-interval-precompile-views'], default 61 (minutes)\n- added: config['default-interval-websocket-ping'], default 1 (minutes)\n- added: config['disable-strict-server-certificate-validation'], default true\n- added: create automatically a ping message for websocket clients\n- added: global INSTALL(type, name, declaration/url/function, [options], [callback]);\n- added: global UNINSTALL(type, name, [options]);\n- added: global CONTROLLER(name);\n- added: framework.install(type, name, declaration/url/function, [options], [callback]);\n- added: framework.uninstall(type, name, [options]);\n- added: framework.on('install', function(type, name) {});\n- added: framework.on('uninstall', function(type, name) {});\n- added: framework.on('route-add', function(type, route) {})\n- added: module/model/source/controller: exports.name = 'name ';\n- added: module/model/source/controller: exports.version = 'version';\n- added: model/source: exports.install = function(framework, options, name) {}\n- added: module/model/source/controller: exports.uninstall = function(framework, options) {}\n- added: String.prototype.parseDateExpire() - parse expiration date, example: '1 minute', '1 year'\n- added: String.parseConfig([default]);\n- added: framework.fs.create.database()\n- added: framework.fs.rm.database()\n- added: controller.isTransfer\n- added: Date.compare(date) - for instance of date;\n- added: Date.compare(d1, d2);\n- added: Controller.date(type, date)\n- added: Controller.callback([viewName])\n- added: HttpFile.type (HttpFile.contentType is deprecated)\n- added: controller.section(name, [value]);", "- updated: NoSQL v2.0.8\n- updated: String.parseDate('yyyy-MM-dd HH:mm:ss') - time is optional\n- updated: module: exports.install = function(framework, options) {};\n- updated: (IMPORTANT) INCLUDE(name, [options]), SOURCE(name, [options]) –> object\n- updated: (IMPORTANT) SOURCE(name, [options]), framework.source(name, [options]) –> object\n- updated: framework.controller(name) - definition was removed (use: framework.install())\n- updated: framework.run([http], config, [port], [ip], [options])\n- updated: utils.validate(), Builders.validate() –> prepare function (added: schemaName): function(name, value, path, schemaName)\n- updated: framework.assert() supports \"data\" as function (for future data)\n- updated: empty-project\n- updated: request.signature([key]) - added key param\n- updated: middleware function to: function(req, res, next) {}\n- update: expiration supports string (framework.cache, response.cookie), example: '1 minute'\n- updated: $view(name, model, [expire]), $viewToggle(name, model, [expire]) - added expiration {String}\n- updated: controller.validate('schema_name', model);\n- updated: Angular.js version\n- updated: @{css()} and @{js()} supports multiple values\n- updated: @{place()} doesn't add `<script>` tag automatically", "- renamed: framework.on('expire') -> framework.on('cache-expire')\n- renamed: framework.accepts(extension, [contentType]) -> framework.accept(extension, [contentType])", "- fixed: controller.custom()\n- fixed: utils.validate()\n- fixed: long messages in WebSocket by Andrea Sessa <https://plus.google.com/u/0/104713619368072403016>\n- fixed: view engine parser (reported by @tohachan)\n- fixed: Builders.prepare()\n- fixed: Builders.validate()\n- fixed: framework.responseFile()\n- fixed: framework.onCompileStatic()\n- fixed: framework configuration\n- fixed: JS CSS\n- fixed: Auto vendor prefixer (CSS)\n- fixed: Image.command()", "- removed: (IMPORTANT) COMPONENTS()\n- removed: (IMPORTANT) prefixes + framework.onPrefix()\n- removed: (IMPORTANT) controller.framework (use: framework. instead of self.framework)\n- removed: (IMPORTANT) global middleware from controllers\n- removed: (IMPORTANT) global module #\n- removed: (IMPORTANT) Request.data.get\n- removed: (IMPORTANT) Request.data.post\n- removed: (IMPORTANT) Request.data.files\n- removed: (IMPORTANT) view engine: templates were changed to views\n- removed: (IMPORTANT) `@{content()}`\n- removed: (IMPORTANT) framework.injectModel() -> framework.install()\n- removed: (IMPORTANT) framework.injectModule() -> framework.install()\n- removed: (IMPORTANT) framework.injectSource() -> framework.install()\n- removed: (IMPORTANT) framework.injectDefinition() -> framework.install()\n- removed: (IMPORTANT) framework.injectController() -> framework.install()\n- removed: (IMPORTANT) framework.onRoute() - TIP: use middleware\n- removed: (IMPORTANT) framework.onRequest() - TIP: use middleware\n- removed: (IMPORTANT) controller & module -> exports.request()", "- clean code\n- improvements: framework", "======= 1.5.3 (HOTFIX)", "- added: request.query (alias for request.data.get)", "- (IMPORTANT) renamed: framework.partial() to framework.middleware()", "- fixed: exit code in assertion testing (bug with lowest priority)\n- (CRITICAL) fixed: WebSocket event", "======= 1.5.2 (HOTFIX)", "- added: CONFIG(name) - returns a value from the config file\n- added: RESOURCE(name, key) - returns a value from the resource file\n- added: utils.parseXML(xml)\n- added: config['static-accept'] += '.json'\n- added: String.prototype.slug([max])\n- added: Array.prototype.orderBy([name], [asc])\n- added: framework.on('request', function(req, res) {})\n- added: framework.on('websocket', function(req, socket) {})", "- updated: assertion testing", "- fixed: WebSocket in IE\n- fixed: calling global helpers like this: @{someHelper('some-argument')}\n- fixed: controller.proxy()\n- fixed: request.signature()\n- fixed: cache.read() - problem with exact expiration\n- fixed: \"options\" route flag\n- fixed: configuration (fixer: @peterkc)\n- fixed: schemas\n- fixed: assertion testing\n- fixed: view @{foreach ....}", "======= 1.5.0 & 1.5.1", "- added: TOTAL.JS PACKAGE MANAGER (new binary: tpm === [t]otal.js [p]ackage [m]anager)\n- added: JS CSS (important: removed LESS)\n- added: framework.noCache(req, [res])\n- added: request.noCache()\n- added: response.noCache()\n- added: new config file (this file is loaded in a debug and in a release mode): /some-app/config\n- added: String.prototype.startsWith(text, [ignoreCase]);\n- added: String.prototype.endsWith(text, [ignoreCase]);\n- added: picture auto resizer: framework.resize(url, [width], [height], [extensions], [path], [options])\n- added: .webm into the config['static-accepts']\n- added: in views - into the repository, model, user, session, get, post, global, config can assign some value: @{repository.name = 'total.js'}\n- added: in views - supports @{foreach [property] in [array]} ... @{end}\n- added: in views - supports nested conditions\n- added: in views - supports inline helpers\n- added: in views - supports sections\n- added: controller.throw400([problem])\n- added: controller.throw401([problem])\n- added: controller.throw403([problem])\n- added: controller.throw404([problem])\n- added: controller.throw500(error)\n- added: controller.throw501([problem])\n- added: request.signature()\n- added: Builders.create(schemaName)\n- added: controller.exception\n- added: framework.onMail(address, subject, body, callback)\n- added: controller.mail(address, subject, viewName, [model], [callback])\n- added: controller.transfer(url, [flags])", "- updated: config['default-websocket-encodedecode'] - default: true\n- updated: @{options(array/object)} - supports Object\n- updated: utils.request(url, flags, [data], callback, cookies, headers, encoding, timeout)\n- updated: utils.download(url, flags, [data], callback, cookies, headers, encoding, timeout)\n- updated: framework.eval(string/url/function) - this function supports eval code from another URL\n- updated: assertion testing (new features)\n- updated: framework.isProcessed(filename or request)\n- updated: framework.isProcessing(filename or request)\n- updated: binary (some changes and improvements)\n- updated: template engine\n- updated: ErrorBuidler.toString([delimiter])", "- renamed: ErrorBuilder.length -> ErrorBuilder.count", "- fixed: framework.isProcessed()\n- fixed: binary (test.js in empty-project)\n- fixed: @{ngCommon()}\n- fixed: @{ngStyle()}\n- fixed: measure JPG - extended buffer\n- fixed: utils.validate()\n- fixed: Mail sender (problem with TLS)", "- removed: IMPORTANT: old template engine was removed from templates\n- removed: IMPORTANT: LESS CSS", "- improvements: views\n- improvements: templates", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/controller-transfer\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/controller-mail\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/css-jscss\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/routing-resize\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/views-place-sections\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/views\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/views-custom-helper", "======= 1.4.0", "- added: new global methods: INCLUDE() - framework.source(), SOURCE() - framework.source(), MODEL(name) -> framework.model(), MODULE(name) -> framework.module(), DATABASE() -> framework.database()\n- added: unauthorize flag\n- added: config['allow-compress-html'] (default: true)\n- added: controller.language (read from request.language)\n- added: framework sets response['Content-Length'] for some static files", "- updated: debug.js (added \"source\")", "- fixed: View not found (message includes full filename)\n- fixed: @{ngFilter()}\n- fixed: routing priority\n- fixed: config['allow-gzip']\n- fixed: utils.decode()\n- fixed: utils.request()", "- renamed: String.prototype.link([max]) to -> String.prototype.linker([max])", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/font-awesome\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/websocket\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/angularjs-websocket\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/config-debug-release", "- MODULES (NEW): https://github.com/totaljs/modules/tree/master/twitter", "======= 1.3.1 (HOTFIX)", "- updated: angular.js version (v1.2.15)", "- fixed: partial views rendering in the layout\n- fixed: internally utils", "======= 1.3.0", "- added: supports CoffeeScript\n- added: framework.isWindows (readonly, boolean)\n- added: framework.isCoffee (readonly, boolean)\n- added: framework.config['directory-source'], great for business logic\n- added: framework.injectSource(name)\n- added: framework.source(name), call a business logic\n- added: new global methods include() and source() are linked into the config['directory-source']\n- added: config['default-websocket-encodedecode'] - encodeURIComponent && decodeURIComponent (IMPORTANT: default: false)\n- added: Builders.ErrorBuilder.resource(filename, prefix) - can change resource filename or prefix\n- added: new global variables - Builders, Mail, Utils\n- added: Builders.validate(schemaName, model) - returns ErrorBuilder from everywhere (uses framework.resource)\n- added: allowed controllers in subdirectories\n- added: utils.assign(obj, path, value/function) - read more in documentation", "- updated: Builders.schema(name, obj, [defaults], [validator]) - validator is new\n- updated: Builders.validation(name, [arr] or [function])\n- updated: controller.find(id or function)\n- updated: utils.copy(source, [target]);\n- updated: WebSocket.close([id], [message], [code]);\n- updated: WebSocketClient.close([message], [code]);", "- fixed: Controller properties on the WebSocket connections\n- fixed: binary\n- fixed: utils.validation()\n- fixed: multipart upload (problem with multiple values)\n- fixed: layout in partial views (from the controller)\n- fixed: Windows path", "IMPORTANT:\nrewritten: WebSocket + WebSocket supports: text, JSON, binary, ping + pong", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs-bootstrap\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/bootstrap\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/framework-schema-validation\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/webrtc (unfinished but for an idea)\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/framework-business-logic-source\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/framework-inject-business-logic-source", "======= 1.2.3-1 (HOTFIX)", "IMPORTANT:\n- fixed: [authorize] flag\n- updated: utils.copy(source, target), previous: utils.copy(target, source);", "======= 1.2.3", "- added: view @{helper('name', [arg1], [arg2], ...)}\n- added: controller.helper(name, [arg1], [arg2], ...)\n- added: controller.change(message)\n- added: new markup /*auto*/ for auto-vendor-prefixes\n- added: [authorize] flag\n- added: @{ng(name)}\n- added: @{ngTemplate(name, [id])}\n- added: @{ngController(name)}\n- added: @{ngFilter(name)}\n- added: @{ngService(name)}\n- added: @{ngDirective(name)}\n- added: @{ngResource(name)}\n- added: @{ngCommon(name)}\n- added: @{ngInclude(name)}\n- added: @{ngStyle(name)}\n- added: @{ngLocale(name)}\n- added: @{helper(helperName, [param1], [param2], ...)}\n- added: config['directory-angular']\n- added: config['angular-version']\n- added: config['angular-i18n-version']\n- added: binary: total -angular [or] total -a\n- added: framework.change(message, [name], [uri], [ip]);\n- added: framework.changes;\n- added: framework.on('change', message, [name], [uri], [ip]);", "IMPORTANT:\n- added: routing with asterix, example: framework.route('/subpage/*', ...);", "IMPORTANT:\n- updated: [logged] flag is obsolete, new flag: authorize\n- updated: [unlogged] flag is obsolete (without flag)", "- fixed: helpers\n- fixed: static files caching in debug mode", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs-websocket\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs-common\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs-mongodb-rest-resources\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/angularjs-routing\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/changes\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/routing\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/problems", "======= 1.2.1-1 (NPM problem)\n======= 1.2.1 (NPM problem)\n======= 1.2.0", "- new: NEW TEMPLATE ENGINE 2.0", "- added: route to website, route to file and route to websocket is possible everywhere\n- added: node harmony functions (see example)\n- added: gc() into framework.on('service')\n- added: config['allow-performance'] true/false (default, false)\n- added: config['default-image-converter'] (default \"gm\" - GraphicsMagick, another possibility: \"im\" - ImageMagick)\n- added: new views/templates/contents cache\n- added: framework.problem(message, [name], [uri], [ip]);\n- added: framework.on('problem', message, [name], [uri], [ip])\n- added: framework.problems;\n- added: req.language;\n- added: controller.title()\n- added: controller.description()\n- added: controller.keywords()\n- added: controller.problem(message)\n- added: controller.memorize(key, expire, fnTo, [fnFrom]) - cache for controller.view(), controller.json(), controller.plain()\n- added: Array.prototype.trim()\n- added: Array.prototype.wait()\n- added: Array.prototype.async()\n- added: String.prototype.hash([type])\n- added: Pagination.next([format]), Pagination.prev([format])\n- added: utils.isRegExp(obj)", "- updated: license\n- updated: parsing of configuration: # and // is a comment\n- updated: auto-vendor-prefixes (updated linear-gradient prioraty according to w3schools.com)\n- updated: websocket.send(message, [id], [blacklist]), id and blacklist can be a function\n- updated: controller.view400([problem])\n- updated: controller.view403([problem])\n- updated: controller.view404([problem])\n- updated: controller.view501([problem])\n- updated: controller.plain(contentBody, [headers]) - added JSON serialized for objects\n- updated: controller.json(obj, [header], [beaufity]);\n- updated: framework.usage([detailed]) - returns OBJECT\n- updated: FrameworkCache.removeAll(search or regexp-pattern)\n- updated: @{sitemap} is currently: @{sitemap()}\n- updated: PageBuilder\n- updated: @{template()} and controller.template() - default repository is controller repository", "- removed: border-radius and box-shadow from auto-vendor-prefixes", "- obsolete: Array.prototype.waiting()", "- fixed: controller.view500()\n- fixed: controller.proxy(), utils.request(), utils.download() - problem with NGINX, missing Content-Length header\n- fixed: WebSocket skips throwing error (socket close, EPIPE)\n- fixed: mail (SPAM fixes)\n- fixed: buffer.write (new node => 0.11.11)\n- fixed: IP and heroku deploy", "- rewritten: view engine\n- rewritten: template engine (according to view engine)", "- improvements: views\n- improvements: templates\n- improvements: partial routing", "IMPORTANT: framework.usage() returns OBJECT\nIMPORTANT: markup of template is OBSOLETE. Templates support only view markup.", "- EXAMPLE (NEW): https://github.com/totaljs/demo\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/heroku\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/controller-memorize\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/generators\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/routing-inline\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/problems\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/mongoose\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/pagination\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/templates", "======= 1.1.0", "- added: new feature COMPONENTS\n- added: new feature MODELS\n- added: framework.id\n- added: framework.isDebug\n- added: framework.isTest\n- added: framework.model(name)\n- added: framework.controller(name, definition)\n- added: framework.functions\n- added: framework.assert(name, callback)\n- added: framework.assert(name, url, callback, method, data, headers, xhr)\n- added: framework.injectComponent(name, url)\n- added: framework.injectModel(name, url)\n- added: framework.path.components([filename])\n- added: framework.path.models([filename])\n- added: controller.model(name)\n- added: controller.$model - (property contains current model)\n- added: flag: OPTIONS", "- updated: framework.usage([detailed])\n- updated: BINARY\n- updated: WebSocket skips throwing error (ECONNRESET)", "- fixed: framework.controller(name)\n- fixed: // char in views and templates\n- fixed: assertion testing\n- fixed: mail attachment (fixed: line too long)\n- fixed: \"@charset\" keyword in CSS\n- fixed: cache-control header\n- fixed: HTML conditional comments in views\n- fixed: controller.cors(), fixed problem with preflight\n- fixed: controller.empty() -> added 204 http status code", "improvements: views (in release mode)", "- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/components\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/models\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/minimal\n- EXAMPLE (NEW): https://github.com/totaljs/examples/tree/master/framework-functions\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/cors\n- EXAMPLE (UPD): https://github.com/totaljs/examples/tree/master/cluster", "======= 1.0.2 (HOTFIX)", "- fixed: mail message (problem with diacritics in OUTLOOK)", "======= 1.0.1 (HOTFIX)", "- added: advanced template conditions", "- fixed: builders.prepare()\n- fixed: binary (command-line tools)\n- fixed: views conditions" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [3, 6627], "buggy_code_start_loc": [3, 6625], "filenames": ["changes.txt", "utils.js"], "fixing_code_end_loc": [5, 6627], "fixing_code_start_loc": [4, 6625], "message": "The package total.js before 3.4.8 are vulnerable to Remote Code Execution (RCE) via set.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:totaljs:total.js:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "903890AB-2DE4-4BA4-83F0-AC47EEF03AFB", "versionEndExcluding": "3.4.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The package total.js before 3.4.8 are vulnerable to Remote Code Execution (RCE) via set."}, {"lang": "es", "value": "El paquete total.js versiones anteriores a 3.4.8, es vulnerable a una ejecuci\u00f3n de c\u00f3digo remota (RCE) por medio de set"}], "evaluatorComment": null, "id": "CVE-2021-23344", "lastModified": "2021-03-05T19:26:24.673", "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"}, {"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": "report@snyk.io", "type": "Secondary"}]}, "published": "2021-03-04T17:15:13.153", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/totaljs/framework/commit/c812bbcab8981797d3a1b9993fc42dad3d246f04"}, {"source": "report@snyk.io", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-TOTALJS-1077069"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-94"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/totaljs/framework/commit/c812bbcab8981797d3a1b9993fc42dad3d246f04"}, "type": "CWE-94"}
243
Determine whether the {function_name} code is vulnerable or not.
[ "// Copyright 2012-2020 (c) Peter Širka <petersirka@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.", "/**\n * @module FrameworkUtils\n * @version 3.4.4\n */", "'use strict';", "const Dns = require('dns');\nconst Url = require('url');\nconst Qs = require('querystring');\nconst Http = require('http');\nconst Https = require('https');\nconst Path = require('path');\nconst Fs = require('fs');\nconst Events = require('events');\nconst Crypto = require('crypto');\nconst Zlib = require('zlib');\nconst Tls = require('tls');\nconst KeepAlive = new Http.Agent({ keepAlive: true, timeout: 60000 });", "const COMPRESS = { gzip: 1, deflate: 1 };\nconst CONCAT = [null, null];\nconst COMPARER = global.Intl ? global.Intl.Collator().compare : function(a, b) {\n\treturn a.removeDiacritics().localeCompare(b.removeDiacritics());\n};", "if (!global.framework_utils)\n\tglobal.framework_utils = exports;", "const Internal = require('./internal');\nvar regexpSTATIC = /\\.\\w{2,8}($|\\?)+/;\nconst regexpTRIM = /^[\\s]+|[\\s]+$/g;\nconst regexpDATE = /(\\d{1,2}\\.\\d{1,2}\\.\\d{4})|(\\d{4}-\\d{1,2}-\\d{1,2})|(\\d{1,2}:\\d{1,2}(:\\d{1,2})?)/g;\nconst regexpDATEFORMAT = /YYYY|yyyy|YY|yy|MMMM|MMM|MM|M|dddd|DDDD|DDD|ddd|DD|dd|D|d|HH|H|hh|h|mm|m|ss|s|a|ww|w/g;\nconst regexpSTRINGFORMAT = /\\{\\d+\\}/g;\nconst regexpPATH = /\\\\/g;\nconst regexpTags = /<\\/?[^>]+(>|$)/g;\nconst regexpDiacritics = /[^\\u0000-\\u007e]/g;\nconst regexpUA = /[a-z]+/gi;\nconst regexpXML = /\\w+=\".*?\"/g;\nconst regexpDECODE = /&#?[a-z0-9]+;/g;\nconst regexpPARAM = /\\{{2}[^}\\n]*\\}{2}/g;\nconst regexpARG = /\\{{1,2}[a-z0-9_.-\\s]+\\}{1,2}/gi;\nconst regexpINTEGER = /(^-|\\s-)?[0-9]+/g;\nconst regexpFLOAT = /(^-|\\s-)?[0-9.,]+/g;\nconst regexpALPHA = /^[A-Za-z0-9]+$/;\nconst regexpSEARCH = /[^a-zA-Zá-žÁ-Ž\\d\\s:]/g;\nconst regexpTERMINAL = /[\\w\\S]+/g;\nconst regexpCONFIGURE = /\\[\\w+\\]/g;\nconst regexpY = /y/g;\nconst regexpN = /\\n/g;\nconst regexpCHARS = /\\W|_/g;\nconst regexpCHINA = /[\\u3400-\\u9FBF]/;\nconst regexpLINES = /\\n|\\r|\\r\\n/;\nconst regexpBASE64 = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/;\nconst SOUNDEX = { a: '', e: '', i: '', o: '', u: '', b: 1, f: 1, p: 1, v: 1, c: 2, g: 2, j: 2, k: 2, q: 2, s: 2, x: 2, z: 2, d: 3, t: 3, l: 4, m: 5, n: 5, r: 6 };\nconst ENCODING = 'utf8';\nconst NEWLINE = '\\r\\n';\nconst isWindows = require('os').platform().substring(0, 3).toLowerCase() === 'win';\nconst DIACRITICSMAP = {};\nconst STREAM_READONLY = { flags: 'r' };\nconst STREAM_END = { end: false };\nconst ALPHA_INDEX = { '&lt': '<', '&gt': '>', '&quot': '\"', '&apos': '\\'', '&amp': '&', '&lt;': '<', '&gt;': '>', '&quot;': '\"', '&apos;': '\\'', '&amp;': '&' };\nconst NODEVERSION = parseFloat(process.version.toString().replace('v', '').replace(/\\./g, ''));\nconst STREAMPIPE = { end: false };\nconst CT = 'Content-Type';\nconst CRC32TABLE = '00000000,77073096,EE0E612C,990951BA,076DC419,706AF48F,E963A535,9E6495A3,0EDB8832,79DCB8A4,E0D5E91E,97D2D988,09B64C2B,7EB17CBD,E7B82D07,90BF1D91,1DB71064,6AB020F2,F3B97148,84BE41DE,1ADAD47D,6DDDE4EB,F4D4B551,83D385C7,136C9856,646BA8C0,FD62F97A,8A65C9EC,14015C4F,63066CD9,FA0F3D63,8D080DF5,3B6E20C8,4C69105E,D56041E4,A2677172,3C03E4D1,4B04D447,D20D85FD,A50AB56B,35B5A8FA,42B2986C,DBBBC9D6,ACBCF940,32D86CE3,45DF5C75,DCD60DCF,ABD13D59,26D930AC,51DE003A,C8D75180,BFD06116,21B4F4B5,56B3C423,CFBA9599,B8BDA50F,2802B89E,5F058808,C60CD9B2,B10BE924,2F6F7C87,58684C11,C1611DAB,B6662D3D,76DC4190,01DB7106,98D220BC,EFD5102A,71B18589,06B6B51F,9FBFE4A5,E8B8D433,7807C9A2,0F00F934,9609A88E,E10E9818,7F6A0DBB,086D3D2D,91646C97,E6635C01,6B6B51F4,1C6C6162,856530D8,F262004E,6C0695ED,1B01A57B,8208F4C1,F50FC457,65B0D9C6,12B7E950,8BBEB8EA,FCB9887C,62DD1DDF,15DA2D49,8CD37CF3,FBD44C65,4DB26158,3AB551CE,A3BC0074,D4BB30E2,4ADFA541,3DD895D7,A4D1C46D,D3D6F4FB,4369E96A,346ED9FC,AD678846,DA60B8D0,44042D73,33031DE5,AA0A4C5F,DD0D7CC9,5005713C,270241AA,BE0B1010,C90C2086,5768B525,206F85B3,B966D409,CE61E49F,5EDEF90E,29D9C998,B0D09822,C7D7A8B4,59B33D17,2EB40D81,B7BD5C3B,C0BA6CAD,EDB88320,9ABFB3B6,03B6E20C,74B1D29A,EAD54739,9DD277AF,04DB2615,73DC1683,E3630B12,94643B84,0D6D6A3E,7A6A5AA8,E40ECF0B,9309FF9D,0A00AE27,7D079EB1,F00F9344,8708A3D2,1E01F268,6906C2FE,F762575D,806567CB,196C3671,6E6B06E7,FED41B76,89D32BE0,10DA7A5A,67DD4ACC,F9B9DF6F,8EBEEFF9,17B7BE43,60B08ED5,D6D6A3E8,A1D1937E,38D8C2C4,4FDFF252,D1BB67F1,A6BC5767,3FB506DD,48B2364B,D80D2BDA,AF0A1B4C,36034AF6,41047A60,DF60EFC3,A867DF55,316E8EEF,4669BE79,CB61B38C,BC66831A,256FD2A0,5268E236,CC0C7795,BB0B4703,220216B9,5505262F,C5BA3BBE,B2BD0B28,2BB45A92,5CB36A04,C2D7FFA7,B5D0CF31,2CD99E8B,5BDEAE1D,9B64C2B0,EC63F226,756AA39C,026D930A,9C0906A9,EB0E363F,72076785,05005713,95BF4A82,E2B87A14,7BB12BAE,0CB61B38,92D28E9B,E5D5BE0D,7CDCEFB7,0BDBDF21,86D3D2D4,F1D4E242,68DDB3F8,1FDA836E,81BE16CD,F6B9265B,6FB077E1,18B74777,88085AE6,FF0F6A70,66063BCA,11010B5C,8F659EFF,F862AE69,616BFFD3,166CCF45,A00AE278,D70DD2EE,4E048354,3903B3C2,A7672661,D06016F7,4969474D,3E6E77DB,AED16A4A,D9D65ADC,40DF0B66,37D83BF0,A9BCAE53,DEBB9EC5,47B2CF7F,30B5FFE9,BDBDF21C,CABAC28A,53B39330,24B4A3A6,BAD03605,CDD70693,54DE5729,23D967BF,B3667A2E,C4614AB8,5D681B02,2A6F2B94,B40BBE37,C30C8EA1,5A05DF1B,2D02EF8D'.split(',').map(s => parseInt(s, 16));\nconst REGISARR = /\\[\\d+\\]|\\[\\]$/;\nconst REGREPLACEARR = /\\[\\]/g;\nconst PROXYBLACKLIST = { 'localhost': 1, '127.0.0.1': 1, '0.0.0.0': 1 };\nconst PROXYOPTIONS = { headers: {}, method: 'CONNECT', agent: false };\nconst PROXYTLS = { headers: {}};\nconst PROXYOPTIONSHTTP = {};\nconst REG_ROOT = /@\\{#\\}(\\/)?/g;\nconst REG_NOREMAP = /@\\{noremap\\}(\\n)?/g;\nconst REG_REMAP = /href=\".*?\"|src=\".*?\"/gi;\nconst REG_AJAX = /('|\")+(!)?(GET|POST|PUT|DELETE|PATCH)\\s(\\(.*?\\)\\s)?\\//g;\nconst REG_URLEXT = /(https|http|wss|ws|file):\\/\\/|\\/\\/[a-z0-9]|[a-z]:/i;\nconst REG_TEXTAPPLICATION = /text|application/i;\nconst REG_TIME = /am|pm/i;\nconst REG_XMLKEY = /\\[|\\]|:|\\.|_/g;", "exports.MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\nexports.DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];", "var DIACRITICS=[{b:' ',c:'\\u00a0'},{b:'0',c:'\\u07c0'},{b:'A',c:'\\u24b6\\uff21\\u00c0\\u00c1\\u00c2\\u1ea6\\u1ea4\\u1eaa\\u1ea8\\u00c3\\u0100\\u0102\\u1eb0\\u1eae\\u1eb4\\u1eb2\\u0226\\u01e0\\u00c4\\u01de\\u1ea2\\u00c5\\u01fa\\u01cd\\u0200\\u0202\\u1ea0\\u1eac\\u1eb6\\u1e00\\u0104\\u023a\\u2c6f'},{b:'AA',c:'\\ua732'},{b:'AE',c:'\\u00c6\\u01fc\\u01e2'},{b:'AO',c:'\\ua734'},{b:'AU',c:'\\ua736'},{b:'AV',c:'\\ua738\\ua73a'},{b:'AY',c:'\\ua73c'},{b:'B',c:'\\u24b7\\uff22\\u1e02\\u1e04\\u1e06\\u0243\\u0181'},{b:'C',c:'\\u24b8\\uff23\\ua73e\\u1e08\\u0106C\\u0108\\u010a\\u010c\\u00c7\\u0187\\u023b'},{b:'D',c:'\\u24b9\\uff24\\u1e0a\\u010e\\u1e0c\\u1e10\\u1e12\\u1e0e\\u0110\\u018a\\u0189\\u1d05\\ua779'},{b:'Dh',c:'\\u00d0'},{b:'DZ',c:'\\u01f1\\u01c4'},{b:'Dz',c:'\\u01f2\\u01c5'},{b:'E',c:'\\u025b\\u24ba\\uff25\\u00c8\\u00c9\\u00ca\\u1ec0\\u1ebe\\u1ec4\\u1ec2\\u1ebc\\u0112\\u1e14\\u1e16\\u0114\\u0116\\u00cb\\u1eba\\u011a\\u0204\\u0206\\u1eb8\\u1ec6\\u0228\\u1e1c\\u0118\\u1e18\\u1e1a\\u0190\\u018e\\u1d07'},{b:'F',c:'\\ua77c\\u24bb\\uff26\\u1e1e\\u0191\\ua77b'}, {b:'G',c:'\\u24bc\\uff27\\u01f4\\u011c\\u1e20\\u011e\\u0120\\u01e6\\u0122\\u01e4\\u0193\\ua7a0\\ua77d\\ua77e\\u0262'},{b:'H',c:'\\u24bd\\uff28\\u0124\\u1e22\\u1e26\\u021e\\u1e24\\u1e28\\u1e2a\\u0126\\u2c67\\u2c75\\ua78d'},{b:'I',c:'\\u24be\\uff29\\u00cc\\u00cd\\u00ce\\u0128\\u012a\\u012c\\u0130\\u00cf\\u1e2e\\u1ec8\\u01cf\\u0208\\u020a\\u1eca\\u012e\\u1e2c\\u0197'},{b:'J',c:'\\u24bf\\uff2a\\u0134\\u0248\\u0237'},{b:'K',c:'\\u24c0\\uff2b\\u1e30\\u01e8\\u1e32\\u0136\\u1e34\\u0198\\u2c69\\ua740\\ua742\\ua744\\ua7a2'},{b:'L',c:'\\u24c1\\uff2c\\u013f\\u0139\\u013d\\u1e36\\u1e38\\u013b\\u1e3c\\u1e3a\\u0141\\u023d\\u2c62\\u2c60\\ua748\\ua746\\ua780'}, {b:'LJ',c:'\\u01c7'},{b:'Lj',c:'\\u01c8'},{b:'M',c:'\\u24c2\\uff2d\\u1e3e\\u1e40\\u1e42\\u2c6e\\u019c\\u03fb'},{b:'N',c:'\\ua7a4\\u0220\\u24c3\\uff2e\\u01f8\\u0143\\u00d1\\u1e44\\u0147\\u1e46\\u0145\\u1e4a\\u1e48\\u019d\\ua790\\u1d0e'},{b:'NJ',c:'\\u01ca'},{b:'Nj',c:'\\u01cb'},{b:'O',c:'\\u24c4\\uff2f\\u00d2\\u00d3\\u00d4\\u1ed2\\u1ed0\\u1ed6\\u1ed4\\u00d5\\u1e4c\\u022c\\u1e4e\\u014c\\u1e50\\u1e52\\u014e\\u022e\\u0230\\u00d6\\u022a\\u1ece\\u0150\\u01d1\\u020c\\u020e\\u01a0\\u1edc\\u1eda\\u1ee0\\u1ede\\u1ee2\\u1ecc\\u1ed8\\u01ea\\u01ec\\u00d8\\u01fe\\u0186\\u019f\\ua74a\\ua74c'}, {b:'OE',c:'\\u0152'},{b:'OI',c:'\\u01a2'},{b:'OO',c:'\\ua74e'},{b:'OU',c:'\\u0222'},{b:'P',c:'\\u24c5\\uff30\\u1e54\\u1e56\\u01a4\\u2c63\\ua750\\ua752\\ua754'},{b:'Q',c:'\\u24c6\\uff31\\ua756\\ua758\\u024a'},{b:'R',c:'\\u24c7\\uff32\\u0154\\u1e58\\u0158\\u0210\\u0212\\u1e5a\\u1e5c\\u0156\\u1e5e\\u024c\\u2c64\\ua75a\\ua7a6\\ua782'},{b:'S',c:'\\u24c8\\uff33\\u1e9e\\u015a\\u1e64\\u015c\\u1e60\\u0160\\u1e66\\u1e62\\u1e68\\u0218\\u015e\\u2c7e\\ua7a8\\ua784'},{b:'T',c:'\\u24c9\\uff34\\u1e6a\\u0164\\u1e6c\\u021a\\u0162\\u1e70\\u1e6e\\u0166\\u01ac\\u01ae\\u023e\\ua786'}, {b:'Th',c:'\\u00de'},{b:'TZ',c:'\\ua728'},{b:'U',c:'\\u24ca\\uff35\\u00d9\\u00da\\u00db\\u0168\\u1e78\\u016a\\u1e7a\\u016c\\u00dc\\u01db\\u01d7\\u01d5\\u01d9\\u1ee6\\u016e\\u0170\\u01d3\\u0214\\u0216\\u01af\\u1eea\\u1ee8\\u1eee\\u1eec\\u1ef0\\u1ee4\\u1e72\\u0172\\u1e76\\u1e74\\u0244'},{b:'V',c:'\\u24cb\\uff36\\u1e7c\\u1e7e\\u01b2\\ua75e\\u0245'},{b:'VY',c:'\\ua760'},{b:'W',c:'\\u24cc\\uff37\\u1e80\\u1e82\\u0174\\u1e86\\u1e84\\u1e88\\u2c72'},{b:'X',c:'\\u24cd\\uff38\\u1e8a\\u1e8c'},{b:'Y',c:'\\u24ce\\uff39\\u1ef2\\u00dd\\u0176\\u1ef8\\u0232\\u1e8e\\u0178\\u1ef6\\u1ef4\\u01b3\\u024e\\u1efe'}, {b:'Z',c:'\\u24cf\\uff3a\\u0179\\u1e90\\u017b\\u017d\\u1e92\\u1e94\\u01b5\\u0224\\u2c7f\\u2c6b\\ua762'},{b:'a',c:'\\u24d0\\uff41\\u1e9a\\u00e0\\u00e1\\u00e2\\u1ea7\\u1ea5\\u1eab\\u1ea9\\u00e3\\u0101\\u0103\\u1eb1\\u1eaf\\u1eb5\\u1eb3\\u0227\\u01e1\\u00e4\\u01df\\u1ea3\\u00e5\\u01fb\\u01ce\\u0201\\u0203\\u1ea1\\u1ead\\u1eb7\\u1e01\\u0105\\u2c65\\u0250\\u0251'},{b:'aa',c:'\\ua733'},{b:'ae',c:'\\u00e6\\u01fd\\u01e3'},{b:'ao',c:'\\ua735'},{b:'au',c:'\\ua737'},{b:'av',c:'\\ua739\\ua73b'},{b:'ay',c:'\\ua73d'}, {b:'b',c:'\\u24d1\\uff42\\u1e03\\u1e05\\u1e07\\u0180\\u0183\\u0253\\u0182'},{b:'c',c:'\\uff43\\u24d2\\u0107\\u0109\\u010b\\u010d\\u00e7\\u1e09\\u0188\\u023c\\ua73f\\u2184'},{b:'d',c:'\\u24d3\\uff44\\u1e0b\\u010f\\u1e0d\\u1e11\\u1e13\\u1e0f\\u0111\\u018c\\u0256\\u0257\\u018b\\u13e7\\u0501\\ua7aa'},{b:'dh',c:'\\u00f0'},{b:'dz',c:'\\u01f3\\u01c6'},{b:'e',c:'\\u24d4\\uff45\\u00e8\\u00e9\\u00ea\\u1ec1\\u1ebf\\u1ec5\\u1ec3\\u1ebd\\u0113\\u1e15\\u1e17\\u0115\\u0117\\u00eb\\u1ebb\\u011b\\u0205\\u0207\\u1eb9\\u1ec7\\u0229\\u1e1d\\u0119\\u1e19\\u1e1b\\u0247\\u01dd'}, {b:'f',c:'\\u24d5\\uff46\\u1e1f\\u0192'},{b:'ff',c:'\\ufb00'},{b:'fi',c:'\\ufb01'},{b:'fl',c:'\\ufb02'},{b:'ffi',c:'\\ufb03'},{b:'ffl',c:'\\ufb04'},{b:'g',c:'\\u24d6\\uff47\\u01f5\\u011d\\u1e21\\u011f\\u0121\\u01e7\\u0123\\u01e5\\u0260\\ua7a1\\ua77f\\u1d79'},{b:'h',c:'\\u24d7\\uff48\\u0125\\u1e23\\u1e27\\u021f\\u1e25\\u1e29\\u1e2b\\u1e96\\u0127\\u2c68\\u2c76\\u0265'},{b:'hv',c:'\\u0195'},{b:'i',c:'\\u24d8\\uff49\\u00ec\\u00ed\\u00ee\\u0129\\u012b\\u012d\\u00ef\\u1e2f\\u1ec9\\u01d0\\u0209\\u020b\\u1ecb\\u012f\\u1e2d\\u0268\\u0131'}, {b:'j',c:'\\u24d9\\uff4a\\u0135\\u01f0\\u0249'},{b:'k',c:'\\u24da\\uff4b\\u1e31\\u01e9\\u1e33\\u0137\\u1e35\\u0199\\u2c6a\\ua741\\ua743\\ua745\\ua7a3'},{b:'l',c:'\\u24db\\uff4c\\u0140\\u013a\\u013e\\u1e37\\u1e39\\u013c\\u1e3d\\u1e3b\\u017f\\u0142\\u019a\\u026b\\u2c61\\ua749\\ua781\\ua747\\u026d'},{b:'lj',c:'\\u01c9'},{b:'m',c:'\\u24dc\\uff4d\\u1e3f\\u1e41\\u1e43\\u0271\\u026f'},{b:'n',c:'\\u24dd\\uff4e\\u01f9\\u0144\\u00f1\\u1e45\\u0148\\u1e47\\u0146\\u1e4b\\u1e49\\u019e\\u0272\\u0149\\ua791\\ua7a5\\u043b\\u0509'},{b:'nj', c:'\\u01cc'},{b:'o',c:'\\u24de\\uff4f\\u00f2\\u00f3\\u00f4\\u1ed3\\u1ed1\\u1ed7\\u1ed5\\u00f5\\u1e4d\\u022d\\u1e4f\\u014d\\u1e51\\u1e53\\u014f\\u022f\\u0231\\u00f6\\u022b\\u1ecf\\u0151\\u01d2\\u020d\\u020f\\u01a1\\u1edd\\u1edb\\u1ee1\\u1edf\\u1ee3\\u1ecd\\u1ed9\\u01eb\\u01ed\\u00f8\\u01ff\\ua74b\\ua74d\\u0275\\u0254\\u1d11'},{b:'oe',c:'\\u0153'},{b:'oi',c:'\\u01a3'},{b:'oo',c:'\\ua74f'},{b:'ou',c:'\\u0223'},{b:'p',c:'\\u24df\\uff50\\u1e55\\u1e57\\u01a5\\u1d7d\\ua751\\ua753\\ua755\\u03c1'},{b:'q',c:'\\u24e0\\uff51\\u024b\\ua757\\ua759'}, {b:'r',c:'\\u24e1\\uff52\\u0155\\u1e59\\u0159\\u0211\\u0213\\u1e5b\\u1e5d\\u0157\\u1e5f\\u024d\\u027d\\ua75b\\ua7a7\\ua783'},{b:'s',c:'\\u24e2\\uff53\\u015b\\u1e65\\u015d\\u1e61\\u0161\\u1e67\\u1e63\\u1e69\\u0219\\u015f\\u023f\\ua7a9\\ua785\\u1e9b\\u0282'},{b:'ss',c:'\\u00df'},{b:'t',c:'\\u24e3\\uff54\\u1e6b\\u1e97\\u0165\\u1e6d\\u021b\\u0163\\u1e71\\u1e6f\\u0167\\u01ad\\u0288\\u2c66\\ua787'},{b:'th',c:'\\u00fe'},{b:'tz',c:'\\ua729'},{b:'u',c:'\\u24e4\\uff55\\u00f9\\u00fa\\u00fb\\u0169\\u1e79\\u016b\\u1e7b\\u016d\\u00fc\\u01dc\\u01d8\\u01d6\\u01da\\u1ee7\\u016f\\u0171\\u01d4\\u0215\\u0217\\u01b0\\u1eeb\\u1ee9\\u1eef\\u1eed\\u1ef1\\u1ee5\\u1e73\\u0173\\u1e77\\u1e75\\u0289'}, {b:'v',c:'\\u24e5\\uff56\\u1e7d\\u1e7f\\u028b\\ua75f\\u028c'},{b:'vy',c:'\\ua761'},{b:'w',c:'\\u24e6\\uff57\\u1e81\\u1e83\\u0175\\u1e87\\u1e85\\u1e98\\u1e89\\u2c73'},{b:'x',c:'\\u24e7\\uff58\\u1e8b\\u1e8d'},{b:'y',c:'\\u24e8\\uff59\\u1ef3\\u00fd\\u0177\\u1ef9\\u0233\\u1e8f\\u00ff\\u1ef7\\u1e99\\u1ef5\\u01b4\\u024f\\u1eff'},{b:'z',c:'\\u24e9\\uff5a\\u017a\\u1e91\\u017c\\u017e\\u1e93\\u1e95\\u01b6\\u0225\\u0240\\u2c6c\\ua763'}];", "for (var i=0; i <DIACRITICS.length; i+=1)\n\tfor (var chars=DIACRITICS[i].c,j=0;j<chars.length;j+=1)\n\t\tDIACRITICSMAP[chars[j]]=DIACRITICS[i].b;", "const DP = Date.prototype;\nconst SP = String.prototype;\nconst NP = Number.prototype;", "DIACRITICS = null;", "var CONTENTTYPES = {\n\taac: 'audio/aac',\n\tai: 'application/postscript',\n\tappcache: 'text/cache-manifest',\n\tavi: 'video/avi',\n\tbin: 'application/octet-stream',\n\tbmp: 'image/bmp',\n\tcoffee: 'text/coffeescript',\n\tcss: 'text/css',\n\tcsv: 'text/csv',\n\tdoc: 'application/msword',\n\tdocx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n\tdtd: 'application/xml-dtd',\n\teps: 'application/postscript',\n\texe: 'application/octet-stream',\n\tflac: 'audio/x-flac',\n\tgeojson: 'application/json',\n\tgif: 'image/gif',\n\tgzip: 'application/x-gzip',\n\theic: 'image/heic',\n\theif: 'image/heif',\n\thtm: 'text/html',\n\thtml: 'text/html',\n\tico: 'image/x-icon',\n\tics: 'text/calendar',\n\tifb: 'text/calendar',\n\tjpe: 'image/jpeg',\n\tjpeg: 'image/jpeg',\n\tjpg: 'image/jpeg',\n\tjs: 'text/javascript',\n\tjson: 'application/json',\n\tjsx: 'text/jsx',\n\tless: 'text/css',\n\tm4a: 'audio/mp4a-latm',\n\tm4v: 'video/x-m4v',\n\tmanifest: 'text/cache-manifest',\n\tmd: 'text/x-markdown',\n\tmid: 'audio/midi',\n\tmidi: 'audio/midi',\n\tmjs: 'text/javascript',\n\tmov: 'video/quicktime',\n\tmp3: 'audio/mpeg',\n\tmp4: 'video/mp4',\n\tmpe: 'video/mpeg',\n\tmpeg: 'video/mpeg',\n\tmpg: 'video/mpeg',\n\tmpga: 'audio/mpeg',\n\tmtl: 'text/plain',\n\tmv4: 'video/mv4',\n\tobj: 'text/plain',\n\togg: 'application/ogg',\n\togv: 'video/ogg',\n\tpackage: 'text/plain',\n\tpdf: 'application/pdf',\n\tpng: 'image/png',\n\tppt: 'application/vnd.ms-powerpoint',\n\tpptx: 'application/vnd.ms-powerpoint',\n\tps: 'application/postscript',\n\trar: 'application/x-rar-compressed',\n\trtf: 'text/rtf',\n\tsass: 'text/css',\n\tscss: 'text/css',\n\tsh: 'application/x-sh',\n\tstl: 'application/sla',\n\tsvg: 'image/svg+xml',\n\tswf: 'application/x-shockwave-flash',\n\ttar: 'application/x-tar',\n\ttif: 'image/tiff',\n\ttiff: 'image/tiff',\n\ttxt: 'text/plain',\n\tsql: 'text/plain',\n\twav: 'audio/x-wav',\n\twebm: 'video/webm',\n\twebp: 'image/webp',\n\twoff: 'application/font-woff',\n\twoff2: 'application/font-woff2',\n\txht: 'application/xhtml+xml',\n\txhtml: 'application/xhtml+xml',\n\txls: 'application/vnd.ms-excel',\n\txlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n\txml: 'application/xml',\n\txpm: 'image/x-xpixmap',\n\txsl: 'application/xml',\n\txslt: 'application/xslt+xml',\n\tzip: 'application/zip'\n};", "var dnscache = {};\nvar datetimeformat = {};\nconst hasOwnProperty = Object.prototype.hasOwnProperty;", "global.DIFFARR = exports.diffarr = function(prop, db, form) {", "\tvar an = [];\n\tvar au = [];\n\tvar ar = [];\n\tvar is, oa, ob;", "\tfor (var i = 0; i < db.length; i++) {\n\t\toa = db[i];\n\t\tis = false;\n\t\tfor (var j = 0; j < form.length; j++) {\n\t\t\tob = form[j];\n\t\t\tif (oa[prop] == ob[prop]) {\n\t\t\t\tau.push({ db: oa, form: ob });\n\t\t\t\tis = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!is)\n\t\t\tar.push(oa[prop]);\n\t}", "\tfor (var i = 0; i < form.length; i++) {\n\t\tob = form[i];\n\t\tis = false;\n\t\tfor (var j = 0; j < db.length; j++) {\n\t\t\toa = db[j];\n\t\t\tif (ob[prop] == oa[prop]) {\n\t\t\t\tis = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!is)\n\t\t\tan.push(ob);\n\t}", "\tvar obj = {};\n\tobj.add = an;\n\tobj.upd = au;\n\tobj.rem = ar;\n\treturn obj;\n};", "/**\n * Checks if is object empty\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isEmpty = function(obj) {", "\tif (!obj || obj instanceof Array)\n\t\treturn true;", "\tfor (var key in obj) {\n\t\tif (hasOwnProperty.call(obj, key))\n\t\t\treturn false;\n\t}", "\treturn true;\n};", "/**\n * Compare objects\n * @param {Object} obj1\n * @param {Object} obj2\n * @return {Boolean}\n */\nexports.isEqual = function(obj1, obj2, properties) {", "\tvar keys = properties ? properties : Object.keys(obj1);", "\tfor (var i = 0, length = keys.length; i < length; i++) {\n\t\tvar key = keys[i];\n\t\tvar a = obj1[key];\n\t\tvar b = obj2[key];\n\t\tvar ta = typeof(a);\n\t\tvar tb = typeof(b);", "\t\tif (ta !== tb)\n\t\t\treturn false;", "\t\tif (a === b)\n\t\t\tcontinue;", "\t\tif (a instanceof Date && b instanceof Date) {\n\t\t\tif (a.getTime() === b.getTime())\n\t\t\t\tcontinue;\n\t\t\treturn false;\n\t\t} else if (a instanceof Array && b instanceof Array) {\n\t\t\tif (JSON.stringify(a) === JSON.stringify(b))\n\t\t\t\tcontinue;\n\t\t\treturn false;\n\t\t}", "\t\tif (ta === 'object' && tb === 'object') {\n\t\t\tif (exports.isEqual(a, b))\n\t\t\t\tcontinue;\n\t\t}", "\t\treturn false;\n\t}", "\treturn true;\n};", "/**\n * Function checks a valid function and waits for it positive result\n * @param {Function} fnValid\n * @param {Function(err, success)} fnCallback\n * @param {Number} timeout Timeout, optional (default: 5000)\n * @param {Number} interval Refresh interval, optional (default: 500)\n */\nexports.wait = function(fnValid, fnCallback, timeout, interval) {", "\tif (fnValid() === true)\n\t\treturn fnCallback(null, true);", "\tvar id_timeout = null;\n\tvar id_interval = setInterval(function() {", "\t\tif (fnValid() === true) {\n\t\t\tclearInterval(id_interval);\n\t\t\tclearTimeout(id_timeout);\n\t\t\tfnCallback && fnCallback(null, true);\n\t\t}", "\t}, interval || 500);", "\tid_timeout = setTimeout(function() {\n\t\tclearInterval(id_interval);\n\t\tfnCallback && fnCallback(new Error('Timeout.'), false);\n\t}, timeout || 5000);\n};", "exports.$$wait = function(fnValid, timeout, interval) {\n\treturn function(callback) {\n\t\texports.wait(fnValid, callback, timeout, interval);\n\t};\n};", "/**\n * Resolves an IP from the URL address\n * @param {String} url\n * @param {Function(err, uri)} callback\n */\nexports.resolve = function(url, callback, param) {", "\tvar uri = Url.parse(url);", "\n\tif (!callback)\n\t\treturn dnscache[uri.host];", "\tif (dnscache[uri.host]) {\n\t\turi.host = dnscache[uri.host];\n\t\tcallback(null, uri, param);\n\t\treturn;\n\t}", "\tDns.resolve4(uri.hostname, function(e, addresses) {\n\t\tif (e)\n\t\t\tsetImmediate(dnsresolve_callback, uri, callback, param);\n\t\telse {\n\t\t\tdnscache[uri.host] = addresses[0];\n\t\t\turi.host = addresses[0];\n\t\t\tcallback(null, uri, param);\n\t\t}\n\t});\n};", "function dnsresolve_callback(uri, callback, param) {\n\tDns.resolve4(uri.hostname, function(e, addresses) {\n\t\tif (addresses && addresses.length) {\n\t\t\tdnscache[uri.host] = addresses[0];\n\t\t\turi.host = addresses[0];\n\t\t}\n\t\tcallback(e, uri, param);\n\t});\n}", "exports.$$resolve = function(url) {\n\treturn function(callback) {\n\t\treturn exports.resolve(url, callback);\n\t};\n};", "/**\n * Clears DNS cache\n */\nexports.clearDNS = function() {\n\tOBSOLETE('U.clearDNS()', 'Use CMD(\\'clear_dnscache\\')');\n\tCMD('clear_dnscache');\n};", "setImmediate(function() {\n\tif (global.F) {\n\t\tF.install('command', 'clear_dnscache', function() {\n\t\t\tdnscache = {};\n\t\t});\n\t}\n});", "\nexports.keywords = function(content, forSearch, alternative, max_count, max_length, min_length) {", "\tif (forSearch === undefined)\n\t\tforSearch = true;", "\tmin_length = min_length || 2;\n\tmax_count = max_count || 200;\n\tmax_length = max_length || 20;", "\tvar words = [];\n\tvar isSoundex = alternative === 'soundex';", "\tif (content instanceof Array) {\n\t\tfor (var i = 0, length = content.length; i < length; i++) {\n\t\t\tif (!content[i])\n\t\t\t\tcontinue;\n\t\t\tvar tmp = (forSearch ? content[i].removeDiacritics().toLowerCase().replace(regexpY, 'i') : content[i].toLowerCase()).replace(regexpN, ' ').split(' ');\n\t\t\tif (!tmp || !tmp.length)\n\t\t\t\tcontinue;\n\t\t\tfor (var j = 0, jl = tmp.length; j < jl; j++)\n\t\t\t\twords.push(tmp[j]);\n\t\t}\n\t} else\n\t\twords = (forSearch ? content.removeDiacritics().toLowerCase().replace(regexpY, 'i') : content.toLowerCase()).replace(regexpN, ' ').split(' ');", "\tif (!words)\n\t\twords = [];", "\tvar dic = {};\n\tvar counter = 0;", "\tfor (var i = 0, length = words.length; i < length; i++) {", "\t\tvar word = words[i].trim().replace(regexpCHARS, keywordscleaner);", "\t\tif (regexpCHINA.test(word)) {", "\t\t\tvar tmpw = word.split('', max_count);", "\t\t\tfor (var j = 0; j < tmpw.length; j++) {\n\t\t\t\tword = tmpw[j];\n\t\t\t\tif (dic[word])\n\t\t\t\t\tdic[word]++;\n\t\t\t\telse\n\t\t\t\t\tdic[word] = 1;\n\t\t\t\tcounter++;\n\t\t\t}", "\t\t\tif (counter >= max_count)\n\t\t\t\tbreak;", "\t\t\tcontinue;\n\t\t}", "\t\tif (word.length < min_length)\n\t\t\tcontinue;", "\t\tif (counter >= max_count)\n\t\t\tbreak;", "\t\t// Gets 80% length of word\n\t\tif (alternative) {\n\t\t\tif (isSoundex)\n\t\t\t\tword = word.soundex();\n\t\t\telse {\n\t\t\t\tvar size = (word.length / 100) * 80;\n\t\t\t\tif (size > min_length + 1)\n\t\t\t\t\tword = word.substring(0, size);\n\t\t\t}\n\t\t}", "\t\tif (word.length < min_length || word.length > max_length)\n\t\t\tcontinue;", "\t\tif (dic[word])\n\t\t\tdic[word]++;\n\t\telse\n\t\t\tdic[word] = 1;", "\t\tcounter++;\n\t}", "\tvar keys = Object.keys(dic);", "\tkeys.sort(function(a, b) {\n\t\tvar countA = dic[a];\n\t\tvar countB = dic[b];\n\t\treturn countA > countB ? -1 : countA < countB ? 1 : 0;\n\t});", "\treturn keys;\n};", "function keywordscleaner(c) {\n\treturn c.charCodeAt(0) < 200 ? '' : c;\n}", "function parseProxy(p) {\n\tvar key = 'proxy_' + p;\n\tif (F.temporary.other[key])\n\t\treturn F.temporary.other[key];", "\tif (p.indexOf('://') === -1)\n\t\tp = 'http://' + p;", "\tvar obj = Url.parse(p);", "\tif (obj.auth)\n\t\tobj._auth = 'Basic ' + Buffer.from(obj.auth).toString('base64');", "\tobj.port = +obj.port;\n\treturn F.temporary.other[key] = obj;\n}", "/**\n * Create a request to a specific URL\n * @param {String} url URL address.\n * @param {String Array} flags Request flags.\n * @param {String or Object} data Request data (optional).\n * @param {Function(error, content, statusCode, headers)} callback Callback.\n * @param {Object} headers Custom cookies (optional, default: null).\n * @param {Object} headers Custom headers (optional, default: null).\n * @param {String} encoding Encoding (optional, default: UTF8)\n * @param {Number} timeout Request timeout.\n * return {Boolean}\n */", "const NOBODY = { GET: 1, OPTIONS: 1, HEAD: 1 };", "global.REQUEST = exports.request = function(url, flags, data, callback, cookies, headers, encoding, timeout, files, param) {", "\t// No data (data is optional argument)\n\tif (typeof(data) === 'function') {\n\t\tencoding = headers;\n\t\theaders = cookies;\n\t\tcookies = callback;\n\t\tcallback = data;\n\t\tdata = '';\n\t} else if (!data)\n\t\tdata = '';", "\tif (callback === NOOP)\n\t\tcallback = null;", "\tif (global.F)\n\t\tglobal.F.stats.performance.external++;", "\tvar options = { length: 0, timeout: timeout || CONF.default_restbuilder_timeout, evt: new EventEmitter2(), encoding: typeof(encoding) !== 'string' ? ENCODING : encoding, callback: callback, post: false, redirect: 0 };\n\tvar method;\n\tvar type = 0;\n\tvar isCookies = false;\n\tvar def;\n\tvar proxy;", "\tif (headers) {\n\t\theaders = exports.extend({}, headers);\n\t\tdef = headers[CT];\n\t} else\n\t\theaders = {};", "\tif (flags instanceof Array) {\n\t\tfor (var i = 0, length = flags.length; i < length; i++) {", "\t\t\t// timeout\n\t\t\tif (flags[i] > 0) {\n\t\t\t\toptions.timeout = flags[i];\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (flags[i][0] === '<') {\n\t\t\t\toptions.max = flags[i].substring(1).trim().parseInt() * 1024; // kB\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (flags[i][0] === 'p' && flags[i][4] === 'y') {\n\t\t\t\tproxy = parseProxy(flags[i].substring(6));\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tswitch (flags[i].toLowerCase()) {\n\t\t\t\tcase 'utf8':\n\t\t\t\tcase 'ascii':\n\t\t\t\tcase 'base64':\n\t\t\t\tcase 'binary':\n\t\t\t\tcase 'hex':\n\t\t\t\t\toptions.encoding = flags[i];\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'xhr':\n\t\t\t\t\theaders['X-Requested-With'] = 'XMLHttpRequest';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'plain':\n\t\t\t\t\tif (!def)\n\t\t\t\t\t\theaders[CT] = 'text/plain';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'html':\n\t\t\t\t\tif (!def)\n\t\t\t\t\t\theaders[CT] = 'text/html';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'raw':\n\t\t\t\t\ttype = 3;\n\t\t\t\t\tif (!def)\n\t\t\t\t\t\theaders[CT] = 'application/octet-stream';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'json':\n\t\t\t\t\tif (!def)\n\t\t\t\t\t\theaders[CT] = 'application/json';\n\t\t\t\t\t!method && (method = 'POST');\n\t\t\t\t\ttype = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'xml':\n\t\t\t\t\tif (!def)\n\t\t\t\t\t\theaders[CT] = 'text/xml';\n\t\t\t\t\t!method && (method = 'POST');\n\t\t\t\t\ttype = 2;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'get':\n\t\t\t\tcase 'options':\n\t\t\t\tcase 'head':\n\t\t\t\t\tmethod = flags[i].charCodeAt(0) > 96 ? flags[i].toUpperCase() : flags[i];\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'noredirect':\n\t\t\t\t\toptions.noredirect = true;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'upload':\n\t\t\t\t\ttype = 4;\n\t\t\t\t\toptions.upload = true;\n\t\t\t\t\toptions.files = files || EMPTYARRAY;\n\t\t\t\t\toptions.boundary = '----totaljs' + Math.random().toString(16).substring(2);\n\t\t\t\t\theaders[CT] = 'multipart/form-data; boundary=' + options.boundary;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'post':\n\t\t\t\tcase 'put':\n\t\t\t\tcase 'delete':\n\t\t\t\tcase 'patch':\n\t\t\t\t\tmethod = flags[i].toUpperCase();\n\t\t\t\t\t!def && !headers[CT] && (headers[CT] = 'application/x-www-form-urlencoded');\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'dnscache':\n\t\t\t\t\toptions.resolve = true;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'keepalive':\n\t\t\t\t\toptions.keepalive = true;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'cookies':\n\t\t\t\t\tisCookies = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:", "\t\t\t\t\t// Fallback for methods (e.g. CalDAV)\n\t\t\t\t\tif (!method)\n\t\t\t\t\t\tmethod = flags[i].charCodeAt(0) > 96 ? flags[i].toUpperCase() : flags[i];", "\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "\tif (method)\n\t\toptions.post = !NOBODY[method];\n\telse\n\t\tmethod = 'GET';", "\tif (type < 3) {", "\t\tif (typeof(data) !== 'string')\n\t\t\tdata = type === 1 ? JSON.stringify(data) : Qs.stringify(data);\n\t\telse if (data[0] === '?')\n\t\t\tdata = data.substring(1);", "\t\tif (!options.post) {\n\t\t\tif (data.length) {\n\t\t\t\tif (url.indexOf('?') === -1)\n\t\t\t\t\turl += '?' + data;\n\t\t\t\telse\n\t\t\t\t\turl += '&' + data;\n\t\t\t}\n\t\t\tdata = '';\n\t\t}", "\t\t// \"null\" or \"empty string\" is valid JSON value too\n\t\tif (type === 1 && (data === EMPTYOBJECT || data === undefined) && options.post)\n\t\t\tdata = BUFEMPTYJSON;\n\t}", "\tif (data && type !== 4) {\n\t\toptions.data = data instanceof Buffer ? data : Buffer.from(data, ENCODING);\n\t\theaders['Content-Length'] = options.data.length;\n\t} else\n\t\toptions.data = data;", "\tif (cookies) {\n\t\tif (isCookies)\n\t\t\toptions.cookies = cookies;\n\t\tvar builder = '';\n\t\tfor (var m in cookies)\n\t\t\tbuilder += (builder ? '; ' : '') + m + '=' + cookies[m];\n\t\tif (builder)\n\t\t\theaders['Cookie'] = builder;\n\t}", "\tvar uri = Url.parse(url);", "\tif (!uri.hostname || !uri.host) {\n\t\tcallback && callback(new Error('URL doesn\\'t contain a hostname'), '', 0);\n\t\treturn;\n\t}", "\turi.method = method;\n\turi.headers = headers;\n\toptions.uri = uri;", "\tif (options.resolve && (uri.hostname === 'localhost' || uri.hostname.charCodeAt(0) < 64))\n\t\toptions.resolve = null;", "\tif (CONF.default_proxy && !proxy && !PROXYBLACKLIST[uri.hostname])\n\t\tproxy = parseProxy(CONF.default_proxy);", "\tif (proxy && (uri.hostname === 'localhost' || uri.hostname === '127.0.0.1'))\n\t\tproxy = null;", "\toptions.proxy = proxy;\n\toptions.param = param;", "\tif (proxy && uri.protocol === 'https:') {\n\t\tproxy.tls = true;\n\t\turi.agent = new ProxyAgent(options);\n\t\turi.agent.request = Http.request;\n\t\turi.agent.createSocket = createSecureSocket;\n\t\turi.agent.defaultPort = 443;\n\t}", "\tif (options.keepalive && !options.proxy && uri.protocol !== 'https:')\n\t\turi.agent = KeepAlive;", "\tif (proxy)\n\t\trequest_call(uri, options);\n\telse if (options.resolve)\n\t\texports.resolve(url, request_resolve, options);\n\telse\n\t\trequest_call(uri, options);", "\treturn options.evt;\n};", "function request_resolve(err, uri, options) {\n\tif (!err)\n\t\toptions.uri.host = uri.host;\n\trequest_call(options.uri, options);\n}", "function ProxyAgent(options) {\n\tvar self = this;\n\tself.options = options;\n\tself.maxSockets = Http.Agent.defaultMaxSockets;\n\tself.requests = [];\n}", "const PAP = ProxyAgent.prototype;", "PAP.createConnection = function(pending) {\n\tvar self = this;\n\tself.createSocket(pending, function(socket) {\n\t\tpending.request.onSocket(socket);\n\t});\n};", "PAP.createSocket = function(options, callback) {", "\tvar self = this;\n\tvar proxy = self.options.proxy;\n\tvar uri = self.options.uri;", "\tPROXYOPTIONS.host = proxy.hostname;\n\tPROXYOPTIONS.port = proxy.port;\n\tPROXYOPTIONS.path = PROXYOPTIONS.headers.host = uri.hostname + ':' + (uri.port || '443');", "\tif (proxy._auth)\n\t\tPROXYOPTIONS.headers['Proxy-Authorization'] = proxy._auth;", "\tvar req = self.request(PROXYOPTIONS);\n\treq.setTimeout(10000);\n\treq.on('response', proxyagent_response);\n\treq.on('connect', function(res, socket) {", "\t\tif (res.statusCode === 200) {\n\t\t\tsocket.$req = req;\n\t\t\tcallback(socket);\n\t\t} else {\n\t\t\tvar err = new Error('Proxy could not be established (maybe a problem in auth), code: ' + res.statusCode);\n\t\t\terr.code = 'ECONNRESET';\n\t\t\toptions.request.emit('error', err);\n\t\t\treq.destroy && req.destroy();\n\t\t\treq = null;\n\t\t\tself.requests = null;\n\t\t\tself.options = null;\n\t\t}\n\t});", "\treq.on('error', function(err) {\n\t\tvar e = new Error('Request Proxy \"proxy {0} --> target {1}\": {2}'.format(PROXYOPTIONS.host + ':' + proxy.port, PROXYOPTIONS.path, err.toString()));\n\t\te.code = err.code;\n\t\toptions.request.emit('error', e);\n\t\treq.destroy && req.destroy();\n\t\treq = null;\n\t\tself.requests = null;\n\t\tself.options = null;\n\t});", "\treq.end();\n};", "function proxyagent_response(res) {\n\tres.upgrade = true;\n}", "PAP.addRequest = function(req, options) {\n\tthis.createConnection({ host: options.host, port: options.port, request: req });\n};", "function createSecureSocket(options, callback) {\n\tvar self = this;\n\tPAP.createSocket.call(self, options, function(socket) {\n\t\tPROXYTLS.servername = self.options.uri.hostname;\n\t\tPROXYTLS.headers = self.options.uri.headers;\n\t\tPROXYTLS.socket = socket;\n\t\tvar tls = Tls.connect(0, PROXYTLS);\n\t\tcallback(tls);\n\t});\n}", "function request_call(uri, options) {", "\tvar opt;", "\tif (options.proxy && !options.proxy.tls) {\n\t\topt = PROXYOPTIONSHTTP;\n\t\topt.port = options.proxy.port;\n\t\topt.host = options.proxy.hostname;\n\t\topt.path = uri.href;\n\t\topt.headers = uri.headers;\n\t\topt.method = uri.method;\n\t\topt.headers.host = uri.host;\n\t\tif (options.proxy._auth)\n\t\t\topt.headers['Proxy-Authorization'] = options.proxy._auth;\n\t} else\n\t\topt = uri;", "\tvar connection = uri.protocol === 'https:' ? Https : Http;\n\tvar req = options.post ? connection.request(opt, request_response) : connection.get(opt, request_response);", "\treq.$options = options;\n\treq.$uri = uri;", "\tif (!options.callback) {\n\t\treq.on('error', NOOP);\n\t\treturn;\n\t}", "\treq.on('error', request_process_error);\n\toptions.timeoutid && clearTimeout(options.timeoutid);\n\toptions.timeoutid = setTimeout(request_process_timeout, options.timeout, req);", "\t// req.on('response', (response) => response.req = req);\n\treq.on('response', request_assign_res);", "\tif (options.upload) {\n\t\toptions.first = true;\n\t\toptions.files.wait(function(file, next) {\n\t\t\trequest_writefile(req, options, file, next);\n\t\t}, function() {\n\t\t\tvar keys = Object.keys(options.data);\n\t\t\tfor (var i = 0, length = keys.length; i < length; i++) {\n\t\t\t\tvar value = options.data[keys[i]];\n\t\t\t\tif (value != null) {\n\t\t\t\t\treq.write((options.first ? '' : NEWLINE) + '--' + options.boundary + NEWLINE + 'Content-Disposition: form-data; name=\"' + keys[i] + '\"' + NEWLINE + NEWLINE + value.toString());\n\t\t\t\t\tif (options.first)\n\t\t\t\t\t\toptions.first = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treq.end(NEWLINE + '--' + options.boundary + '--');\n\t\t});\n\t} else\n\t\treq.end(options.data);\n}", "function request_process_error(err) {\n\tvar options = this.$options;\n\tif (options.callback && !options.done) {\n\t\tif (options.timeoutid) {\n\t\t\tclearTimeout(options.timeoutid);\n\t\t\toptions.timeoutid = null;\n\t\t}\n\t\toptions.canceled = true;\n\t\toptions.callback(err, '', 0, undefined, this.$uri.host, EMPTYOBJECT, options.param);\n\t\toptions.callback = null;\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t}\n}", "function request_process_timeout(req) {\n\tvar options = req.$options;\n\tif (options.callback) {\n\t\tif (options.timeoutid) {\n\t\t\tclearTimeout(options.timeoutid);\n\t\t\toptions.timeoutid = null;\n\t\t}\n\t\treq.socket.destroy();\n\t\treq.socket.end();\n\t\treq.abort();\n\t\toptions.canceled = true;\n\t\toptions.callback(new Error(exports.httpStatus(408)), '', 0, undefined, req.$uri.host, EMPTYOBJECT, options.param);\n\t\toptions.callback = null;\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t}\n}", "function request_assign_res(response) {\n\tresponse.req = this;\n}", "function request_writefile(req, options, file, next) {", "\tvar type = typeof(file.buffer);\n\tvar filename = (type === 'string' ? file.buffer : exports.getName(file.filename));", "\treq.write((options.first ? '' : NEWLINE) + '--' + options.boundary + NEWLINE + 'Content-Disposition: form-data; name=\"' + file.name + '\"; filename=\"' + filename + '\"' + NEWLINE + 'Content-Type: ' + exports.getContentType(exports.getExtension(filename)) + NEWLINE + NEWLINE);", "\tif (options.first)\n\t\toptions.first = false;", "\t// Is Buffer\n\tif (file.buffer && type === 'object') {\n\t\treq.write(file.buffer);\n\t\tnext();\n\t} else {\n\t\tvar stream = Fs.createReadStream(file.filename);\n\t\tstream.once('close', next);\n\t\tstream.pipe(req, STREAMPIPE);\n\t}\n}", "function request_response(res) {", "\tvar options = this.$options;\n\tvar uri = this.$uri;", "\tres._buffer = null;\n\tres._bufferlength = 0;", "\t// We have redirect\n\tif (res.statusCode === 301 || res.statusCode === 302) {", "\t\tif (options.noredirect) {", "\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.canceled = true;", "\t\t\tif (options.callback) {\n\t\t\t\toptions.callback(null, '', res.statusCode, res.headers, uri.host, EMPTYOBJECT, options.param);\n\t\t\t\toptions.callback = null;\n\t\t\t}", "\t\t\tif (options.evt) {\n\t\t\t\toptions.evt.removeAllListeners();\n\t\t\t\toptions.evt = null;\n\t\t\t}", "\t\t\tres.req.removeAllListeners();\n\t\t\tres.removeAllListeners();\n\t\t\tres.req = null;\n\t\t\tres = null;\n\t\t\treturn;\n\t\t}", "\t\tif (options.redirect > 3) {", "\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.canceled = true;", "\t\t\tif (options.callback) {\n\t\t\t\toptions.callback(new Error('Too many redirects.'), '', 0, undefined, uri.host, EMPTYOBJECT, options.param);\n\t\t\t\toptions.callback = null;\n\t\t\t}", "\t\t\tif (options.evt) {\n\t\t\t\toptions.evt.removeAllListeners();\n\t\t\t\toptions.evt = null;\n\t\t\t}", "\t\t\tres.req.removeAllListeners();\n\t\t\tres.removeAllListeners();\n\t\t\tres.req = null;\n\t\t\tres = null;\n\t\t\treturn;\n\t\t}", "\t\toptions.redirect++;", "\t\tvar loc = res.headers['location'];\n\t\tvar proto = loc.substring(0, 6);", "\t\tif (proto !== 'http:/' && proto !== 'https:')\n\t\t\tloc = uri.protocol + '//' + uri.hostname + loc;", "\t\tvar tmp = Url.parse(loc);\n\t\ttmp.headers = uri.headers;\n\t\t// tmp.agent = false;\n\t\ttmp.method = uri.method;", "\t\tres.req.removeAllListeners();\n\t\tres.req = null;", "\t\tif (options.proxy && tmp.protocol === 'https:') {\n\t\t\t// TLS?\n\t\t\toptions.proxy.tls = true;\n\t\t\toptions.uri = tmp;\n\t\t\toptions.uri.agent = new ProxyAgent(options);\n\t\t\toptions.uri.agent.request = Http.request;\n\t\t\toptions.uri.agent.createSocket = createSecureSocket;\n\t\t\toptions.uri.agent.defaultPort = 443;\n\t\t}", "\t\tif (!options.resolve) {\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\treturn request_call(tmp, options);\n\t\t}", "\t\texports.resolve(tmp, function(err, u) {\n\t\t\tif (!err)\n\t\t\t\ttmp.host = u.host;\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\trequest_call(tmp, options);\n\t\t});", "\t\treturn;\n\t}", "\toptions.length = +res.headers['content-length'] || 0;\n\toptions.evt && options.evt.$events.begin && options.evt.emit('begin', options.length);", "\t// Shared cookies\n\tif (options.cookies) {\n\t\tvar arr = (res.headers['set-cookie'] || '');", "\t\t// Only the one value\n\t\tif (arr && !(arr instanceof Array))\n\t\t\tarr = [arr];", "\t\tif (arr instanceof Array) {\n\t\t\tfor (var i = 0, length = arr.length; i < length; i++) {\n\t\t\t\tvar line = arr[i];\n\t\t\t\tvar end = line.indexOf(';');\n\t\t\t\tif (end === -1)\n\t\t\t\t\tend = line.length;\n\t\t\t\tline = line.substring(0, end);\n\t\t\t\tvar index = line.indexOf('=');\n\t\t\t\tif (index !== -1)\n\t\t\t\t\toptions.cookies[line.substring(0, index)] = decodeURIComponent(line.substring(index + 1));\n\t\t\t}\n\t\t}\n\t}", "\tif (res.statusCode === 204) {\n\t\toptions.done = true;\n\t\trequest_process_end.call(res);\n\t\treturn;\n\t}", "\tvar encoding = res.headers['content-encoding'] || '';\n\tif (encoding)\n\t\tencoding = encoding.split(',')[0];", "\tif (COMPRESS[encoding]) {\n\t\tvar zlib = encoding === 'gzip' ? Zlib.createGunzip() : Zlib.createInflate();\n\t\tzlib._buffer = res.buffer;\n\t\tzlib.headers = res.headers;\n\t\tzlib.statusCode = res.statusCode;\n\t\tzlib.res = res;\n\t\tzlib.on('data', request_process_data);\n\t\tzlib.on('end', request_process_end);\n\t\tres.pipe(zlib);\n\t} else {\n\t\tres.on('data', request_process_data);\n\t\tres.on('end', request_process_end);\n\t}", "\tres.resume();\n}", "function request_process_data(chunk) {\n\tvar self = this;", "\t// Is Zlib\n\tif (!self.req)\n\t\tself = self.res;", "\tvar options = self.req.$options;\n\tif (options.canceled || (options.max && self._bufferlength > options.max))\n\t\treturn;\n\tif (self._buffer) {\n\t\tCONCAT[0] = self._buffer;\n\t\tCONCAT[1] = chunk;\n\t\tself._buffer = Buffer.concat(CONCAT);\n\t} else\n\t\tself._buffer = chunk;\n\tself._bufferlength += chunk.length;\n\toptions.evt && options.evt.$events.data && options.evt.emit('data', chunk, options.length ? (self._bufferlength / options.length) * 100 : 0);\n}", "function request_process_end() {", "\tvar res = this;", "\t// Is Zlib\n\tif (!res.req)\n\t\tres = res.res;", "\tvar self = res;\n\tvar options = self.req.$options;\n\tvar uri = self.req.$uri;\n\tvar data;", "\toptions.socket && options.uri.agent.destroy();\n\toptions.timeoutid && clearTimeout(options.timeoutid);", "\tif (options.canceled)\n\t\treturn;", "\tvar ct = self.headers['content-type'];", "\tif (!ct || REG_TEXTAPPLICATION.test(ct))\n\t\tdata = self._buffer ? (options.encoding === 'binary' ? self._buffer : self._buffer.toString(options.encoding)) : '';\n\telse\n\t\tdata = self._buffer;", "\toptions.canceled = true;", "\tself._buffer = undefined;", "\tif (options.evt) {\n\t\toptions.evt.$events.end && options.evt.emit('end', data, self.statusCode, self.headers, uri.host, options.cookies, options.param);\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t}", "\tif (options.callback) {\n\t\toptions.callback(null, uri.method === 'HEAD' ? self.headers : data, self.statusCode, self.headers, uri.host, options.cookies, options.param);\n\t\toptions.callback = null;\n\t}", "\tif (res.statusCode !== 204) {\n\t\tres.req && res.req.removeAllListeners();\n\t\tres.removeAllListeners();\n\t}\n}", "exports.$$request = function(url, flags, data, cookies, headers, encoding, timeout) {\n\treturn function(callback) {\n\t\texports.request(url, flags, data, callback, cookies, headers, encoding, timeout);\n\t};\n};", "exports.btoa = function(str) {\n\treturn (str instanceof Buffer) ? str.toString('base64') : Buffer.from(str.toString(), 'utf8').toString('base64');\n};", "exports.atob = function(str) {\n\treturn Buffer.from(str, 'base64').toString('utf8');\n};", "/**\n * Create a request to a specific URL\n * @param {String} url URL address.\n * @param {String Array} flags Request flags.\n * @param {String or Object} data Request data (optional).\n * @param {Function(error, response)} callback Callback.\n * @param {Object} cookies Custom cookies (optional, default: null).\n * @param {Object} headers Custom headers (optional, default: null).\n * @param {String} encoding Encoding (optional, default: UTF8)\n * @param {Number} timeout Request timeout.\n * return {Boolean}\n */\nexports.download = function(url, flags, data, callback, cookies, headers, encoding, timeout, param) {", "\t// No data (data is optional argument)\n\tif (typeof(data) === 'function') {\n\t\ttimeout = encoding;\n\t\tencoding = headers;\n\t\theaders = cookies;\n\t\tcookies = callback;\n\t\tcallback = data;\n\t\tdata = '';\n\t}", "\tif (typeof(cookies) === 'number') {\n\t\tcookies = null;\n\t\ttimeout = cookies;\n\t}", "\tif (typeof(headers) === 'number') {\n\t\theaders = null;\n\t\ttimeout = headers;\n\t}", "\tif (typeof(encoding) === 'number') {\n\t\tencoding = null;\n\t\ttimeout = encoding;\n\t}", "\tif (typeof(encoding) !== 'string')\n\t\tencoding = ENCODING;", "\tvar proxy, type = 0;\n\tvar method = 'GET';\n\tvar options = { callback: callback, resolve: false, length: 0, evt: new EventEmitter2(), timeout: timeout || 60000, post: false, encoding: encoding };", "\tif (headers)\n\t\theaders = exports.extend({}, headers);\n\telse\n\t\theaders = {};", "\tif (data === null)\n\t\tdata = '';", "\tif (flags instanceof Array) {\n\t\tfor (var i = 0, length = flags.length; i < length; i++) {", "\t\t\t// timeout\n\t\t\tif (flags[i] > 0) {\n\t\t\t\toptions.timeout = flags[i];\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (flags[i][0] === '<') {\n\t\t\t\t// max length is not supported\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (flags[i][0] === 'p' && flags[i][4] === 'y') {\n\t\t\t\tproxy = parseProxy(flags[i].substring(6));\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tswitch (flags[i].toLowerCase()) {", "\t\t\t\tcase 'utf8':\n\t\t\t\tcase 'ascii':\n\t\t\t\tcase 'base64':\n\t\t\t\tcase 'binary':\n\t\t\t\tcase 'hex':\n\t\t\t\t\toptions.encoding = flags[i];\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'xhr':\n\t\t\t\t\theaders['X-Requested-With'] = 'XMLHttpRequest';\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'plain':\n\t\t\t\t\theaders['Content-Type'] = 'text/plain';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'html':\n\t\t\t\t\theaders['Content-Type'] = 'text/html';\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'json':\n\t\t\t\t\theaders['Content-Type'] = 'application/json';\n\t\t\t\t\ttype = 1;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'xml':\n\t\t\t\t\theaders['Content-Type'] = 'text/xml';\n\t\t\t\t\ttype = 2;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'get':\n\t\t\t\tcase 'head':\n\t\t\t\tcase 'options':\n\t\t\t\t\tmethod = flags[i].charCodeAt(0) > 96 ? flags[i].toUpperCase() : flags[i];\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'upload':\n\t\t\t\t\theaders['Content-Type'] = 'multipart/form-data';\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'post':\n\t\t\t\tcase 'patch':\n\t\t\t\tcase 'delete':\n\t\t\t\tcase 'put':\n\t\t\t\t\tmethod = flags[i].charCodeAt(0) > 96 ? flags[i].toUpperCase() : flags[i];\n\t\t\t\t\tif (!headers['Content-Type'])\n\t\t\t\t\t\theaders['Content-Type'] = 'application/x-www-form-urlencoded';\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'dnscache':\n\t\t\t\t\toptions.resolve = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'keepalive':\n\t\t\t\t\toptions.keepalive = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t// Fallback for methods (e.g. CalDAV)\n\t\t\t\t\tmethod = flags[i].charCodeAt(0) > 96 ? flags[i].toUpperCase() : flags[i];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "\tif (!method)\n\t\tmethod = 'GET';", "\toptions.post = !NOBODY[method];", "\tif (typeof(data) !== 'string')\n\t\tdata = type === 1 ? JSON.stringify(data) : Qs.stringify(data);\n\telse if (data[0] === '?')\n\t\tdata = data.substring(1);", "\tif (!options.post) {\n\t\tif (data.length && url.indexOf('?') === -1)\n\t\t\turl += '?' + data;\n\t\tdata = '';\n\t}", "\tif (cookies) {\n\t\tvar builder = '';\n\t\tfor (var m in cookies)\n\t\t\tbuilder += (builder ? '; ' : '') + m + '=' + cookies[m];\n\t\tif (builder)\n\t\t\theaders['Cookie'] = builder;\n\t}", "\tvar uri = Url.parse(url);\n\turi.method = method;\n\t// uri.agent = false;\n\turi.headers = headers;\n\toptions.uri = uri;\n\toptions.param = param;", "\tif (options.resolve && (uri.hostname === 'localhost' || uri.hostname.charCodeAt(0) < 64))\n\t\toptions.resolve = null;", "\tif (data.length) {\n\t\toptions.data = Buffer.from(data, ENCODING);\n\t\theaders['Content-Length'] = options.data.length;\n\t}", "\tif (CONF.default_proxy && !proxy && !PROXYBLACKLIST[uri.hostname])\n\t\tproxy = parseProxy(CONF.default_proxy);", "\toptions.proxy = proxy;", "\tif (proxy && uri.protocol === 'https:') {\n\t\tproxy.tls = true;\n\t\turi.agent = new ProxyAgent(options);\n\t\turi.agent.request = Http.request;\n\t\turi.agent.createSocket = createSecureSocket;\n\t\turi.agent.defaultPort = 443;\n\t}", "\tif (options.keepalive && !options.proxy && uri.protocol !== 'https:')\n\t\turi.agent = KeepAlive;", "\tif (global.F)\n\t\tglobal.F.stats.performance.external++;", "\tif (proxy)\n\t\tdownload_call(uri, options);\n\telse if (options.resolve)\n\t\texports.resolve(url, download_resolve, options);\n\telse\n\t\tdownload_call(uri, options);", "\treturn options.evt;\n};", "function download_resolve(err, uri, options) {\n\tif (!err)\n\t\toptions.uri.host = uri.host;\n\tdownload_call(options.uri, options);\n}", "function download_call(uri, options) {", "\tvar opt;\n\toptions.length = 0;", "\tif (options.proxy && !options.proxy.tls) {\n\t\topt = PROXYOPTIONSHTTP;\n\t\topt.port = options.proxy.port;\n\t\topt.host = options.proxy.hostname;\n\t\topt.path = uri.href;\n\t\topt.headers = uri.headers;\n\t\topt.method = uri.method;\n\t\tif (options.proxy._auth)\n\t\t\topt.headers['Proxy-Authorization'] = options.proxy._auth;\n\t} else\n\t\topt = uri;", "\tvar connection = uri.protocol === 'https:' ? Https : Http;\n\tvar req = options.post ? connection.request(opt, download_response) : connection.get(opt, download_response);", "\treq.$options = options;\n\treq.$uri = uri;", "\tif (!options.callback) {\n\t\treq.on('error', NOOP);\n\t\treturn;\n\t}", "\treq.on('error', download_process_error);\n\toptions.timeoutid && clearTimeout(options.timeoutid);\n\toptions.timeoutid = setTimeout(download_process_timeout, options.timeout);\n\treq.on('response', download_assign_res);\n\treq.end(options.data);\n}", "function download_assign_res(response) {\n\tresponse.req = this;\n\tvar options = this.$options;\n\toptions.length = +response.headers['content-length'] || 0;\n\toptions.evt && options.evt.$events.begin && options.evt.emit('begin', options.length);\n}", "function download_process_timeout(req) {\n\tvar options = req.$options;\n\tif (options.callback) {\n\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\toptions.timeoutid = null;\n\t\treq.abort();\n\t\toptions.callback(new Error(exports.httpStatus(408)), null, null, null, null, options.param);\n\t\toptions.callback = null;\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t\toptions.canceled = true;\n\t}\n}", "function download_process_error(err) {\n\tvar options = this.$options;\n\tif (options.callback && !options.done) {\n\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\toptions.timeoutid = null;\n\t\toptions.callback(err, null, null, null, null, options.param);\n\t\toptions.callback = null;\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t\toptions.canceled = true;\n\t}\n}", "function download_response(res) {", "\tvar options = this.$options;\n\tvar uri = this.$uri;", "\tres._bufferlength = 0;", "\t// We have redirect\n\tif (res.statusCode === 301 || res.statusCode === 302) {", "\t\tif (options.redirect > 3) {\n\t\t\toptions.canceled = true;\n\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.callback && options.callback(new Error('Too many redirects.'), null, null, null, null, options.param);\n\t\t\tres.req.removeAllListeners();\n\t\t\tres.req = null;\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\treturn;\n\t\t}", "\t\toptions.redirect++;", "\t\tvar loc = res.headers['location'];\n\t\tvar proto = loc.substring(0, 6);", "\t\tif (proto !== 'http:/' && proto !== 'https:')\n\t\t\tloc = uri.protocol + '//' + uri.hostname + loc;", "\t\tvar tmp = Url.parse(loc);\n\t\ttmp.headers = uri.headers;\n\t\t// tmp.agent = false;\n\t\ttmp.method = uri.method;\n\t\tres.req.removeAllListeners();\n\t\tres.req = null;", "\t\tif (options.proxy && tmp.protocol === 'https:') {\n\t\t\t// TLS?\n\t\t\toptions.uri = tmp;\n\t\t\tdownload_call(options, request_call);\n\t\t\treturn;\n\t\t}", "\t\tif (!options.resolve) {\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\treturn download_call(tmp, options);\n\t\t}", "\t\texports.resolve(loc, function(err, u) {\n\t\t\tif (!err)\n\t\t\t\ttmp.host = u.host;\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\tdownload_call(tmp, options);\n\t\t});", "\t\treturn;\n\t}", "\tres.on('data', download_process_data);\n\tres.on('end', download_process_end);", "\tres.resume();\n\toptions.timeoutid && clearTimeout(options.timeoutid);\n\toptions.callback && options.callback(null, res, res.statusCode, res.headers, uri.host, options.param);\n}", "exports.$$download = function(url, flags, data, cookies, headers, encoding, timeout) {\n\treturn function(callback) {\n\t\texports.download(url, flags, data, callback, cookies, headers, encoding, timeout);\n\t};\n};", "function download_process_end() {", "\tvar res = this;\n\tvar self = this;\n\tvar options = self.req.$options;\n\tvar uri = self.req.$uri;", "\tif (!options.canceled) {\n\t\tvar str = self._buffer ? self._buffer.toString(options.encoding) : '';\n\t\tself._buffer = undefined;\n\t\toptions.evt && options.evt.$events.end && options.evt.emit('end', str, self.statusCode, self.headers, uri.host);\n\t}", "\tif (options.evt) {\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t}", "\tres.req && res.req.removeAllListeners();\n\tres.removeAllListeners();\n}", "function download_process_data(chunk) {\n\tvar self = this;\n\tvar options = self.req.$options;\n\tif (!options.canceled) {\n\t\tself._bufferlength += chunk.length;\n\t\tif (options.evt) {\n\t\t\toptions.evt.$events.data && options.evt.emit('data', chunk, options.length ? (self._bufferlength / options.length) * 100 : 0);\n\t\t\toptions.evt.$events.progress && options.evt.emit('progress', options.length ? (self._bufferlength / options.length) * 100 : 0);\n\t\t}\n\t}\n}", "/**\n * Upload a stream through HTTP\n * @param {String} name Filename with extension.\n * @param {Stream} stream Stream.\n * @param {String} url A valid URL address.\n * @param {Function} callback Callback.\n * @param {Object} headers Custom headers (optional).\n * @param {String} method HTTP method (optional, default POST).\n * @param {Number} timeout Request timeout, default: 60000 (1 minute)\n */\nexports.send = function(name, stream, url, callback, cookies, headers, method, timeout) {", "\tOBSOLETE('U.send()', 'Use U.upload() instead of U.send().');", "\tif (typeof(stream) === 'string')\n\t\tstream = Fs.createReadStream(stream, STREAM_READONLY);", "\tvar BOUNDARY = '----totaljs' + Math.random().toString(16).substring(2);\n\tvar h = {};", "\tif (headers)\n\t\texports.extend(h, headers);", "\tif (cookies) {\n\t\tvar builder = '';\n\t\tfor (var m in cookies)\n\t\t\tbuilder += (builder ? '; ' : '') + m + '=' + cookies[m];\n\t\tif (builder)\n\t\t\th['Cookie'] = builder;\n\t}", "\tname = exports.getName(name);", "\th['Cache-Control'] = 'max-age=0';\n\th['Content-Type'] = 'multipart/form-data; boundary=' + BOUNDARY;", "\tif (global.F)\n\t\tglobal.F.stats.performance.external++;", "\tvar e = new EventEmitter2();\n\tvar uri = Url.parse(url);\n\tvar options = { protocol: uri.protocol, auth: uri.auth, method: method || 'POST', hostname: uri.hostname, port: uri.port, path: uri.path, agent: false, headers: h };\n\tvar responseLength = 0;", "\tvar response = function(res) {", "\t\tres.body = Buffer.alloc(0);\n\t\tres._bufferlength = 0;", "\t\tres.on('data', function(chunk) {\n\t\t\tCONCAT[0] = res.body;\n\t\t\tCONCAT[1] = chunk;\n\t\t\tres.body = Buffer.concat(CONCAT);\n\t\t\tres._bufferlength += chunk.length;\n\t\t\te.$events.data && e.emit('data', chunk, responseLength ? (res._bufferlength / responseLength) * 100 : 0);\n\t\t});", "\t\tres.on('end', function() {\n\t\t\tvar self = this;\n\t\t\te.$events.end && e.emit('end', self.statusCode, self.headers);\n\t\t\te.removeAllListeners();\n\t\t\te = null;\n\t\t\tcallback && callback(null, self.body.toString('utf8'), self.statusCode, self.headers, uri.host);\n\t\t\tself.body = null;\n\t\t});\n\t};", "\tvar connection = options.protocol === 'https:' ? Https : Http;\n\tvar req = connection.request(options, response);", "\treq.on('response', function(response) {\n\t\tresponseLength = +response.headers['content-length'] || 0;\n\t\te.$events.begin && e.emit('begin', responseLength);\n\t});", "\treq.setTimeout(timeout || 60000, function() {\n\t\treq.removeAllListeners();\n\t\treq = null;\n\t\te.removeAllListeners();\n\t\te = null;\n\t\tcallback && callback(new Error(exports.httpStatus(408)), '', 408, undefined, uri.host);\n\t});", "\treq.on('error', function(err) {\n\t\treq.removeAllListeners();\n\t\treq = null;\n\t\te.removeAllListeners();\n\t\te = null;\n\t\tcallback && callback(err, '', 0, undefined, uri.host);\n\t});", "\treq.on('close', function() {\n\t\treq.removeAllListeners();\n\t\treq = null;\n\t});", "\tvar header = NEWLINE + NEWLINE + '--' + BOUNDARY + NEWLINE + 'Content-Disposition: form-data; name=\"File\"; filename=\"' + name + '\"' + NEWLINE + 'Content-Type: ' + exports.getContentType(exports.getExtension(name)) + NEWLINE + NEWLINE;\n\treq.write(header);", "\t// Is Buffer\n\tif (stream.length) {\n\t\treq.write(stream);\n\t\treq.end(NEWLINE + NEWLINE + '--' + BOUNDARY + '--');\n\t\treturn e;\n\t}", "\tstream.on('end', () => req.end(NEWLINE + NEWLINE + '--' + BOUNDARY + '--'));\n\tstream.pipe(req, STREAM_END);\n\treturn e;\n};", "exports.$$send = function(name, stream, url, cookies, headers, method, timeout) {\n\treturn function(callback) {\n\t\texports.send(name, stream, url, callback, cookies, headers, method, timeout);\n\t};\n};", "exports.upload = function(files, url, callback, cookies, headers, method, timeout) {", "\tvar BOUNDARY = '----totaljs' + Math.random().toString(16).substring(2);\n\tvar h = {};", "\theaders && exports.extend_headers2(h, headers);", "\tif (cookies) {\n\t\tvar builder = '';\n\t\tfor (var m in cookies)\n\t\t\tbuilder += (builder ? '; ' : '') + m + '=' + cookies[m];\n\t\tbuilder && (h['Cookie'] = builder);\n\t}", "\tif (global.F)\n\t\tglobal.F.stats.performance.external++;", "\th['Cache-Control'] = 'max-age=0';\n\th['Content-Type'] = 'multipart/form-data; boundary=' + BOUNDARY;", "\tvar e = new EventEmitter2();\n\tvar uri = Url.parse(url);\n\tvar options = { protocol: uri.protocol, auth: uri.auth, method: method || 'POST', hostname: uri.hostname, port: uri.port, path: uri.path, agent: false, headers: h };\n\tvar responseLength = 0;\n\tvar timeoutid;\n\tvar done = false;", "\tvar response = function(res) {", "\t\tres.body = Buffer.alloc(0);\n\t\tres._bufferlength = 0;", "\t\tres.on('data', function(chunk) {\n\t\t\tif (!done) {\n\t\t\t\tCONCAT[0] = res.body;\n\t\t\t\tCONCAT[1] = chunk;\n\t\t\t\tres.body = Buffer.concat(CONCAT);\n\t\t\t\tres._bufferlength += chunk.length;\n\t\t\t\te.$events.data && e.emit('data', chunk, responseLength ? (res._bufferlength / responseLength) * 100 : 0);\n\t\t\t}\n\t\t});", "\t\tres.on('end', function() {\n\t\t\tif (!done) {\n\t\t\t\tvar self = this;\n\t\t\t\te.$events.end && e.emit('end', self.statusCode, self.headers);\n\t\t\t\te.removeAllListeners();\n\t\t\t\tcallback && callback(null, self.body.toString('utf8'), self.statusCode, self.headers, uri.host);\n\t\t\t\ttimeoutid && clearTimeout(timeoutid);\n\t\t\t\tself.body = null;\n\t\t\t\te = null;\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t});\n\t};", "\tvar connection = options.protocol === 'https:' ? Https : Http;\n\tvar req = connection.request(options, response);", "\treq.on('response', function(response) {\n\t\tresponseLength = +response.headers['content-length'] || 0;\n\t\te.$events.begin && e.emit('begin', responseLength);\n\t});", "\tvar timeoutcallback = function() {\n\t\tif (!done) {\n\t\t\treq.removeAllListeners();\n\t\t\te.removeAllListeners();\n\t\t\tcallback && callback(new Error(exports.httpStatus(408)), '', 408, undefined, uri.host);\n\t\t\ttimeoutid && clearTimeout(timeoutid);\n\t\t\treq = null;\n\t\t\te = null;\n\t\t\tdone = true;\n\t\t}\n\t};", "\tif (timeout)\n\t\ttimeoutid = setTimeout(timeoutcallback, timeout);", "\treq.setTimeout(timeout || 60000, timeoutcallback);", "\treq.on('error', function(err) {\n\t\tdone = true;\n\t\treq.removeAllListeners();\n\t\te.removeAllListeners();\n\t\tcallback && callback(err, '', 0, undefined, uri.host);\n\t\ttimeoutid && clearTimeout(timeoutid);\n\t\treq = null;\n\t\te = null;\n\t});", "\treq.on('close', function() {\n\t\treq.removeAllListeners();\n\t\treq = null;\n\t});", "\tvar header = NEWLINE + NEWLINE + '--' + BOUNDARY + NEWLINE + 'Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"' + NEWLINE + 'Content-Type: {2}' + NEWLINE + NEWLINE;", "\tfiles.wait(function(item, next) {", "\t\t// item.name;\n\t\t// item.filename;\n\t\t// item.stream (optional) or item.buffer (optional)", "\t\treq.write(header.format(item.name, U.getName(item.filename), exports.getContentType(exports.getExtension(item.filename))));", "\t\tif (item.buffer) {\n\t\t\treq.write(item.buffer);\n\t\t\treturn next();\n\t\t}", "\t\t!item.stream && (item.stream = Fs.createReadStream(item.filename));\n\t\titem.stream.pipe(req, STREAM_END);\n\t\titem.stream.on('error', next);\n\t\titem.stream.on('end', next);", "\t}, () => req.end(NEWLINE + NEWLINE + '--' + BOUNDARY + '--'));\n\treturn e;\n};", "exports.$$upload = function(files, url, cookies, headers, method, timeout) {\n\treturn function(callback) {\n\t\texports.upload(files, url, callback, cookies, headers, method, timeout);\n\t};\n};", "/**\n * Trim string properties\n * @param {Object} obj\n * @return {Object}\n */\nexports.trim = function(obj, clean) {", "\tif (!obj)\n\t\treturn obj;", "\tvar type = typeof(obj);\n\tif (type === 'string') {\n\t\tobj = obj.trim();\n\t\treturn clean && !obj ? undefined : obj;\n\t}", "\tif (obj instanceof Array) {\n\t\tfor (var i = 0, length = obj.length; i < length; i++) {", "\t\t\tvar item = obj[i];\n\t\t\ttype = typeof(item);", "\t\t\tif (type === 'object') {\n\t\t\t\texports.trim(item, clean);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (type !== 'string')\n\t\t\t\tcontinue;", "\t\t\tobj[i] = item.trim();\n\t\t\tif (clean && !obj[i])\n\t\t\t\tobj[i] = undefined;\n\t\t}", "\t\treturn obj;\n\t}", "\tif (type !== 'object')\n\t\treturn obj;", "\tvar keys = Object.keys(obj);\n\tfor (var i = 0, length = keys.length; i < length; i++) {\n\t\tvar val = obj[keys[i]];\n\t\tvar type = typeof(val);\n\t\tif (type === 'object') {\n\t\t\texports.trim(val, clean);\n\t\t\tcontinue;\n\t\t} else if (type !== 'string')\n\t\t\tcontinue;\n\t\tobj[keys[i]] = val.trim();\n\t\tif (clean && !obj[keys[i]])\n\t\t\tobj[keys[i]] = undefined;\n\t}", "\treturn obj;\n};", "/**\n * Noop function\n * @return {Function} Empty function.\n */\nexports.noop = global.noop = global.NOOP = function() {};", "/**\n * Read HTTP status\n * @param {Number} code HTTP code status.\n * @param {Boolean} addCode Add code number to HTTP status.\n * @return {String}\n */\nexports.httpStatus = function(code, addCode) {\n\tif (addCode === undefined)\n\t\taddCode = true;\n\treturn (addCode ? code + ': ' : '') + Http.STATUS_CODES[code];\n};", "/**\n * Extend object\n * @param {Object} target Target object.\n * @param {Object} source Source object.\n * @param {Boolean} rewrite Rewrite exists values (optional, default true).\n * @return {Object} Modified object.\n */\nexports.extend = function(target, source, rewrite) {", "\tif (!target || !source)\n\t\treturn target;", "\tif (typeof(target) !== 'object' || typeof(source) !== 'object')\n\t\treturn target;", "\tif (rewrite === undefined)\n\t\trewrite = true;", "\tvar keys = Object.keys(source);\n\tvar i = keys.length;", "\twhile (i--) {\n\t\tvar key = keys[i];\n\t\tif (rewrite || target[key] === undefined)\n\t\t\ttarget[key] = exports.clone(source[key]);\n\t}", "\treturn target;\n};", "exports.extend_headers = function(first, second) {\n\tvar keys = Object.keys(first);\n\tvar headers = {};", "\tvar i = keys.length;\n\twhile (i--)\n\t\theaders[keys[i]] = first[keys[i]];", "\tkeys = Object.keys(second);\n\ti = keys.length;", "\twhile (i--)\n\t\theaders[keys[i]] = second[keys[i]];", "\treturn headers;\n};", "exports.extend_headers2 = function(first, second) {\n\tvar keys = Object.keys(second);\n\tvar i = keys.length;\n\twhile (i--)\n\t\tfirst[keys[i]] = second[keys[i]];\n\treturn first;\n};", "/**\n * Clones object\n * @param {Object} obj\n * @param {Object} skip Optional, can be only object e.g. { name: true, age: true }.\n * @param {Boolean} skipFunctions It doesn't clone functions, optional --> default false.\n * @return {Object}\n */\nglobal.CLONE = exports.clone = function(obj, skip, skipFunctions) {", "\tif (!obj)\n\t\treturn obj;", "\tvar type = typeof(obj);\n\tif (type !== 'object' || obj instanceof Date || obj instanceof Error)\n\t\treturn obj;", "\tvar length;\n\tvar o;", "\tif (obj instanceof Array) {", "\t\tlength = obj.length;\n\t\to = new Array(length);", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\ttype = typeof(obj[i]);\n\t\t\tif (type !== 'object' || obj[i] instanceof Date || obj[i] instanceof Error) {\n\t\t\t\tif (skipFunctions && type === 'function')\n\t\t\t\t\tcontinue;\n\t\t\t\to[i] = obj[i];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\to[i] = exports.clone(obj[i], skip, skipFunctions);\n\t\t}", "\t\treturn o;\n\t}", "\to = {};", "\tfor (var m in obj) {", "\t\tif (skip && skip[m])\n\t\t\tcontinue;", "\t\tvar val = obj[m];", "\t\tif (val instanceof Buffer) {\n\t\t\tvar copy = Buffer.alloc(val.length);\n\t\t\tval.copy(copy);\n\t\t\to[m] = copy;\n\t\t\tcontinue;\n\t\t}", "\t\tvar type = typeof(val);\n\t\tif (type !== 'object' || val instanceof Date || val instanceof Error) {\n\t\t\tif (skipFunctions && type === 'function')\n\t\t\t\tcontinue;\n\t\t\to[m] = val;\n\t\t\tcontinue;\n\t\t}", "\t\to[m] = exports.clone(obj[m], skip, skipFunctions);\n\t}", "\treturn o;\n};", "/**\n * Copy values from object to object\n * @param {Object} source Object source\n * @param {Object} target Object target (optional)\n * @return {Object} Modified object.\n */\nexports.copy = function(source, target) {", "\tif (target === undefined)\n\t\treturn exports.extend({}, source, true);", "\tif (!target || !source || typeof(target) !== 'object' || typeof(source) !== 'object')\n\t\treturn target;", "\tvar keys = Object.keys(source);\n\tvar i = keys.length;", "\twhile (i--) {\n\t\tvar key = keys[i];\n\t\ttarget[key] !== undefined && (target[key] = exports.clone(source[key]));\n\t}", "\treturn target;\n};", "/**\n * Reduce an object\n * @param {Object} source Source object.\n * @param {String Array or Object} prop Other properties than these ones will be removed.\n * @param {Boolean} reverse Reverse reducing (prop will be removed), default: false.\n * @return {Object}\n */\nexports.reduce = function(source, prop, reverse) {", "\tif (!(prop instanceof Array)) {\n\t\tif (typeof(prop) === 'object')\n\t\t\treturn exports.reduce(source, Object.keys(prop), reverse);\n\t}", "\tif (source instanceof Array) {\n\t\tvar arr = [];\n\t\tfor (var i = 0, length = source.length; i < length; i++)\n\t\t\tarr.push(exports.reduce(source[i], prop, reverse));\n\t\treturn arr;\n\t}", "\tvar output = {};", "\tvar keys = Object.keys(source);\n\tfor (var i = 0; i < keys.length; i++) {\n\t\tvar o = keys[i];\n\t\tif (reverse) {\n\t\t\tif (prop.indexOf(o) === -1)\n\t\t\t\toutput[o] = source[o];\n\t\t} else {\n\t\t\tif (prop.indexOf(o) !== -1)\n\t\t\t\toutput[o] = source[o];\n\t\t}\n\t}", "\treturn output;\n};", "/**\n * Assign value to an object according to a path\n * @param {Object} obj Source object.\n * @param {String} path Path to the update.\n * @param {Object or Function} fn Value or Function to update.\n * @return {Object}\n */\n// @TODO: deprecated, it will be removed in v4\nexports.assign = function(obj, path, fn) {", "\tif (obj == null)\n\t\treturn obj;", "\tvar arr = path.split('.');\n\tvar model = obj[arr[0]];", "\tfor (var i = 1; i < arr.length - 1; i++)\n\t\tmodel = model[arr[i]];", "\tmodel[arr[arr.length - 1]] = typeof (fn) === 'function' ? fn(model[arr[arr.length - 1]]) : fn;\n\treturn obj;\n};", "/**\n * Checks if is relative url\n * @param {String} url\n * @return {Boolean}\n */\nexports.isRelative = function(url) {\n\treturn !(url.substring(0, 2) === '//' || url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1);\n};", "/**\n * Streamer method\n * @param {String/Buffer} beg\n * @param {String/Buffer} end\n * @param {Function(value, index)} callback\n */\nexports.streamer = function(beg, end, callback, skip, stream, raw) {", "\tif (typeof(end) === 'function') {\n\t\tstream = skip;\n\t\tskip = callback;\n\t\tcallback = end;\n\t\tend = undefined;\n\t}", "\tif (typeof(skip) === 'object') {\n\t\tstream = skip;\n\t\tskip = 0;\n\t}", "\tvar indexer = 0;\n\tvar buffer = Buffer.alloc(0);\n\tvar canceled = false;\n\tvar fn;", "\tif (skip === undefined)\n\t\tskip = 0;", "\tif (!(beg instanceof Buffer))\n\t\tbeg = Buffer.from(beg, 'utf8');", "\tif (end && !(end instanceof Buffer))\n\t\tend = Buffer.from(end, 'utf8');", "\tif (!end) {\n\t\tvar length = beg.length;\n\t\tfn = function(chunk) {", "\t\t\tif (!chunk || canceled)\n\t\t\t\treturn;", "\t\t\tCONCAT[0] = buffer;\n\t\t\tCONCAT[1] = chunk;", "\t\t\tvar f = 0;", "\t\t\tif (buffer.length) {\n\t\t\t\tf = buffer.length - beg.length;\n\t\t\t\tif (f < 0)\n\t\t\t\t\tf = 0;\n\t\t\t}", "\t\t\tbuffer = Buffer.concat(CONCAT);", "\t\t\tvar index = buffer.indexOf(beg, f);\n\t\t\tif (index === -1)\n\t\t\t\treturn;", "\t\t\twhile (index !== -1) {", "\t\t\t\tif (skip)\n\t\t\t\t\tskip--;\n\t\t\t\telse {\n\t\t\t\t\tif (callback(raw ? buffer.slice(0, index + length) : buffer.toString('utf8', 0, index + length), indexer++) === false)\n\t\t\t\t\t\tcanceled = true;\n\t\t\t\t}", "\t\t\t\tif (canceled)\n\t\t\t\t\treturn;", "\t\t\t\tbuffer = buffer.slice(index + length);\n\t\t\t\tindex = buffer.indexOf(beg);\n\t\t\t\tif (index === -1)\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t};", "\t\tstream && stream.on('end', () => fn(beg));\n\t\treturn fn;\n\t}", "\tvar blength = beg.length;\n\tvar elength = end.length;\n\tvar bi = -1;\n\tvar ei = -1;\n\tvar is = false;", "\tfn = function(chunk) {", "\t\tif (!chunk || canceled)\n\t\t\treturn;", "\t\tCONCAT[0] = buffer;\n\t\tCONCAT[1] = chunk;\n\t\tbuffer = Buffer.concat(CONCAT);", "\t\tif (!is) {\n\t\t\tvar f = CONCAT[0].length - beg.length;\n\t\t\tif (f < 0)\n\t\t\t\tf = 0;\n\t\t\tbi = buffer.indexOf(beg, f);\n\t\t\tif (bi === -1)\n\t\t\t\treturn;\n\t\t\tis = true;\n\t\t}", "\t\tif (is) {\n\t\t\tei = buffer.indexOf(end, bi + blength);\n\t\t\tif (ei === -1)\n\t\t\t\treturn;\n\t\t}", "\t\twhile (bi !== -1) {", "\t\t\tif (skip)\n\t\t\t\tskip--;\n\t\t\telse {\n\t\t\t\tif (callback(raw ? buffer.slice(bi, ei + elength) : buffer.toString('utf8', bi, ei + elength), indexer++) === false)\n\t\t\t\t\tcanceled = true;\n\t\t\t}", "\t\t\tif (canceled)\n\t\t\t\treturn;", "\t\t\tbuffer = buffer.slice(ei + elength);\n\t\t\tis = false;\n\t\t\tbi = buffer.indexOf(beg);\n\t\t\tif (bi === -1)\n\t\t\t\treturn;\n\t\t\tis = true;\n\t\t\tei = buffer.indexOf(end, bi + blength);\n\t\t\tif (ei === -1)\n\t\t\t\treturn;\n\t\t}\n\t};", "\tstream && stream.on('end', () => fn(end));\n\treturn fn;\n};", "exports.streamer2 = function(beg, end, callback, skip, stream) {\n\treturn exports.streamer(beg, end, callback, skip, stream, true);\n};", "/**\n * HTML encode string\n * @param {String} str\n * @return {String}\n */\nexports.encode = function(str) {", "\tif (str == null)\n\t\treturn '';", "\tvar type = typeof(str);\n\tif (type !== 'string')\n\t\tstr = str.toString();", "\treturn str.encode();\n};", "/**\n * HTML decode string\n * @param {String} str\n * @return {String}\n */\nexports.decode = function(str) {", "\tif (str == null)\n\t\treturn '';", "\tvar type = typeof(str);\n\tif (type !== 'string')\n\t\tstr = str.toString();", "\treturn str.decode();\n};", "/**\n * Checks if URL contains file extension.\n * @param {String} url\n * @return {Boolean}\n */\nexports.isStaticFile = function(url) {\n\treturn regexpSTATIC.test(url);\n};", "/**\n * Converts Value to number\n * @param {Object} obj Value to convert.\n * @param {Number} def Default value (default: 0).\n * @return {Number}\n */\nexports.parseInt = function(obj, def) {\n\tif (obj == null || obj === '')\n\t\treturn def === undefined ? 0 : def;\n\tvar type = typeof(obj);\n\treturn type === 'number' ? obj : (type !== 'string' ? obj.toString() : obj).parseInt(def);\n};", "exports.parseBool = exports.parseBoolean = function(obj, def) {\n\tif (obj == null)\n\t\treturn def === undefined ? false : def;\n\tvar type = typeof(obj);\n\treturn type === 'boolean' ? obj : type === 'number' ? obj > 0 : (type !== 'string' ? obj.toString() : obj).parseBool(def);\n};", "/**\n * Converts Value to float number\n * @param {Object} obj Value to convert.\n * @param {Number} def Default value (default: 0).\n * @return {Number}\n */\nexports.parseFloat = function(obj, def) {\n\tif (obj == null || obj === '')\n\t\treturn def === undefined ? 0 : def;\n\tvar type = typeof(obj);\n\treturn type === 'number' ? obj : (type !== 'string' ? obj.toString() : obj).parseFloat(def);\n};", "/**\n * Check if the object is Array.\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isArray = function(obj) {\n\treturn obj instanceof Array;\n};", "/**\n * Check if the object is RegExp\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isRegExp = function(obj) {\n\treturn obj && typeof(obj.test) === 'function' ? true : false;\n};", "/**\n * Check if the object is Date\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isDate = function(obj) {\n\treturn obj instanceof Date && !isNaN(obj.getTime()) ? true : false;\n};", "/**\n * Check if the object is Date\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isError = function(obj) {\n\treturn (obj && obj.stack) ? true : false;\n};", "/**\n * Check if the value is object\n * @param {Object} value\n * @return {Boolean}\n */\nexports.isObject = function(value) {\n\ttry {\n\t\treturn (value && Object.getPrototypeOf(value) === Object.prototype) ? true : false;\n\t} catch (e) {\n\t\treturn false;\n\t}\n};", "/**\n * Get ContentType from file extension.\n * @param {String} ext File extension.\n * @return {String}\n */\nexports.getContentType = function(ext) {\n\tif (ext[0] === '.')\n\t\text = ext.substring(1);\n\treturn CONTENTTYPES[ext] || 'application/octet-stream';\n};", "/**\n * Get extension from filename\n * @param {String} filename\n * @return {String}\n */\nexports.getExtension = function(filename, raw) {\n\tvar end = filename.length;\n\tfor (var i = filename.length - 1; i > 0; i--) {\n\t\tvar c = filename[i];\n\t\tif (c === ' ' || c === '?')\n\t\t\tend = i;\n\t\telse if (c === '.') {\n\t\t\tc = filename.substring(i + 1, end);\n\t\t\treturn raw ? c : c.toLowerCase();\n\t\t}\n\t\telse if (c === '/' || c === '\\\\')\n\t\t\treturn '';\n\t}\n\treturn '';\n};", "/**\n * Get base name from path\n * @param {String} path\n * @return {String}\n */\nexports.getName = function(path) {\n\tvar l = path.length - 1;\n\tvar c = path[l];\n\tif (c === '/' || c === '\\\\')\n\t\tpath = path.substring(0, l);\n\tvar index = path.lastIndexOf('/');\n\tif (index !== -1)\n\t\treturn path.substring(index + 1);\n\tindex = path.lastIndexOf('\\\\');\n\treturn index === -1 ? path : path.substring(index + 1);\n};", "/**\n * Add a new content type to content types\n * @param {String} ext File extension.\n * @param {String} type Content type (example: application/json).\n */\nexports.setContentType = function(ext, type) {\n\tif (ext[0] === '.')\n\t\text = ext.substring(1);", "\tif (ext.length > 8) {\n\t\tvar tmp = regexpSTATIC.toString().replace(/,\\d+\\}/, ',' + ext.length + '}').substring(1);\n\t\tregexpSTATIC = new RegExp(tmp.substring(0, tmp.length - 1));\n\t}", "\tCONTENTTYPES[ext] = type;\n\treturn true;\n};", "exports.path = function(path, delimiter) {\n\tif (!path)\n\t\tpath = '';\n\tdelimiter = delimiter || '/';\n\treturn path[path.length - 1] === delimiter ? path : path + delimiter;\n};", "exports.join = function() {\n\tvar path = [''];", "\tfor (var i = 0; i < arguments.length; i++) {\n\t\tvar current = arguments[i];\n\t\tif (!current)\n\t\t\tcontinue;\n\t\tif (current[0] === '/')\n\t\t\tcurrent = current.substring(1);\n\t\tvar l = current.length - 1;\n\t\tif (current[l] === '/')\n\t\t\tcurrent = current.substring(0, l);\n\t\tpath.push(current);\n\t}", "\tpath = path.join('/');\n\treturn !isWindows ? path : path.indexOf(':') > -1 ? path.substring(1) : path;\n};", "/**\n * Prepares Windows path to UNIX like format\n * @internal\n * @param {String} path\n * @return {String}\n */\nexports.$normalize = function(path) {\n\treturn isWindows ? path.replace(regexpPATH, '/') : path;\n};", "exports.random = function(max, min) {\n\tmax = (max || 100000);\n\tmin = (min || 0);\n\treturn Math.floor(Math.random() * (max - min + 1)) + min;\n};", "function rnd() {\n\treturn Math.floor(Math.random() * 65536).toString(36);\n}", "global.GUID = exports.GUID = function(max) {\n\tmax = max || 40;\n\tvar str = '';\n\tfor (var i = 0; i < (max / 3) + 1; i++)\n\t\tstr += rnd();\n\treturn str.substring(0, max);\n};", "function validate_builder_default(name, value, entity) {", "\tvar type = typeof(value);", "\tif (entity.type === 12)\n\t\treturn value != null && type === 'object' && !(value instanceof Array);", "\tif (entity.type === 11)\n\t\treturn type === 'number';", "\t// Enum + KeyValue + Custom (8+9+10)\n\tif (entity.type > 7)\n\t\treturn value !== undefined;", "\tswitch (entity.subtype) {\n\t\tcase 'uid':\n\t\t\treturn value.isUID();\n\t\tcase 'zip':\n\t\t\treturn value.isZIP();\n\t\tcase 'email':\n\t\t\treturn value.isEmail();\n\t\tcase 'json':\n\t\t\treturn value.isJSON();\n\t\tcase 'url':\n\t\t\treturn value.isURL();\n\t\tcase 'phone':\n\t\t\treturn value.isPhone();\n\t\tcase 'base64':\n\t\t\treturn value.isBase64();\n\t}", "\tif (type === 'number')\n\t\treturn value > 0;", "\tif (type === 'string' || value instanceof Array)\n\t\treturn value.length > 0;", "\tif (type === 'boolean')\n\t\treturn value === true;", "\tif (value == null)\n\t\treturn false;", "\tif (value instanceof Date)\n\t\treturn value.toString()[0] !== 'I'; // Invalid Date", "\treturn true;\n}", "exports.validate_builder = function(model, error, schema, path, index, fields, pluspath) {", "\tvar prepare = schema.onValidate || F.onValidate || NOOP;\n\tvar current = path ? path + '.' : '';\n\tvar properties = model && model.$$keys ? model.$$keys : schema.properties;\n\tvar result;", "\tif (!pluspath)\n\t\tpluspath = '';", "\tif (model == null)\n\t\tmodel = {};", "\tfor (var i = 0; i < properties.length; i++) {", "\t\tvar name = properties[i];", "\t\tif (fields && fields.indexOf(name) === -1)\n\t\t\tcontinue;", "\t\tvar TYPE = schema.schema[name];\n\t\tif (!TYPE)\n\t\t\tcontinue;", "\t\tif (TYPE.can && !TYPE.can(model, model.$$workflow || EMPTYOBJECT))\n\t\t\tcontinue;", "\t\tvar value = model[name];\n\t\tvar type = typeof(value);\n\t\tvar prefix = schema.resourcePrefix ? (schema.resourcePrefix + name) : name;", "\t\tif (value === undefined) {\n\t\t\terror.push(pluspath + name, '@', current + name, undefined, prefix);\n\t\t\tcontinue;\n\t\t} else if (type === 'function')\n\t\t\tvalue = model[name]();", "\t\tif (TYPE.isArray) {\n\t\t\tif (TYPE.type === 7 && value instanceof Array && value.length) {\n\t\t\t\tvar nestedschema = schema.parent.collection[TYPE.raw] || GETSCHEMA(TYPE.raw);\n\t\t\t\tif (nestedschema) {\n\t\t\t\t\tfor (var j = 0, jl = value.length; j < jl; j++)\n\t\t\t\t\t\texports.validate_builder(value[j], error, nestedschema, current + name + '[' + j + ']', j, undefined, pluspath);\n\t\t\t\t} else\n\t\t\t\t\tthrow new Error('Nested schema \"{0}\" not found in \"{1}\".'.format(TYPE.raw, schema.parent.name));\n\t\t\t} else {", "\t\t\t\tif (!TYPE.required)\n\t\t\t\t\tcontinue;", "\t\t\t\tresult = TYPE.validate ? TYPE.validate(value, model) : prepare(name, value, current + name, model, schema.name, TYPE);\n\t\t\t\tif (result == null) {\n\t\t\t\t\tresult = value instanceof Array ? value.length > 0 : false;\n\t\t\t\t\tif (result == null || result === true)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}", "\t\t\t\ttype = typeof(result);\n\t\t\t\tif (type === 'string') {\n\t\t\t\t\tif (result[0] === '@')\n\t\t\t\t\t\terror.push(pluspath + name, '@', current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\t\t\telse\n\t\t\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t\t\t} else if (type === 'boolean') {\n\t\t\t\t\t!result && error.push(pluspath + name, '@', current + name, index, prefix);\n\t\t\t\t} else if (result.isValid === false)\n\t\t\t\t\terror.push(pluspath + name, result.error, current + name, index, prefix);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}", "\t\tif (TYPE.type === 7) {", "\t\t\tif (!value && !TYPE.required)\n\t\t\t\tcontinue;", "\t\t\t// Another schema\n\t\t\tresult = TYPE.validate ? TYPE.validate(value, model) : null;", "\t\t\tif (result == null) {\n\t\t\t\tvar nestedschema = schema.parent.collection[TYPE.raw] || GETSCHEMA(TYPE.raw);\n\t\t\t\tif (nestedschema)\n\t\t\t\t\texports.validate_builder(value, error, nestedschema, current + name, undefined, undefined, pluspath);\n\t\t\t\telse\n\t\t\t\t\tthrow new Error('Nested schema \"{0}\" not found in \"{1}\".'.format(TYPE.raw, schema.parent.name));\n\t\t\t} else {\n\t\t\t\ttype = typeof(result);\n\t\t\t\tif (type === 'string') {\n\t\t\t\t\tif (result[0] === '@')\n\t\t\t\t\t\terror.push(pluspath + name, '@', current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\t\t\telse\n\t\t\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t\t\t} else if (type === 'boolean') {\n\t\t\t\t\t!result && error.push(pluspath + name, '@', current + name, index, prefix);\n\t\t\t\t} else if (result.isValid === false)\n\t\t\t\t\terror.push(pluspath + name, result.error, current + name, index, prefix);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}", "\t\tif (!TYPE.required)\n\t\t\tcontinue;", "\t\tresult = TYPE.validate ? TYPE.validate(value, model) : prepare(name, value, current + name, model, schema.name, TYPE);\n\t\tif (result == null) {\n\t\t\tresult = validate_builder_default(name, value, TYPE);\n\t\t\tif (result == null || result === true)\n\t\t\t\tcontinue;\n\t\t}", "\t\ttype = typeof(result);", "\t\tif (type === 'string') {\n\t\t\tif (result[0] === '@')\n\t\t\t\terror.push(pluspath + name, '@', current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\telse\n\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t} else if (type === 'boolean') {\n\t\t\t!result && error.push(pluspath + name, '@', current + name, index, prefix);\n\t\t} else if (result.isValid === false)\n\t\t\terror.push(pluspath + name, result.error, current + name, index, prefix);\n\t}", "\treturn error;\n};", "/**\n * Combine paths\n * @return {String}\n */\nexports.combine = function() {", "\tvar p = F.directory;", "\tfor (var i = 0, length = arguments.length; i < length; i++) {\n\t\tvar v = arguments[i];\n\t\tif (!v)\n\t\t\tcontinue;\n\t\tif (v[0] === '/')\n\t\t\tv = v.substring(1);", "\t\tif (v[0] === '~')\n\t\t\tp = v.substring(1);\n\t\telse\n\t\t\tp += (p[p.length - 1] !== '/' ? '/' : '') + v;\n\t}\n\treturn exports.$normalize(p);\n};", "/**\n * Remove diacritics\n * @param {String} str\n * @return {String}\n */\nexports.removeDiacritics = function(str) {\n\treturn str.replace(regexpDiacritics, c => DIACRITICSMAP[c] || c);\n};", "/**\n * Simple XML parser\n * @param {String} xml\n * @return {Object}\n */\nexports.parseXML = function(xml, replace) {", "\tvar beg = -1;\n\tvar end = 0;\n\tvar tmp = 0;\n\tvar current = [];\n\tvar obj = {};\n\tvar from = -1;", "\twhile (true) {\n\t\tbeg = xml.indexOf('<![CDATA[', beg);\n\t\tif (beg === -1)\n\t\t\tbreak;\n\t\tend = xml.indexOf(']]>', beg + 9);\n\t\txml = xml.substring(0, beg) + xml.substring(beg + 9, end).trim().encode() + xml.substring(end + 3);\n\t\tbeg += 9;\n\t}", "\tbeg = -1;\n\tend = 0;", "\twhile (true) {", "\t\tbeg = xml.indexOf('<', beg + 1);\n\t\tif (beg === -1)\n\t\t\tbreak;", "\t\tend = xml.indexOf('>', beg + 1);\n\t\tif (end === -1)\n\t\t\tbreak;", "\t\tvar el = xml.substring(beg, end + 1);\n\t\tvar c = el[1];", "\t\tif (c === '?' || c === '/') {", "\t\t\tvar o = current.pop();", "\t\t\tif (from === -1 || o !== el.substring(2, el.length - 1))\n\t\t\t\tcontinue;", "\t\t\tvar path = (current.length ? current.join('.') + '.' : '') + o;\n\t\t\tvar value = xml.substring(from, beg).decode();", "\t\t\tif (replace)\n\t\t\t\tpath = path.replace(REG_XMLKEY, '_');", "\t\t\tif (obj[path] === undefined)\n\t\t\t\tobj[path] = value;\n\t\t\telse if (obj[path] instanceof Array)\n\t\t\t\tobj[path].push(value);\n\t\t\telse\n\t\t\t\tobj[path] = [obj[path], value];", "\t\t\tfrom = -1;\n\t\t\tcontinue;\n\t\t}", "\t\ttmp = el.indexOf(' ');\n\t\tvar hasAttributes = true;", "\t\tif (tmp === -1) {\n\t\t\ttmp = el.length - 1;\n\t\t\thasAttributes = false;\n\t\t}", "\t\tfrom = beg + el.length;", "\t\tvar isSingle = el[el.length - 2] === '/';\n\t\tvar name = el.substring(1, tmp);", "\t\tif (!isSingle)\n\t\t\tcurrent.push(name);", "\t\tif (!hasAttributes)\n\t\t\tcontinue;", "\t\tvar match = el.match(regexpXML);\n\t\tif (!match)\n\t\t\tcontinue;", "\t\tvar attr = {};\n\t\tvar length = match.length;", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\tvar index = match[i].indexOf('\"');\n\t\t\tattr[match[i].substring(0, index - 1)] = match[i].substring(index + 1, match[i].length - 1).decode();\n\t\t}", "\t\tvar k = current.join('.') + (isSingle ? '.' + name : '') + '[]';\n\t\tif (replace)\n\t\t\tk = k.replace(REG_XMLKEY, '_');\n\t\tobj[k] = attr;\n\t}", "\treturn obj;\n};", "exports.parseJSON = function(value, date) {\n\ttry {\n\t\treturn JSON.parse(value, date ? jsonparser : undefined);\n\t} catch(e) {\n\t}\n};", "exports.parseQuery = function(value) {\n\treturn F.onParseQuery(value);\n};", "function jsonparser(key, value) {\n\treturn typeof(value) === 'string' && value.isJSONDate() ? new Date(value) : value;\n}", "/**\n * Get WebSocket frame\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} code\n * @param {Buffer or String} message\n * @param {Hexa} type\n * @return {Buffer}\n */\nexports.getWebSocketFrame = function(code, message, type, compress) {\n\tvar messageBuffer = getWebSocketFrameMessageBytes(code, message);\n\tvar lengthBuffer = getWebSocketFrameLengthBytes(messageBuffer.length);\n\tvar frameBuffer = Buffer.alloc(1 + lengthBuffer.length + messageBuffer.length);\n\tframeBuffer[0] = 0x80 | type;\n\tcompress && (frameBuffer[0] |= 0x40);\n\tlengthBuffer.copy(frameBuffer, 1, 0, lengthBuffer.length);\n\tmessageBuffer.copy(frameBuffer, lengthBuffer.length + 1, 0, messageBuffer.length);\n\treturn frameBuffer;\n};", "/**\n * Get bytes of WebSocket frame message\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} code\n * @param {Buffer or String} message\n * @return {Buffer}\n */\nfunction getWebSocketFrameMessageBytes(code, message) {", "\tvar index = code ? 2 : 0;\n\tvar binary = message instanceof Int8Array || message instanceof Buffer;\n\tvar length = message.length;", "\tvar messageBuffer = Buffer.alloc(length + index);", "\tfor (var i = 0; i < length; i++) {\n\t\tif (binary)\n\t\t\tmessageBuffer[i + index] = message[i];\n\t\telse\n\t\t\tmessageBuffer[i + index] = message.charCodeAt(i);\n\t}", "\tif (code) {\n\t\tmessageBuffer[0] = code >> 8;\n\t\tmessageBuffer[1] = code;\n\t}", "\treturn messageBuffer;\n}", "/**\n * Get length of WebSocket frame\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} length\n * @return {Number}\n */\nfunction getWebSocketFrameLengthBytes(length) {\n\tvar lengthBuffer = null;", "\tif (length <= 125) {\n\t\tlengthBuffer = Buffer.alloc(1);\n\t\tlengthBuffer[0] = length;\n\t\treturn lengthBuffer;\n\t}", "\tif (length <= 65535) {\n\t\tlengthBuffer = Buffer.alloc(3);\n\t\tlengthBuffer[0] = 126;\n\t\tlengthBuffer[1] = (length >> 8) & 255;\n\t\tlengthBuffer[2] = (length) & 255;\n\t\treturn lengthBuffer;\n\t}", "\tlengthBuffer = Buffer.alloc(9);", "\tlengthBuffer[0] = 127;\n\tlengthBuffer[1] = 0x00;\n\tlengthBuffer[2] = 0x00;\n\tlengthBuffer[3] = 0x00;\n\tlengthBuffer[4] = 0x00;\n\tlengthBuffer[5] = (length >> 24) & 255;\n\tlengthBuffer[6] = (length >> 16) & 255;\n\tlengthBuffer[7] = (length >> 8) & 255;\n\tlengthBuffer[8] = (length) & 255;", "\treturn lengthBuffer;\n}", "/**\n * GPS distance in KM\n * @param {Number} lat1\n * @param {Number} lon1\n * @param {Number} lat2\n * @param {Number} lon2\n * @return {Number}\n */\nexports.distance = function(lat1, lon1, lat2, lon2) {\n\tvar R = 6371;\n\tvar dLat = (lat2 - lat1).toRad();\n\tvar dLon = (lon2 - lon1).toRad();\n\tvar a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon / 2) * Math.sin(dLon / 2);\n\tvar c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\treturn (R * c).floor(3);\n};", "function ls(path, callback, advanced, filter) {\n\tvar filelist = new FileList();\n\tvar tmp;", "\tfilelist.advanced = advanced;\n\tfilelist.onComplete = callback;", "\tif (typeof(filter) === 'string') {\n\t\ttmp = filter.toLowerCase();\n\t\tfilelist.onFilter = function(filename, is) {\n\t\t\treturn is ? true : filename.toLowerCase().indexOf(tmp) !== -1;\n\t\t};\n\t} else if (exports.isRegExp(filter)) {\n\t\ttmp = filter;\n\t\tfilelist.onFilter = function(filename, is) {\n\t\t\treturn is ? true : tmp.test(filename);\n\t\t};\n\t} else\n\t\tfilelist.onFilter = filter || null;", "\tfilelist.walk(path);\n}", "/**\n * Directory listing\n * @param {String} path Path.\n * @param {Function(files, directories)} callback Callback\n * @param {Function(filename, isDirectory) or String or RegExp} filter Custom filter (optional).\n */\nexports.ls = function(path, callback, filter) {\n\tls(path, callback, false, filter);\n};", "/**\n * Advanced Directory listing\n * @param {String} path Path.\n * @param {Function(files, directories)} callback Callback\n * @param {Function(filename ,isDirectory) or String or RegExp} filter Custom filter (optional).\n */\nexports.ls2 = function(path, callback, filter) {\n\tls(path, callback, true, filter);\n};", "DP.setTimeZone = function(timezone) {\n\tvar dt = this.toLocaleString('en-US', { timeZone: timezone, hour12: false, dateStyle: 'short', timeStyle: 'short' });\n\treturn new Date(Date.parse(dt));\n};", "DP.add = function(type, value) {", "\tvar self = this;", "\tif (type.constructor === Number)\n\t\treturn new Date(self.getTime() + (type - type % 1));", "\tif (value === undefined) {\n\t\tvar arr = type.split(' ');\n\t\ttype = arr[1];\n\t\tvalue = exports.parseInt(arr[0]);\n\t}", "\tvar dt = new Date(self.getTime());", "\tswitch(type) {\n\t\tcase 's':\n\t\tcase 'ss':\n\t\tcase 'sec':\n\t\tcase 'second':\n\t\tcase 'seconds':\n\t\t\tdt.setUTCSeconds(dt.getUTCSeconds() + value);\n\t\t\treturn dt;\n\t\tcase 'm':\n\t\tcase 'mm':\n\t\tcase 'minute':\n\t\tcase 'min':\n\t\tcase 'minutes':\n\t\t\tdt.setUTCMinutes(dt.getUTCMinutes() + value);\n\t\t\treturn dt;\n\t\tcase 'h':\n\t\tcase 'hh':\n\t\tcase 'hour':\n\t\tcase 'hours':\n\t\t\tdt.setUTCHours(dt.getUTCHours() + value);\n\t\t\treturn dt;\n\t\tcase 'd':\n\t\tcase 'dd':\n\t\tcase 'day':\n\t\tcase 'days':\n\t\t\tdt.setUTCDate(dt.getUTCDate() + value);\n\t\t\treturn dt;\n\t\tcase 'w':\n\t\tcase 'ww':\n\t\tcase 'week':\n\t\tcase 'weeks':\n\t\t\tdt.setUTCDate(dt.getUTCDate() + (value * 7));\n\t\t\treturn dt;\n\t\tcase 'M':\n\t\tcase 'MM':\n\t\tcase 'month':\n\t\tcase 'months':\n\t\t\tdt.setUTCMonth(dt.getUTCMonth() + value);\n\t\t\treturn dt;\n\t\tcase 'y':\n\t\tcase 'yyyy':\n\t\tcase 'year':\n\t\tcase 'years':\n\t\t\tdt.setUTCFullYear(dt.getUTCFullYear() + value);\n\t\t\treturn dt;\n\t}\n\treturn dt;\n};", "/**\n * Date difference\n * @param {Date/Number/String} date Optional.\n * @param {String} type Date type: minutes, seconds, hours, days, months, years\n * @return {Number}\n */\nDP.diff = function(date, type) {", "\tif (arguments.length === 1) {\n\t\ttype = date;\n\t\tdate = Date.now();\n\t} else {\n\t\tvar to = typeof(date);\n\t\tif (to === 'string')\n\t\t\tdate = Date.parse(date);\n\t\telse if (exports.isDate(date))\n\t\t\tdate = date.getTime();\n\t}", "\tvar r = this.getTime() - date;", "\tswitch (type) {\n\t\tcase 's':\n\t\tcase 'ss':\n\t\tcase 'second':\n\t\tcase 'seconds':\n\t\t\treturn Math.ceil(r / 1000);\n\t\tcase 'm':\n\t\tcase 'mm':\n\t\tcase 'minute':\n\t\tcase 'minutes':\n\t\t\treturn Math.ceil((r / 1000) / 60);\n\t\tcase 'h':\n\t\tcase 'hh':\n\t\tcase 'hour':\n\t\tcase 'hours':\n\t\t\treturn Math.ceil(((r / 1000) / 60) / 60);\n\t\tcase 'd':\n\t\tcase 'dd':\n\t\tcase 'day':\n\t\tcase 'days':\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / 24);\n\t\tcase 'M':\n\t\tcase 'MM':\n\t\tcase 'month':\n\t\tcase 'months':\n\t\t\t// avg: 28 days per month\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / (24 * 28));", "\t\tcase 'y':\n\t\tcase 'yyyy':\n\t\tcase 'year':\n\t\tcase 'years':\n\t\t\t// avg: 28 days per month\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / (24 * 28 * 12));\n\t}", "\treturn NaN;\n};", "DP.extend = function(date) {\n\tvar dt = new Date(this);\n\tvar match = date.match(regexpDATE);", "\tif (!match)\n\t\treturn dt;", "\tfor (var i = 0, length = match.length; i < length; i++) {\n\t\tvar m = match[i];\n\t\tvar arr, tmp;", "\t\tif (m.indexOf(':') !== -1) {", "\t\t\tarr = m.split(':');\n\t\t\ttmp = +arr[0];\n\t\t\ttmp >= 0 && dt.setUTCHours(tmp);", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\ttmp >= 0 && dt.setUTCMinutes(tmp);\n\t\t\t}", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\ttmp >= 0 && dt.setUTCSeconds(tmp);\n\t\t\t}", "\t\t\tcontinue;\n\t\t}", "\t\tif (m.indexOf('-') !== -1) {\n\t\t\tarr = m.split('-');", "\t\t\ttmp = +arr[0];\n\t\t\ttmp && dt.setUTCFullYear(tmp);", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\ttmp >= 0 && dt.setUTCMonth(tmp - 1);\n\t\t\t}", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\ttmp >= 0 && dt.setUTCDate(tmp);\n\t\t\t}", "\t\t\tcontinue;\n\t\t}", "\t\tif (m.indexOf('.') !== -1) {\n\t\t\tarr = m.split('.');", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\t!isNaN(tmp) && dt.setUTCFullYear(tmp);\n\t\t\t}", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\t!isNaN(tmp) && dt.setUTCMonth(tmp - 1);\n\t\t\t}", "\t\t\ttmp = +arr[0];\n\t\t\t!isNaN(tmp) && dt.setUTCDate(tmp);", "\t\t\tcontinue;\n\t\t}\n\t}", "\treturn dt;\n};", "/**\n * Compare dates\n * @param {Date} date\n * @return {Number} Results: -1 = current date is earlier than @date, 0 = current date is same as @date, 1 = current date is later than @date\n */\nDP.compare = function(date) {", "\tvar self = this;\n\tvar r = self.getTime() - date.getTime();", "\tif (r === 0)\n\t\treturn 0;", "\tif (r < 0)\n\t\treturn -1;", "\treturn 1;\n};", "/**\n * Compare two dates\n * @param {String or Date} d1\n * @param {String or Date} d2\n * @return {Number} Results: -1 = @d1 is earlier than @d2, 0 = @d1 is same as @d2, 1 = @d1 is later than @d2\n */\nDate.compare = function(d1, d2) {", "\tif (typeof(d1) === 'string')\n\t\td1 = d1.parseDate();", "\tif (typeof(d2) === 'string')\n\t\td2 = d2.parseDate();", "\treturn d1.compare(d2);\n};", "/**\n * Format datetime\n * @param {String} format\n * @return {String}\n */\nDP.format = function(format, resource) {", "\tif (!format)\n\t\treturn this.getUTCFullYear() + '-' + (this.getUTCMonth() + 1).toString().padLeft(2, '0') + '-' + this.getUTCDate().toString().padLeft(2, '0') + 'T' + this.getUTCHours().toString().padLeft(2, '0') + ':' + this.getUTCMinutes().toString().padLeft(2, '0') + ':' + this.getUTCSeconds().toString().padLeft(2, '0') + '.' + this.getUTCMilliseconds().toString().padLeft(3, '0') + 'Z';", "\tif (datetimeformat[format])\n\t\treturn datetimeformat[format](this, resource);", "\tvar key = format;\n\tvar half = false;", "\tif (format && format[0] === '!') {\n\t\thalf = true;\n\t\tformat = format.substring(1);\n\t}", "\tvar beg = '\\'+';\n\tvar end = '+\\'';\n\tvar before = [];", "\tvar ismm = false;\n\tvar isdd = false;\n\tvar isww = false;", "\tformat = format.replace(regexpDATEFORMAT, function(key) {\n\t\tswitch (key) {\n\t\t\tcase 'yyyy':\n\t\t\tcase 'YYYY':\n\t\t\t\treturn beg + 'd.getFullYear()' + end;\n\t\t\tcase 'yy':\n\t\t\tcase 'YY':\n\t\t\t\treturn beg + 'd.getFullYear().toString().substring(2)' + end;\n\t\t\tcase 'MMM':\n\t\t\t\tismm = true;\n\t\t\t\treturn beg + '(F.resource(resource, mm) || mm).substring(0, 3)' + end;\n\t\t\tcase 'MMMM':\n\t\t\t\tismm = true;\n\t\t\t\treturn beg + '(F.resource(resource, mm) || mm)' + end;\n\t\t\tcase 'MM':\n\t\t\t\treturn beg + '(d.getMonth() + 1).toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'M':\n\t\t\t\treturn beg + '(d.getMonth() + 1)' + end;\n\t\t\tcase 'ddd':\n\t\t\tcase 'DDD':\n\t\t\t\tisdd = true;\n\t\t\t\treturn beg + '(F.resource(resource, dd) || dd).substring(0, 2).toUpperCase()' + end;\n\t\t\tcase 'dddd':\n\t\t\tcase 'DDDD':\n\t\t\t\tisdd = true;\n\t\t\t\treturn beg + '(F.resource(resource, dd) || dd)' + end;\n\t\t\tcase 'dd':\n\t\t\tcase 'DD':\n\t\t\t\treturn beg + 'd.getDate().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'd':\n\t\t\tcase 'D':\n\t\t\t\treturn beg + 'd.getDate()' + end;\n\t\t\tcase 'HH':\n\t\t\tcase 'hh':\n\t\t\t\treturn beg + (half ? 'framework_utils.$pmam(d.getHours()).toString().padLeft(2, \\'0\\')' : 'd.getHours().toString().padLeft(2, \\'0\\')') + end;\n\t\t\tcase 'H':\n\t\t\tcase 'h':\n\t\t\t\treturn beg + (half ? 'framework_utils(d.getHours())' : 'd.getHours()') + end;\n\t\t\tcase 'mm':\n\t\t\t\treturn beg + 'd.getMinutes().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'm':\n\t\t\t\treturn beg + 'd.getMinutes()' + end;\n\t\t\tcase 'ss':\n\t\t\t\treturn beg + 'd.getSeconds().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 's':\n\t\t\t\treturn beg + 'd.getSeconds()' + end;\n\t\t\tcase 'w':\n\t\t\tcase 'ww':\n\t\t\t\tisww = true;\n\t\t\t\treturn beg + (key === 'ww' ? 'ww.toString().padLeft(2, \\'0\\')' : 'ww') + end;\n\t\t\tcase 'a':\n\t\t\t\tvar b = \"'PM':'AM'\";\n\t\t\t\treturn beg + '(d.getHours() >= 12 ? ' + b + ')' + end;\n\t\t}\n\t});", "\tismm && before.push('var mm = framework_utils.MONTHS[d.getMonth()];');\n\tisdd && before.push('var dd = framework_utils.DAYS[d.getDay()];');\n\tisww && before.push('var ww = new Date(+d);ww.setHours(0, 0, 0);ww.setDate(ww.getDate() + 4 - (ww.getDay() || 7));ww = Math.ceil((((ww - new Date(ww.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7);');", "\tdatetimeformat[key] = new Function('d', 'resource', before.join('\\n') + 'return \\'' + format + '\\';');\n\treturn datetimeformat[key](this, resource);\n};", "exports.$pmam = function(value) {\n\treturn value >= 12 ? value - 12 : value;\n};", "DP.toUTC = function(ticks) {\n\tvar dt = this.getTime() + this.getTimezoneOffset() * 60000;\n\treturn ticks ? dt : new Date(dt);\n};", "// +v2.2.0 parses JSON dates as dates and this is the fallback for backward compatibility\nDP.parseDate = function() {\n\treturn this;\n};", "SP.isJSONDate = function() {\n\tvar l = this.length - 1;\n\treturn l > 22 && l < 30 && this[l] === 'Z' && this[10] === 'T' && this[4] === '-' && this[13] === ':' && this[16] === ':';\n};", "SP.ROOT = function(noremap) {", "\tvar str = this;", "\tstr = str.replace(REG_NOREMAP, function() {\n\t\tnoremap = true;\n\t\treturn '';\n\t}).replace(REG_ROOT, $urlmaker);", "\tif (!noremap && CONF.default_root)\n\t\tstr = str.replace(REG_REMAP, $urlremap).replace(REG_AJAX, $urlajax);", "\treturn str;\n};", "function $urlremap(text) {\n\tvar pos = text[0] === 'h' ? 6 : 5;\n\treturn REG_URLEXT.test(text) ? text : ((text[0] === 'h' ? 'href' : 'src') + '=\"' + CONF.default_root + (text[pos] === '/' ? text.substring(pos + 1) : text));\n}", "function $urlajax(text) {\n\treturn text.substring(0, text.length - 1) + CONF.default_root;\n}", "function $urlmaker(text) {\n\tvar c = text[4];\n\treturn CONF.default_root ? CONF.default_root : (c || '');\n}", "if (!SP.trim) {\n\tSP.trim = function() {\n\t\treturn this.replace(regexpTRIM, '');\n\t};\n}", "if (!SP.replaceAt) {\n\tSP.replaceAt = function(index, character) {\n\t\treturn this.substr(0, index) + character + this.substr(index + character.length);\n\t};\n}", "/**\n * Checks if the string starts with the text\n * @see {@link http://docs.totaljs.com/SP/#SP.startsWith|Documentation}\n * @param {String} text Text to find.\n * @param {Boolean/Number} ignoreCase Ingore case sensitive or position in the string.\n * @return {Boolean}\n */\nSP.startsWith = function(text, ignoreCase) {\n\tvar self = this;\n\tvar length = text.length;\n\tvar tmp;", "\tif (ignoreCase === true) {\n\t\ttmp = self.substring(0, length);\n\t\treturn tmp.length === length && tmp.toLowerCase() === text.toLowerCase();\n\t}", "\tif (ignoreCase)\n\t\ttmp = self.substr(ignoreCase, length);\n\telse\n\t\ttmp = self.substring(0, length);", "\treturn tmp.length === length && tmp === text;\n};", "/**\n * Checks if the string ends with the text\n * @see {@link http://docs.totaljs.com/SP/#SP.endsWith|Documentation}\n * @param {String} text Text to find.\n * @param {Boolean/Number} ignoreCase Ingore case sensitive or position in the string.\n * @return {Boolean}\n */\nSP.endsWith = function(text, ignoreCase) {\n\tvar self = this;\n\tvar length = text.length;\n\tvar tmp;", "\tif (ignoreCase === true) {\n\t\ttmp = self.substring(self.length - length);\n\t\treturn tmp.length === length && tmp.toLowerCase() === text.toLowerCase();\n\t}", "\tif (ignoreCase)\n\t\ttmp = self.substr((self.length - ignoreCase) - length, length);\n\telse\n\t\ttmp = self.substring(self.length - length);", "\treturn tmp.length === length && tmp === text;\n};", "SP.replacer = function(find, text) {\n\tvar self = this;\n\tvar beg = self.indexOf(find);\n\treturn beg === -1 ? self : (self.substring(0, beg) + text + self.substring(beg + find.length));\n};", "/**\n * Hash string\n * @param {String} type Hash type.\n * @param {String} salt Optional, salt.\n * @return {String}\n */\nSP.hash = function(type, salt) {\n\tvar str = salt ? this + salt : this;\n\tswitch (type) {\n\t\tcase 'md5':\n\t\t\treturn str.md5();\n\t\tcase 'sha1':\n\t\t\treturn str.sha1();\n\t\tcase 'sha256':\n\t\t\treturn str.sha256();\n\t\tcase 'sha512':\n\t\t\treturn str.sha512();\n\t\tcase 'crc32':\n\t\t\treturn str.crc32();\n\t\tcase 'crc32unsigned':\n\t\t\treturn str.crc32(true);\n\t\tdefault:\n\t\t\tvar val = string_hash(str);\n\t\t\treturn type === true ? val >>> 0 : val;\n\t}\n};", "global.HASH = function(value, type) {\n\treturn value.hash(type ? type : true);\n};", "SP.makeid = function() {\n\treturn this.hash(true).toString(16);\n};", "SP.crc32 = function(unsigned) {\n\tvar crc = -1;\n\tfor (var i = 0, length = this.length; i < length; i++)\n\t\tcrc = (crc >>> 8) ^ CRC32TABLE[(crc ^ this.charCodeAt(i)) & 0xFF];\n\tvar val = crc ^ (-1);\n\treturn unsigned ? val >>> 0 : val;\n};", "function string_hash(s, convert) {\n\tvar hash = 0;\n\tif (s.length === 0)\n\t\treturn convert ? '' : hash;\n\tfor (var i = 0, l = s.length; i < l; i++) {\n\t\tvar char = s.charCodeAt(i);\n\t\thash = ((hash << 5) - hash) + char;\n\t\thash |= 0;\n\t}\n\treturn hash;\n}", "SP.count = function(text) {\n\tvar index = 0;\n\tvar count = 0;\n\tdo {\n\t\tindex = this.indexOf(text, index + text.length);\n\t\tif (index > 0)\n\t\t\tcount++;\n\t} while (index > 0);\n\treturn count;\n};", "SP.parseXML = function(replace) {\n\treturn F.onParseXML(this, replace);\n};", "SP.parseJSON = function(date) {\n\treturn exports.parseJSON(this, date);\n};", "SP.parseQuery = function() {\n\treturn exports.parseQuery(this);\n};", "SP.parseUA = function(structured) {", "\tvar ua = this;", "\tif (!ua)\n\t\treturn '';", "\tvar arr = ua.match(regexpUA);\n\tvar uid = '';", "\tif (arr) {", "\t\tvar data = {};", "\t\tfor (var i = 0; i < arr.length; i++) {", "\t\t\tif (arr[i] === 'like' && arr[i + 1] === 'Gecko') {\n\t\t\t\ti += 1;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tvar key = arr[i].toLowerCase();\n\t\t\tif (key === 'like')\n\t\t\t\tbreak;", "\t\t\tswitch (key) {\n\t\t\t\tcase 'linux':\n\t\t\t\tcase 'windows':\n\t\t\t\tcase 'mac':\n\t\t\t\tcase 'symbian':\n\t\t\t\tcase 'symbos':\n\t\t\t\tcase 'tizen':\n\t\t\t\tcase 'android':\n\t\t\t\t\tdata[arr[i]] = 2;\n\t\t\t\t\tif (key === 'tizen' || key === 'android')\n\t\t\t\t\t\tdata.Mobile = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'webos':\n\t\t\t\t\tdata.WebOS = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'media':\n\t\t\t\tcase 'center':\n\t\t\t\tcase 'tv':\n\t\t\t\tcase 'smarttv':\n\t\t\t\tcase 'smart':\n\t\t\t\t\tdata[arr[i]] = 5;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'iemobile':\n\t\t\t\tcase 'mobile':\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'ipad':\n\t\t\t\tcase 'ipod':\n\t\t\t\tcase 'iphone':\n\t\t\t\t\tdata.iOS = 2;\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tif (key === 'ipad')\n\t\t\t\t\t\tdata.Tablet = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'phone':\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'tizenbrowser':\n\t\t\t\tcase 'blackberry':\n\t\t\t\tcase 'mini':\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'samsungbrowser':\n\t\t\t\tcase 'chrome':\n\t\t\t\tcase 'firefox':\n\t\t\t\tcase 'msie':\n\t\t\t\tcase 'opera':\n\t\t\t\tcase 'brave':\n\t\t\t\tcase 'vivaldi':\n\t\t\t\tcase 'outlook':\n\t\t\t\tcase 'safari':\n\t\t\t\tcase 'mail':\n\t\t\t\tcase 'edge':\n\t\t\t\tcase 'maxthon':\n\t\t\t\tcase 'electron':\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'trident':\n\t\t\t\t\tdata.MSIE = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'opr':\n\t\t\t\t\tdata.Opera = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'tablet':\n\t\t\t\t\tdata.Tablet = 4;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (data.MSIE) {\n\t\t\tdata.IE = 1;\n\t\t\tdelete data.MSIE;\n\t\t}", "\t\tif (data.WebOS || data.Android)\n\t\t\tdelete data.Linux;", "\t\tif (data.IEMobile) {\n\t\t\tif (data.Android)\n\t\t\t\tdelete data.Android;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t} else if (data.MSIE) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Edge) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Opera || data.Electron) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Chrome) {\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t\tif (data.SamsungBrowser)\n\t\t\t\tdelete data.SamsungBrowser;\n\t\t} else if (data.SamsungBrowser) {\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t}", "\t\tif (structured) {\n\t\t\tvar keys = Object.keys(data);\n\t\t\tvar output = { os: '', browser: '', device: 'desktop' };", "\t\t\tif (data.Tablet)\n\t\t\t\toutput.device = 'tablet';\n\t\t\telse if (data.Mobile)\n\t\t\t\toutput.device = 'mobile';", "\t\t\tfor (var i = 0; i < keys.length; i++) {\n\t\t\t\tvar val = data[keys[i]];\n\t\t\t\tswitch (val) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\toutput.browser += (output.browser ? ' ' : '') + keys[i];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\toutput.os += (output.os ? ' ' : '') + keys[i];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\toutput.device = 'tv';\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn output;\n\t\t}", "\t\tuid = Object.keys(data).join(' ');\n\t}", "\treturn uid;\n};", "SP.parseCSV = function(delimiter) {", "\tif (!delimiter)\n\t\tdelimiter = ',';", "\tvar delimiterstring = '\"';\n\tvar t = this;\n\tvar scope;\n\tvar tmp = {};\n\tvar index = 1;\n\tvar data = [];\n\tvar current = 'a';", "\tfor (var i = 0; i < t.length; i++) {\n\t\tvar c = t[i];", "\t\tif (!scope) {", "\t\t\tif (c === '\\n' || c === '\\r') {\n\t\t\t\ttmp && data.push(tmp);\n\t\t\t\tindex = 1;\n\t\t\t\tcurrent = 'a';\n\t\t\t\ttmp = null;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (c === delimiter) {\n\t\t\t\tcurrent = String.fromCharCode(97 + index);\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (c === delimiterstring) {\n\t\t\t// Check escaped quotes\n\t\t\tif (scope && t[i + 1] === delimiterstring) {\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\tscope = c === scope ? '' : c;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (!tmp)\n\t\t\ttmp = {};", "\t\tif (tmp[current])\n\t\t\ttmp[current] += c;\n\t\telse\n\t\t\ttmp[current] = c;\n\t}", "\ttmp && data.push(tmp);\n\treturn data;\n};", "SP.parseTerminal = function(fields, fn, skip, take) {", "\tvar lines = this.split('\\n');", "\tif (typeof(fields) === 'function') {\n\t\ttake = skip;\n\t\tskip = fn;\n\t\tfn = fields;\n\t\tparseTerminal2(lines, fn, skip, take);\n\t\treturn this;\n\t}", "\tif (skip === undefined)\n\t\tskip = 0;\n\tif (take === undefined)\n\t\ttake = lines.length;", "\tvar headers = [];\n\tvar indexer = 0;\n\tvar line = lines[0];", "\tif (!line) {\n\t\tline = lines[1];\n\t\tskip++;\n\t}", "\tif (!line) {\n\t\tline = lines[2];\n\t\tskip++;\n\t}", "\tif (!line)\n\t\treturn this;", "\tvar fieldslength = fields.length;\n\tvar tmp;", "\tfor (var i = 0, length = fieldslength; i < length; i++) {\n\t\tvar field = fields[i];", "\t\tvar beg = -1;\n\t\tvar end = -1;\n\t\tvar type = typeof(field);", "\t\tif (type === 'object' && field.test) {\n\t\t\ttmp = line.match(field);\n\t\t\tif (tmp) {\n\t\t\t\tbeg = tmp.index;\n\t\t\t\tend = beg + tmp.toString().length;\n\t\t\t} else {\n\t\t\t\tbeg = -1;\n\t\t\t\tend = -1;\n\t\t\t}\n\t\t} else if (type === 'string') {\n\t\t\ttmp = line.indexOf(field);\n\t\t\tif (tmp === -1) {\n\t\t\t\tbeg = -1;\n\t\t\t\tend = -1;\n\t\t\t} else {\n\t\t\t\tbeg = tmp;\n\t\t\t\tend = line.indexOf(' ', beg + field.length);\n\t\t\t}\n\t\t}", "\t\theaders.push({ beg: beg, end: end });\n\t}", "\tfor (var i = skip + 1, length = skip + 1 + take; i < length; i++) {", "\t\tvar line = lines[i];\n\t\tif (!line)\n\t\t\tcontinue;", "\t\tvar arr = [];\n\t\tvar is = false;\n\t\tvar beg;", "\t\tfor (var j = 0; j < fieldslength; j++) {\n\t\t\tvar header = headers[j];\n\t\t\tif (header.beg !== -1) {\n\t\t\t\tis = true;\n\t\t\t\tbeg = 0;", "\t\t\t\tfor (var k = header.beg; k > -1; k--) {\n\t\t\t\t\tif (line[k] === ' ') {\n\t\t\t\t\t\tbeg = k + 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tarr.push(line.substring(beg, header.end === -1 ? undefined : header.end).trim());\n\t\t\t} else\n\t\t\t\tarr.push('');\n\t\t}", "\t\tis && fn(arr, indexer++, length, i);\n\t}", "\treturn this;\n};", "function parseTerminal2(lines, fn, skip, take) {\n\tvar indexer = 0;", "\tif (skip === undefined)\n\t\tskip = 0;\n\tif (take === undefined)\n\t\ttake = lines.length;", "\tfor (var i = skip, length = skip + take; i < length; i++) {\n\t\tvar line = lines[i];\n\t\tif (!line)\n\t\t\tcontinue;\n\t\tvar m = line.match(regexpTERMINAL);\n\t\tm && fn(m, indexer++, length, i);\n\t}\n}", "function parseDateFormat(format, val) {", "\tvar tmp = [];\n\tvar tmpformat = [];\n\tvar prev = '';\n\tvar prevformat = '';\n\tvar allowed = { y: 1, Y: 1, M: 1, m: 1, d: 1, D: 1, H: 1, s: 1, a: 1, w: 1 };", "\tfor (var i = 0; i < format.length; i++) {", "\t\tvar c = format[i];", "\t\tif (!allowed[c])\n\t\t\tcontinue;", "\t\tif (prev !== c) {\n\t\t\tprevformat && tmpformat.push(prevformat);\n\t\t\tprevformat = c;\n\t\t\tprev = c;\n\t\t} else\n\t\t\tprevformat += c;\n\t}", "\tprev = '';", "\tfor (var i = 0; i < val.length; i++) {\n\t\tvar code = val.charCodeAt(i);\n\t\tif (code >= 48 && code <= 57)\n\t\t\tprev += val[i];\n\t}", "\tprevformat && tmpformat.push(prevformat);", "\tvar f = 0;\n\tfor (var i = 0; i < tmpformat.length; i++) {\n\t\tvar l = tmpformat[i].length;\n\t\ttmp.push(prev.substring(f, f + l));\n\t\tf += l;\n\t}", "\tvar dt = {};", "\tfor (var i = 0; i < tmpformat.length; i++) {\n\t\tvar type = tmpformat[i];\n\t\tif (tmp[i])\n\t\t\tdt[type[0]] = +tmp[i];\n\t}", "\tvar h = dt.h || dt.H;", "\tif (h != null) {\n\t\tvar ampm = val.match(REG_TIME);\n\t\tif (ampm && ampm[0].toLowerCase() === 'pm')\n\t\t\th += 12;\n\t}", "\treturn new Date((dt.y || dt.Y) || 0, (dt.M || 1) - 1, dt.d || dt.D || 0, h || 0, dt.m || 0, dt.s || 0);\n}", "SP.parseDate = function(format) {", "\tif (format)\n\t\treturn parseDateFormat(format, this);", "\tvar self = this.trim();\n\tvar lc = self.charCodeAt(self.length - 1);", "\t// Classic date\n\tif (lc === 41)\n\t\treturn new Date(self);", "\t// JSON format\n\tif (lc === 90)\n\t\treturn new Date(Date.parse(self));", "\tvar arr = self.indexOf(' ') === -1 ? self.split('T') : self.split(' ');\n\tvar index = arr[0].indexOf(':');\n\tvar length = arr[0].length;", "\tif (index !== -1) {\n\t\tvar tmp = arr[1];\n\t\tarr[1] = arr[0];\n\t\tarr[0] = tmp;\n\t}", "\tif (arr[0] === undefined)\n\t\tarr[0] = '';", "\tvar noTime = arr[1] === undefined ? true : arr[1].length === 0;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar c = arr[0].charCodeAt(i);\n\t\tif (c === 45 || c === 46 || (c > 47 && c < 58))\n\t\t\tcontinue;\n\t\tif (noTime)\n\t\t\treturn new Date(self);\n\t}", "\tif (arr[1] === undefined)\n\t\tarr[1] = '00:00:00';", "\tvar firstDay = arr[0].indexOf('-') === -1;", "\tvar date = (arr[0] || '').split(firstDay ? '.' : '-');\n\tvar time = (arr[1] || '').split(':');\n\tvar parsed = [];", "\tif (date.length < 4 && time.length < 2)\n\t\treturn new Date(self);", "\tindex = (time[2] || '').indexOf('.');", "\t// milliseconds\n\tif (index !== -1) {\n\t\ttime[3] = time[2].substring(index + 1);\n\t\ttime[2] = time[2].substring(0, index);\n\t} else\n\t\ttime[3] = '0';", "\tparsed.push(+date[firstDay ? 2 : 0]); // year\n\tparsed.push(+date[1]); // month\n\tparsed.push(+date[firstDay ? 0 : 2]); // day\n\tparsed.push(+time[0]); // hours\n\tparsed.push(+time[1]); // minutes\n\tparsed.push(+time[2]); // seconds\n\tparsed.push(+time[3]); // miliseconds", "\tvar def = new Date();", "\tfor (var i = 0, length = parsed.length; i < length; i++) {\n\t\tif (isNaN(parsed[i]))\n\t\t\tparsed[i] = 0;", "\t\tvar value = parsed[i];\n\t\tif (value !== 0)\n\t\t\tcontinue;", "\t\tswitch (i) {\n\t\t\tcase 0:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getFullYear();\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getMonth() + 1;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getDate();\n\t\t\t\tbreak;\n\t\t}\n\t}", "\treturn new Date(parsed[0], parsed[1] - 1, parsed[2], parsed[3], parsed[4] - NOW.getTimezoneOffset(), parsed[5]);\n};", "SP.parseDateExpiration = function() {\n\tvar self = this;", "\tvar arr = self.split(' ');\n\tvar dt = new Date();\n\tvar length = arr.length;", "\tfor (var i = 0; i < length; i += 2) {\n\t\tvar num = arr[i].parseInt();\n\t\tif (num === 0)\n\t\t\tcontinue;\n\t\tvar type = arr[i + 1];\n\t\tif (type)\n\t\t\tdt = dt.add(type, num);\n\t}", "\treturn dt;\n};", "SP.contains = function(value, mustAll) {\n\tvar str = this;", "\tif (typeof(value) === 'string')\n\t\treturn str.indexOf(value, typeof(mustAll) === 'number' ? mustAll : 0) !== -1;", "\tfor (var i = 0, length = value.length; i < length; i++) {\n\t\tvar exists = str.indexOf(value[i]) !== -1;\n\t\tif (mustAll) {\n\t\t\tif (!exists)\n\t\t\t\treturn false;\n\t\t} else if (exists)\n\t\t\treturn true;\n\t}", "\treturn mustAll;\n};", "/**\n * Same functionality as as String.localeCompare() but this method works with latin.\n * @param {String} value\n * @return {Number}\n */\nSP.localeCompare2 = function(value) {\n\treturn COMPARER(this, value);\n};", "var configurereplace = function(text) {\n\tvar val = CONF[text.substring(1, text.length - 1)];\n\treturn val == null ? '' : val;\n};", "SP.env = function() {\n\treturn this.replace(regexpCONFIGURE, configurereplace);\n};", "/**\n * Parse configuration from a string\n * @param {Object} def\n * @onerr {Function} error handling\n * @return {Object}\n */\nSP.parseConfig = function(def, onerr) {", "\tif (typeof(def) === 'function') {\n\t\tonerr = def;\n\t\tdef = null;\n\t}", "\tvar arr = this.split('\\n');\n\tvar length = arr.length;\n\tvar obj = def ? exports.extend({}, def) : {};\n\tvar subtype;\n\tvar name;\n\tvar index;\n\tvar value;", "\tfor (var i = 0; i < length; i++) {", "\t\tvar str = arr[i];\n\t\tif (!str || str[0] === '#' || str.substring(0, 2) === '//')\n\t\t\tcontinue;", "\t\tindex = str.indexOf(':');\n\t\tif (index === -1) {\n\t\t\tindex = str.indexOf('\\t:');\n\t\t\tif (index === -1)\n\t\t\t\tcontinue;\n\t\t}", "\t\tname = str.substring(0, index).trim();\n\t\tvalue = str.substring(index + 2).trim();", "\t\tindex = name.indexOf('(');\n\t\tif (index !== -1) {\n\t\t\tsubtype = name.substring(index + 1, name.indexOf(')')).trim().toLowerCase();\n\t\t\tname = name.substring(0, index).trim();\n\t\t} else\n\t\t\tsubtype = '';", "\t\tswitch (subtype) {\n\t\t\tcase 'string':\n\t\t\t\tobj[name] = value;\n\t\t\t\tbreak;\n\t\t\tcase 'number':\n\t\t\tcase 'float':\n\t\t\tcase 'double':\n\t\t\tcase 'currency':\n\t\t\t\tobj[name] = value.isNumber(true) ? value.parseFloat2() : value.parseInt2();\n\t\t\t\tbreak;\n\t\t\tcase 'boolean':\n\t\t\tcase 'bool':\n\t\t\t\tobj[name] = (/true|on|1|enabled/i).test(value);\n\t\t\t\tbreak;\n\t\t\tcase 'config':\n\t\t\t\tobj[name] = CONF[value];\n\t\t\t\tbreak;\n\t\t\tcase 'eval':\n\t\t\tcase 'object':\n\t\t\tcase 'array':\n\t\t\t\ttry {\n\t\t\t\t\tobj[name] = new Function('return ' + value)();\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (onerr)\n\t\t\t\t\t\tonerr(e, arr[i]);\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow new Error('A value of \"{0}\" can\\'t be converted to \"{1}\": '.format(name, subtype) + e.toString());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'json':\n\t\t\t\tobj[name] = value.parseJSON(true);\n\t\t\t\tbreak;\n\t\t\tcase 'env':\n\t\t\tcase 'environment':\n\t\t\t\tobj[name] = process.env[value];\n\t\t\t\tbreak;\n\t\t\tcase 'date':\n\t\t\tcase 'time':\n\t\t\tcase 'datetime':\n\t\t\t\tobj[name] = value.parseDate();\n\t\t\t\tbreak;\n\t\t\tcase 'random':\n\t\t\t\tobj[name] = GUID((value || '0').parseInt() || 10);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tobj[name] = value;\n\t\t\t\tbreak;\n\t\t}\n\t}", "\treturn obj;\n};", "SP.format = function() {\n\tvar arg = arguments;\n\treturn this.replace(regexpSTRINGFORMAT, function(text) {\n\t\tvar value = arg[+text.substring(1, text.length - 1)];\n\t\treturn value == null ? '' : value;\n\t});\n};", "SP.encryptUID = function(key) {\n\treturn exports.encryptUID(this, key);\n};", "SP.decryptUID = function(key) {\n\treturn exports.decryptUID(this, key);\n};", "SP.encode = function() {\n\tvar output = '';\n\tfor (var i = 0, length = this.length; i < length; i++) {\n\t\tvar c = this[i];\n\t\tswitch (c) {\n\t\t\tcase '<':\n\t\t\t\toutput += '&lt;';\n\t\t\t\tbreak;\n\t\t\tcase '>':\n\t\t\t\toutput += '&gt;';\n\t\t\t\tbreak;\n\t\t\tcase '\"':\n\t\t\t\toutput += '&quot;';\n\t\t\t\tbreak;\n\t\t\tcase '\\'':\n\t\t\t\toutput += '&apos;';\n\t\t\t\tbreak;\n\t\t\tcase '&':\n\t\t\t\toutput += '&amp;';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\toutput += c;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn output;\n};", "SP.decode = function() {\n\treturn this.replace(regexpDECODE, function(s) {\n\t\tif (s.charAt(1) !== '#')\n\t\t\treturn ALPHA_INDEX[s] || s;\n\t\tvar code = s[2].toLowerCase() === 'x' ? parseInt(s.substr(3), 16) : parseInt(s.substr(2));\n\t\treturn !code || code < -32768 || code > 65535 ? '' : String.fromCharCode(code);\n\t});\n};", "SP.urlEncode = function() {\n\treturn encodeURIComponent(this);\n};", "SP.urlDecode = function() {\n\treturn decodeURIComponent(this);\n};", "SP.arg = function(obj, encode, def) {\n\tif (typeof(encode) === 'string')\n\t\tdef = encode;\n\treturn this.replace(regexpARG, function(text) {\n\t\t// Is double?\n\t\tvar l = text[1] === '{' ? 2 : 1;\n\t\tvar val = obj[text.substring(l, text.length - l).trim()];\n\t\tif (encode && encode === 'json')\n\t\t\treturn JSON.stringify(val);\n\t\treturn val == null ? (def == null ? text : def) : encode ? encode === 'html' ? (val + '').encode() : encodeURIComponent(val + '') : val;\n\t});\n};", "SP.params = function(obj) {", "\tOBSOLETE('String.params()', 'The method is deprecated instead of it use F.viewCompile() or String.format().');", "\tvar formatted = this;\n\tif (obj == null)\n\t\treturn formatted;", "\treturn formatted.replace(regexpPARAM, function(prop) {", "\t\tvar isEncode = false;\n\t\tvar name = prop.substring(2, prop.length - 2).trim();", "\t\tvar format = '';\n\t\tvar index = name.indexOf('|');", "\t\tif (index !== -1) {\n\t\t\tformat = name.substring(index + 1, name.length).trim();\n\t\t\tname = name.substring(0, index).trim();\n\t\t}", "\t\tif (name[0] === '!')\n\t\t\tname = name.substring(1);\n\t\telse\n\t\t\tisEncode = true;", "\t\tvar val;", "\t\tif (name.indexOf('.') !== -1) {\n\t\t\tvar arr = name.split('.');\n\t\t\tif (arr.length === 2) {\n\t\t\t\tif (obj[arr[0]])\n\t\t\t\t\tval = obj[arr[0]][arr[1]];\n\t\t\t} else if (arr.length === 3) {\n\t\t\t\tif (obj[arr[0]] && obj[arr[0]][arr[1]])\n\t\t\t\t\tval = obj[arr[0]][arr[1]][arr[2]];\n\t\t\t} else if (arr.length === 4) {\n\t\t\t\tif (obj[arr[0]] && obj[arr[0]][arr[1]] && obj[arr[0]][arr[1]][arr[2]])\n\t\t\t\t\tval = obj[arr[0]][arr[1]][arr[2]][arr[3]];\n\t\t\t} else if (arr.length === 5) {\n\t\t\t\tif (obj[arr[0]] && obj[arr[0]][arr[1]] && obj[arr[0]][arr[1]][arr[2]] && obj[arr[0]][arr[1]][arr[2]][arr[3]])\n\t\t\t\t\tval = obj[arr[0]][arr[1]][arr[2]][arr[3]][arr[4]];\n\t\t\t}\n\t\t} else\n\t\t\tval = name.length ? obj[name] : obj;", "\t\tif (typeof(val) === 'function')\n\t\t\tval = val(index);", "\t\tif (val === undefined)\n\t\t\treturn prop;", "\t\tif (format.length) {\n\t\t\tvar type = typeof(val);\n\t\t\tif (type === 'string') {\n\t\t\t\tvar max = +format;\n\t\t\t\tif (!isNaN(max))\n\t\t\t\t\tval = val.max(max + 3, '...');", "\t\t\t} else if (type === 'number' || exports.isDate(val)) {\n\t\t\t\tif (format.isNumber())\n\t\t\t\t\tformat = +format;\n\t\t\t\tval = val.format(format);\n\t\t\t}\n\t\t}", "\t\tval = val.toString();\n\t\treturn isEncode ? exports.encode(val) : val;\n\t});\n};", "SP.max = function(length, chars) {\n\tvar str = this;\n\tif (typeof(chars) !== 'string')\n\t\tchars = '...';\n\treturn str.length > length ? str.substring(0, length - chars.length) + chars : str;\n};", "SP.isJSON = function() {\n\tvar self = this;\n\tif (self.length <= 1)\n\t\treturn false;", "\tvar l = self.length - 1;\n\tvar a;\n\tvar b;\n\tvar i = 0;", "\twhile (true) {\n\t\ta = self[i++];\n\t\tif (a === ' ' || a === '\\n' || a === '\\r' || a === '\\t')\n\t\t\tcontinue;\n\t\tbreak;\n\t}", "\twhile (true) {\n\t\tb = self[l--];\n\t\tif (b === ' ' || b === '\\n' || b === '\\r' || b === '\\t')\n\t\t\tcontinue;\n\t\tbreak;\n\t}", "\treturn (a === '\"' && b === '\"') || (a === '[' && b === ']') || (a === '{' && b === '}') || (a.charCodeAt(0) > 47 && b.charCodeAt(0) < 57);\n};", "SP.isURL = function() {\n\treturn this.length <= 7 ? false : F.validators.url.test(this);\n};", "SP.isZIP = function() {\n\treturn F.validators.zip.test(this);\n};", "SP.isEmail = function() {\n\treturn this.length <= 4 ? false : F.validators.email.test(this);\n};", "SP.isPhone = function() {\n\treturn this.length < 6 ? false : F.validators.phone.test(this);\n};", "SP.isBase64 = function() {\n\tvar str = this;\n\treturn str.length % 4 === 0 && regexpBASE64.test(str);\n};", "SP.isUID = function() {\n\tvar str = this;", "\tif (str.length < 12)\n\t\treturn false;", "\tvar is = DEF.validators.uid.test(str);\n\tif (is) {", "\t\tvar sum;\n\t\tvar beg;\n\t\tvar end;\n\t\tvar e = str[str.length - 1];", "\t\tif (e === 'b' || e === 'c' || e === 'd') {\n\t\t\tsum = str[str.length - 2];\n\t\t\tbeg = +str[str.length - 3];\n\t\t\tend = str.length - 5;\n\t\t\tvar tmp = e === 'c' || e === 'd' ? (+str.substring(beg, end)) : parseInt(str.substring(beg, end), 16);\n\t\t\treturn sum === (tmp % 2 ? '1' : '0');\n\t\t} else if (e === 'a') {\n\t\t\tsum = str[str.length - 2];\n\t\t\tbeg = 6;\n\t\t\tend = str.length - 4;\n\t\t} else {\n\t\t\tsum = str[str.length - 1];\n\t\t\tbeg = 10;\n\t\t\tend = str.length - 4;\n\t\t}", "\t\twhile (beg++ < end) {\n\t\t\tif (str[beg] !== '0') {\n\t\t\t\tif (((+str.substring(beg, end)) % 2 ? '1' : '0') === sum)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n};", "SP.parseUID = function() {\n\tvar self = this;\n\tvar obj = {};\n\tvar hash;\n\tvar e = self[self.length - 1];", "\tif (e === 'b' || e === 'c' || e === 'd') {\n\t\tend = +self[self.length - 3];\n\t\tvar ticks = ((e === 'b' ? (+self.substring(0, end)) : parseInt(self.substring(0, end), e=== 'd' ? 36 : 16)) * 1000 * 60) + 1580511600000; // 1.1.2020\n\t\tobj.date = new Date(ticks);\n\t\tbeg = end;\n\t\tend = self.length - 5;\n\t\thash = +self.substring(end + 3, end + 4);\n\t\tobj.century = Math.floor((obj.date.getFullYear() - 1) / 100) + 1;\n\t\tobj.hash = self.substring(end, end + 2);\n\t} else if (e === 'a') {\n\t\tvar ticks = ((+self.substring(0, 6)) * 1000 * 60) + 1548975600000; // old 1.1.2019\n\t\tobj.date = new Date(ticks);\n\t\tbeg = 7;\n\t\tend = self.length - 4;\n\t\thash = +self.substring(end + 2, end + 3);\n\t\tobj.century = Math.floor((obj.date.getFullYear() - 1) / 100) + 1;\n\t\tobj.hash = self.substring(end, end + 2);\n\t} else {\n\t\tvar y = self.substring(0, 2);\n\t\tvar M = self.substring(2, 4);\n\t\tvar d = self.substring(4, 6);\n\t\tvar H = self.substring(6, 8);\n\t\tvar m = self.substring(8, 10);", "\t\tobj.date = new Date(+('20' + y), (+M) - 1, +d, +H, +m, 0);", "\t\tvar beg = 0;\n\t\tvar end = 0;\n\t\tvar index = 10;", "\t\twhile (true) {", "\t\t\tvar c = self[index];", "\t\t\tif (!c)\n\t\t\t\tbreak;", "\t\t\tif (!beg && c !== '0')\n\t\t\t\tbeg = index;", "\t\t\tif (c.charCodeAt(0) > 96) {\n\t\t\t\tend = index;\n\t\t\t\tbreak;\n\t\t\t}", "\t\t\tindex++;\n\t\t}", "\t\tobj.century = self.substring(end + 4);", "\t\tif (obj.century) {\n\t\t\tobj.century = 20 + (+obj.century);\n\t\t\tobj.date.setYear(obj.date.getFullYear() + 100);\n\t\t} else\n\t\t\tobj.century = 21;", "\t\thash = +self.substring(end + 3, end + 4);\n\t\tobj.hash = self.substring(end, end + 3);\n\t}", "\tobj.index = +self.substring(beg, end);\n\tobj.valid = (obj.index % 2 ? 1 : 0) === hash;\n\treturn obj;\n};", "SP.parseENV = function() {", "\tvar arr = this.split(regexpLINES);\n\tvar obj = {};", "\tfor (var i = 0; i < arr.length; i++) {\n\t\tvar line = arr[i];\n\t\tif (!line || line.substring(0, 2) === '//' || line[0] === '#')\n\t\t\tcontinue;", "\t\tvar index = line.indexOf('=');\n\t\tif (index === -1)\n\t\t\tcontinue;", "\t\tvar key = line.substring(0, index);\n\t\tvar val = line.substring(index + 1).replace(/\\\\n/g, '\\n');\n\t\tvar end = val.length - 1;", "\t\tif ((val[0] === '\"' && val[end] === '\"') || (val[0] === '\\'' && val[end] === '\\''))\n\t\t\tval = val.substring(1, end);\n\t\telse\n\t\t\tval = val.trim();", "\t\tobj[key] = val;\n\t}", "\treturn obj;\n};", "SP.parseInt = function(def) {\n\tvar str = this.trim();\n\tvar num = +str;\n\treturn isNaN(num) ? (def === undefined ? 0 : def) : num;\n};", "SP.parseInt2 = function(def) {\n\tvar num = this.match(regexpINTEGER);\n\treturn num ? +num[0] : (def === undefined ? 0 : def);\n};", "SP.parseFloat2 = function(def) {\n\tvar num = this.match(regexpFLOAT);\n\treturn num ? +num[0].toString().replace(/,/g, '.') : (def === undefined ? 0 : def);\n};", "SP.parseBool = SP.parseBoolean = function() {\n\tvar self = this.toLowerCase();\n\treturn self === 'true' || self === '1' || self === 'on';\n};", "SP.parseFloat = function(def) {\n\tvar str = this.trim();\n\tif (str.indexOf(',') !== -1)\n\t\tstr = str.replace(',', '.');\n\tvar num = +str;\n\treturn isNaN(num) ? (def === undefined ? 0 : def) : num;\n};", "SP.capitalize = function(first) {", "\tif (first)\n\t\treturn (this[0] || '').toUpperCase() + this.substring(1);", "\tvar builder = '';\n\tvar c;", "\tfor (var i = 0, length = this.length; i < length; i++) {\n\t\tvar c = this[i - 1];\n\t\tif (!c || (c === ' ' || c === '\\t' || c === '\\n'))\n\t\t\tc = this[i].toUpperCase();\n\t\telse\n\t\t\tc = this[i];\n\t\tbuilder += c;\n\t}", "\treturn builder;\n};", "SP.toUnicode = function() {\n\tvar output = '';\n\tfor (var i = 0; i < this.length; i++) {\n\t\tvar c = this[i].charCodeAt(0);\n\t\tif(c > 126 || c < 32)\n\t\t\toutput += '\\\\u' + ('000' + c.toString(16)).substr(-4);\n\t\telse\n\t\t\toutput += this[i];\n\t}\n\treturn output;\n};", "SP.fromUnicode = function() {\n\tvar output = '';\n\tfor (var i = 0; i < this.length; i++) {\n\t\tif (this[i] === '\\\\' && this[i + 1] === 'u') {\n\t\t\toutput += String.fromCharCode(parseInt(this[i + 2] + this[i + 3] + this[i + 4] + this[i + 5], 16));\n\t\t\ti += 5;\n\t\t} else\n\t\t\toutput += this[i];\n\t}\n\treturn output;\n};", "SP.sha1 = function(salt) {\n\tvar hash = Crypto.createHash('sha1');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.sha256 = function(salt) {\n\tvar hash = Crypto.createHash('sha256');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.sha512 = function(salt) {\n\tvar hash = Crypto.createHash('sha512');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.md5 = function(salt) {\n\tvar hash = Crypto.createHash('md5');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.toSearch = function() {\n\tvar str = this.replace(regexpSEARCH, '').trim().toLowerCase().removeDiacritics();\n\tvar buf = [];\n\tvar prev = '';\n\tfor (var i = 0, length = str.length; i < length; i++) {\n\t\tvar c = str[i];\n\t\tif (c === 'y')\n\t\t\tc = 'i';\n\t\tif (c === prev)\n\t\t\tcontinue;\n\t\tprev = c;\n\t\tbuf.push(c);\n\t}", "\treturn buf.join('');\n};", "SP.toKeywords = SP.keywords = function(forSearch, alternative, max_count, max_length, min_length) {\n\treturn exports.keywords(this, forSearch, alternative, max_count, max_length, min_length);\n};", "function checksum(val) {\n\tvar sum = 0;\n\tfor (var i = 0; i < val.length; i++)\n\t\tsum += val.charCodeAt(i);\n\treturn sum;\n}", "SP.encrypt = function(key, isUnique, secret) {\n\tvar str = '0' + this;\n\tvar data_count = str.length;\n\tvar key_count = key.length;\n\tvar random = isUnique ? exports.random(120) + 40 : 65;\n\tvar count = data_count + (random % key_count);\n\tvar values = [];\n\tvar index = 0;", "\tvalues[0] = String.fromCharCode(random);", "\tvar counter = this.length + key.length;", "\tfor (var i = count - 1; i > 0; i--) {\n\t\tindex = str.charCodeAt(i % data_count);\n\t\tvalues[i] = String.fromCharCode(index ^ (key.charCodeAt(i % key_count) ^ random));\n\t}", "\tstr = Buffer.from(counter + '=' + values.join(''), ENCODING).toString('hex');\n\tvar sum = 0;", "\tfor (var i = 0; i < str.length; i++)\n\t\tsum += str.charCodeAt(i);", "\treturn (sum + checksum((secret || CONF.secret) + key)) + '-' + str;\n};", "SP.decrypt = function(key, secret) {", "\tvar index = this.indexOf('-');\n\tif (index === -1)\n\t\treturn null;", "\tvar cs = +this.substring(0, index);\n\tif (!cs || isNaN(cs))\n\t\treturn null;", "\tvar hash = this.substring(index + 1);\n\tvar sum = checksum((secret || CONF.secret) + key);\n\tfor (var i = 0; i < hash.length; i++)\n\t\tsum += hash.charCodeAt(i);", "\tif (sum !== cs)\n\t\treturn null;", "\tvar values = Buffer.from(hash, 'hex').toString(ENCODING);\n\tvar index = values.indexOf('=');\n\tif (index === -1)\n\t\treturn null;", "\tvar counter = +values.substring(0, index);\n\tif (isNaN(counter))\n\t\treturn null;", "\tvalues = values.substring(index + 1);", "\tvar count = values.length;\n\tvar random = values.charCodeAt(0);\n\tvar key_count = key.length;\n\tvar data_count = count - (random % key_count);\n\tvar decrypt_data = [];", "\tfor (var i = data_count - 1; i > 0; i--) {\n\t\tindex = values.charCodeAt(i) ^ (random ^ key.charCodeAt(i % key_count));\n\t\tdecrypt_data[i] = String.fromCharCode(index);\n\t}", "\tvar val = decrypt_data.join('');\n\treturn counter !== (val.length + key.length) ? null : val;\n};", "exports.encryptUID = function(val, key) {", "\tvar num = typeof(val) === 'number';\n\tvar sum = 0;", "\tif (!key)\n\t\tkey = CONF.secret;", "\tval = val + '';", "\tfor (var i = 0; i < val.length; i++)\n\t\tsum += val.charCodeAt(i);", "\tfor (var i = 0; i < key.length; i++)\n\t\tsum += key.charCodeAt(i);", "\treturn (num ? 'n' : 'x') + (CONF.secret_uid + val + sum + key).crc32(true).toString(16) + 'x' + val;\n};", "exports.decryptUID = function(val, key) {\n\tvar num = val[0] === 'n';\n\tvar raw = val.substring(val.indexOf('x', 1) + 1);", "\tif (num)\n\t\traw = +raw;", "\treturn exports.encryptUID(raw, key) === val ? raw : null;\n};", "SP.base64ToFile = function(filename, callback) {\n\tvar self = this;\n\tvar index = self.indexOf(',');\n\tif (index === -1)\n\t\tindex = 0;\n\telse\n\t\tindex++;\n\tFs.writeFile(filename, self.substring(index), 'base64', callback || exports.noop);\n\treturn this;\n};", "SP.base64ToBuffer = function() {\n\tvar self = this;", "\tvar index = self.indexOf(',');\n\tif (index === -1)\n\t\tindex = 0;\n\telse\n\t\tindex++;", "\treturn Buffer.from(self.substring(index), 'base64');\n};", "SP.base64ContentType = function() {\n\tvar self = this;\n\tvar index = self.indexOf(';');\n\treturn index === -1 ? '' : self.substring(5, index);\n};", "SP.removeDiacritics = function() {\n\treturn exports.removeDiacritics(this);\n};", "SP.indent = function(max, c) {\n\tvar plus = '';\n\tif (c === undefined)\n\t\tc = ' ';\n\twhile (max--)\n\t\tplus += c;\n\treturn plus + this;\n};", "SP.isNumber = function(isDecimal) {", "\tvar self = this;\n\tvar length = self.length;", "\tif (!length)\n\t\treturn false;", "\tisDecimal = isDecimal || false;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar ascii = self.charCodeAt(i);", "\t\tif (isDecimal) {\n\t\t\tif (ascii === 44 || ascii === 46) {\n\t\t\t\tisDecimal = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (ascii < 48 || ascii > 57)\n\t\t\treturn false;\n\t}", "\treturn true;\n};", "if (!SP.padLeft) {\n\tSP.padLeft = function(max, c) {\n\t\tvar self = this;\n\t\tvar len = max - self.length;\n\t\tif (len < 0)\n\t\t\treturn self;\n\t\tif (c === undefined)\n\t\t\tc = ' ';\n\t\twhile (len--)\n\t\t\tself = c + self;\n\t\treturn self;\n\t};\n}", "\nif (!SP.padRight) {\n\tSP.padRight = function(max, c) {\n\t\tvar self = this;\n\t\tvar len = max - self.length;\n\t\tif (len < 0)\n\t\t\treturn self;\n\t\tif (c === undefined)\n\t\t\tc = ' ';\n\t\twhile (len--)\n\t\t\tself += c;\n\t\treturn self;\n\t};\n}", "SP.insert = function(index, value) {\n\tvar str = this;\n\tvar a = str.substring(0, index);\n\tvar b = value.toString() + str.substring(index);\n\treturn a + b;\n};", "/**\n * Create a link from String\n * @param {Number} max A maximum length, default: 60 and optional.\n * @return {String}\n */\nSP.slug = SP.toSlug = SP.toLinker = SP.linker = function(max) {\n\tmax = max || 60;", "\tvar self = this.trim().toLowerCase().removeDiacritics();\n\tvar builder = '';\n\tvar length = self.length;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar c = self[i];\n\t\tvar code = self.charCodeAt(i);", "\t\tif (code > 540){\n\t\t\tbuilder = '';\n\t\t\tbreak;\n\t\t}", "\t\tif (builder.length >= max)\n\t\t\tbreak;", "\t\tif (code > 31 && code < 48) {\n\t\t\tif (builder[builder.length - 1] !== '-')\n\t\t\t\tbuilder += '-';\n\t\t\tcontinue;\n\t\t}", "\t\tif ((code > 47 && code < 58) || (code > 94 && code < 123))\n\t\t\tbuilder += c;\n\t}", "\tif (builder.length > 1) {\n\t\tlength = builder.length - 1;\n\t\treturn builder[length] === '-' ? builder.substring(0, length) : builder;\n\t} else if (!length)\n\t\treturn '';", "\tlength = self.length;\n\tself = self.replace(/\\s/g, '');\n\tbuilder = self.crc32(true).toString(36) + '';\n\treturn self[0].charCodeAt(0).toString(32) + builder + self[self.length - 1].charCodeAt(0).toString(32) + length;\n};", "SP.pluralize = function(zero, one, few, other) {\n\treturn this.parseInt().pluralize(zero, one, few, other);\n};", "SP.isBoolean = function() {\n\tvar self = this.toLowerCase();\n\treturn (self === 'true' || self === 'false') ? true : false;\n};", "/**\n * Check if the string contains only letters and numbers.\n * @return {Boolean}\n */\nSP.isAlphaNumeric = function() {\n\treturn regexpALPHA.test(this);\n};", "SP.soundex = function() {", "\tvar arr = this.toLowerCase().split('');\n\tvar first = arr.shift();\n\tvar builder = first.toUpperCase();", "\tfor (var i = 0, length = arr.length; i < length; i++) {\n\t\tvar v = SOUNDEX[arr[i]];\n\t\tif (v === undefined)\n\t\t\tcontinue;\n\t\tif (i) {\n\t\t\tif (v !== arr[i - 1])\n\t\t\t\tbuilder += v;\n\t\t} else if (v !== SOUNDEX[first])\n\t\t\tbuilder += v;\n\t}", "\treturn (builder + '000').substring(0, 4);\n};", "/**\n* Remove all Html Tags from a string\n* @return {string}\n*/\nSP.removeTags = function() {\n\treturn this.replace(regexpTags, '');\n};", "NP.floor = function(decimals) {\n\treturn Math.floor(this * Math.pow(10, decimals)) / Math.pow(10, decimals);\n};", "NP.fixed = function(decimals) {\n\treturn +this.toFixed(decimals);\n};", "NP.padLeft = function(max, c) {\n\treturn this.toString().padLeft(max, c || '0');\n};", "NP.padRight = function(max, c) {\n\treturn this.toString().padRight(max, c || '0');\n};", "NP.round = function(precision) {\n\tvar m = Math.pow(10, precision) || 1;\n\treturn Math.round(this * m) / m;\n};", "NP.currency = function(currency, a, b, c) {\n\tvar curr = DEF.currencies[currency];\n\treturn curr ? curr(this, a, b, c) : this.format(2);\n};", "/**\n * Async decrements\n * @param {Function(index, next)} fn\n * @param {Function} callback\n * @return {Number}\n */\nNP.async = function(fn, callback) {\n\tvar number = this;\n\tif (number)\n\t\tfn(number--, () => setImmediate(() => number.async(fn, callback)));\n\telse\n\t\tcallback && callback();\n\treturn number;\n};", "/**\n * Format number\n * @param {Number} decimals Maximum decimal numbers\n * @param {String} separator Number separator, default ' '\n * @param {String} separatorDecimal Decimal separator, default '.' if number separator is ',' or ' '.\n * @return {String}\n */\nNP.format = function(decimals, separator, separatorDecimal) {", "\tvar self = this;", "\tif (typeof(decimals) === 'string')\n\t\treturn self.format2(decimals);", "\tvar num = self.toString();\n\tvar dec = '';\n\tvar output = '';\n\tvar minus = num[0] === '-' ? '-' : '';\n\tif (minus)\n\t\tnum = num.substring(1);", "\tvar index = num.indexOf('.');", "\tif (typeof(decimals) === 'string') {\n\t\tvar tmp = separator;\n\t\tseparator = decimals;\n\t\tdecimals = tmp;\n\t}", "\tif (separator === undefined)\n\t\tseparator = ' ';", "\tif (index !== -1) {\n\t\tdec = num.substring(index + 1);\n\t\tnum = num.substring(0, index);\n\t}", "\tindex = -1;\n\tfor (var i = num.length - 1; i >= 0; i--) {\n\t\tindex++;\n\t\tif (index > 0 && index % 3 === 0)\n\t\t\toutput = separator + output;\n\t\toutput = num[i] + output;\n\t}", "\tif (decimals || dec.length) {\n\t\tif (dec.length > decimals)\n\t\t\tdec = dec.substring(0, decimals || 0);\n\t\telse\n\t\t\tdec = dec.padRight(decimals || 0, '0');\n\t}", "\tif (dec.length && separatorDecimal === undefined)\n\t\tseparatorDecimal = separator === '.' ? ',' : '.';", "\treturn minus + output + (dec.length ? separatorDecimal + dec : '');\n};", "NP.add = function(value, decimals) {", "\tif (value == null)\n\t\treturn this;", "\tif (typeof(value) === 'number')\n\t\treturn this + value;", "\tvar first = value.charCodeAt(0);\n\tvar is = false;", "\tif (first < 48 || first > 57) {\n\t\tis = true;\n\t\tvalue = value.substring(1);\n\t}", "\tvar length = value.length;\n\tvar num;", "\tif (value[length - 1] === '%') {\n\t\tvalue = value.substring(0, length - 1);\n\t\tif (is) {\n\t\t\tvar val = value.parseFloat();\n\t\t\tswitch (first) {\n\t\t\t\tcase 42:\n\t\t\t\t\tnum = this * ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 43:\n\t\t\t\t\tnum = this + ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 45:\n\t\t\t\t\tnum = this - ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 47:\n\t\t\t\t\tnum = this / ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn decimals !== undefined ? num.floor(decimals) : num;\n\t\t} else {\n\t\t\tnum = (this / 100) * value.parseFloat();\n\t\t\treturn decimals !== undefined ? num.floor(decimals) : num;\n\t\t}", "\t} else\n\t\tnum = value.parseFloat();", "\tswitch (first) {\n\t\tcase 42:\n\t\t\tnum = this * num;\n\t\t\tbreak;\n\t\tcase 43:\n\t\t\tnum = this + num;\n\t\t\tbreak;\n\t\tcase 45:\n\t\t\tnum = this - num;\n\t\t\tbreak;\n\t\tcase 47:\n\t\t\tnum = this / num;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tnum = this;\n\t\t\tbreak;\n\t}", "\tif (decimals !== undefined)\n\t\treturn num.floor(decimals);", "\treturn num;\n};", "NP.format2 = function(format) {\n\tvar index = 0;\n\tvar num = this.toString();\n\tvar beg = 0;\n\tvar end = 0;\n\tvar max = 0;\n\tvar output = '';\n\tvar length = 0;", "\tif (typeof(format) === 'string') {", "\t\tvar d = false;\n\t\tlength = format.length;", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\tvar c = format[i];\n\t\t\tif (c === '#') {\n\t\t\t\tif (d)\n\t\t\t\t\tend++;\n\t\t\t\telse\n\t\t\t\t\tbeg++;\n\t\t\t}", "\t\t\tif (c === '.')\n\t\t\t\td = true;\n\t\t}", "\t\tvar strBeg = num;\n\t\tvar strEnd = '';", "\t\tindex = num.indexOf('.');", "\t\tif (index !== -1) {\n\t\t\tstrBeg = num.substring(0, index);\n\t\t\tstrEnd = num.substring(index + 1);\n\t\t}", "\t\tif (strBeg.length > beg) {\n\t\t\tmax = strBeg.length - beg;\n\t\t\tvar tmp = '';\n\t\t\tfor (var i = 0; i < max; i++)\n\t\t\t\ttmp += '#';", "\t\t\tformat = tmp + format;\n\t\t}", "\t\tif (strBeg.length < beg)\n\t\t\tstrBeg = strBeg.padLeft(beg, ' ');", "\t\tif (strEnd.length < end)\n\t\t\tstrEnd = strEnd.padRight(end, '0');", "\t\tif (strEnd.length > end)\n\t\t\tstrEnd = strEnd.substring(0, end);", "\t\td = false;\n\t\tindex = 0;", "\t\tvar skip = true;\n\t\tlength = format.length;", "\t\tfor (var i = 0; i < length; i++) {", "\t\t\tvar c = format[i];", "\t\t\tif (c !== '#') {", "\t\t\t\tif (skip)\n\t\t\t\t\tcontinue;", "\t\t\t\tif (c === '.') {\n\t\t\t\t\td = true;\n\t\t\t\t\tindex = 0;\n\t\t\t\t}", "\t\t\t\toutput += c;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tvar value = d ? strEnd[index] : strBeg[index];", "\t\t\tif (skip)\n\t\t\t\tskip = [',', ' '].indexOf(value) !== -1;", "\t\t\tif (!skip)\n\t\t\t\toutput += value;", "\t\t\tindex++;\n\t\t}", "\t\treturn output;\n\t}", "\toutput = '### ### ###';\n\tbeg = num.indexOf('.');\n\tmax = format || 0;", "\tif (max === 0 && beg !== -1)\n\t\tmax = num.length - (beg + 1);", "\tif (max > 0) {\n\t\toutput += '.';\n\t\tfor (var i = 0; i < max; i++)\n\t\t\toutput += '#';\n\t}", "\treturn this.format(output);\n};", "NP.pluralize = function(zero, one, few, other) {", "\tvar num = this;\n\tvar value = '';", "\tif (num == 0)\n\t\tvalue = zero || '';\n\telse if (num == 1)\n\t\tvalue = one || '';\n\telse if (num > 1 && num < 5)\n\t\tvalue = few || '';\n\telse\n\t\tvalue = other;", "\tvar beg = value.indexOf('#');\n\tif (beg === -1)\n\t\treturn value;", "\tvar end = value.lastIndexOf('#');\n\tvar format = value.substring(beg, end + 1);\n\treturn num.format(format) + value.replace(format, '');\n};", "NP.hex = function(length) {\n\tvar str = this.toString(16).toUpperCase();\n\twhile(str.length < length)\n\t\tstr = '0' + str;\n\treturn str;\n};", "NP.VAT = function(percentage, decimals, includedVAT) {\n\tvar num = this;\n\tvar type = typeof(decimals);", "\tif (type === 'boolean') {\n\t\tvar tmp = includedVAT;\n\t\tincludedVAT = decimals;\n\t\tdecimals = tmp;\n\t\ttype = typeof(decimals);\n\t}", "\tif (type === 'undefined')\n\t\tdecimals = 2;", "\tif (includedVAT === undefined)\n\t\tincludedVAT = true;", "\tif (!percentage || !num)\n\t\treturn num;\n\treturn includedVAT ? (num / ((percentage / 100) + 1)).round(decimals) : (num * ((percentage / 100) + 1)).round(decimals);\n};", "NP.discount = function(percentage, decimals) {\n\tvar num = this;\n\tif (decimals === undefined)\n\t\tdecimals = 2;\n\treturn (num - (num / 100) * percentage).floor(decimals);\n};", "NP.parseDate = function(plus) {\n\treturn new Date(this + (plus || 0));\n};", "if (!NP.toRad) {\n\tNP.toRad = function () {\n\t\treturn this * Math.PI / 180;\n\t};\n}", "\nNP.filesize = function(decimals, type) {", "\tif (typeof(decimals) === 'string') {\n\t\tvar tmp = type;\n\t\ttype = decimals;\n\t\tdecimals = tmp;\n\t}", "\tvar value;", "\t// this === bytes\n\tswitch (type) {\n\t\tcase 'bytes':\n\t\t\tvalue = this;\n\t\t\tbreak;\n\t\tcase 'KB':\n\t\t\tvalue = this / 1024;\n\t\t\tbreak;\n\t\tcase 'MB':\n\t\t\tvalue = filesizehelper(this, 2);\n\t\t\tbreak;\n\t\tcase 'GB':\n\t\t\tvalue = filesizehelper(this, 3);\n\t\t\tbreak;\n\t\tcase 'TB':\n\t\t\tvalue = filesizehelper(this, 4);\n\t\t\tbreak;\n\t\tdefault:", "\t\t\ttype = 'bytes';\n\t\t\tvalue = this;", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'KB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'MB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'GB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'TB';\n\t\t\t}", "\t\t\tbreak;\n\t}", "\ttype = ' ' + type;\n\treturn (decimals === undefined ? value.format(2).replace('.00', '') : value.format(decimals)) + type;\n};", "function filesizehelper(number, count) {\n\twhile (count--) {\n\t\tnumber = number / 1024;\n\t\tif (number.toFixed(3) === '0.000')\n\t\t\treturn 0;\n\t}\n\treturn number;\n}", "var AP = Array.prototype;", "/**\n * Take items from array\n * @param {Number} count\n * @return {Array}\n */\nAP.take = function(count) {\n\tvar arr = [];\n\tvar self = this;\n\tvar length = self.length;\n\tfor (var i = 0; i < length; i++) {\n\t\tarr.push(self[i]);\n\t\tif (arr.length >= count)\n\t\t\treturn arr;\n\t}\n\treturn arr;\n};", "/**\n * Extend objects in Array\n * @param {Object} obj\n * @param {Boolean} rewrite Default: false.\n * @return {Array} Returns self\n */\nAP.extend = function(obj, rewrite) {\n\tvar isFn = typeof(obj) === 'function';\n\tfor (var i = 0, length = this.length; i < length; i++) {\n\t\tif (isFn)\n\t\t\tthis[i] = obj(this[i], i);\n\t\telse\n\t\t\tthis[i] = exports.extend(this[i], obj, rewrite);\n\t}\n\treturn this;\n};", "/**\n * First item in array\n * @param {Object} def Default value.\n * @return {Object}\n */\nAP.first = function(def) {\n\tvar item = this[0];\n\treturn item === undefined ? def : item;\n};", "/**\n * Create object from Array\n * @param {String} name Optional, property name.\n * @return {Object}\n */\nAP.toObject = function(name) {", "\tvar self = this;\n\tvar obj = {};", "\tfor (var i = 0, length = self.length; i < length; i++) {\n\t\tvar item = self[i];\n\t\tif (name)\n\t\t\tobj[item[name]] = item;\n\t\telse\n\t\t\tobj[item] = true;\n\t}", "\treturn obj;\n};", "/**\n * Compare two arrays\n * @param {String} id An identificator.\n * @param {Array} b Second array.\n * @param {Function(itemA, itemB, indexA, indexB)} executor\n */\nAP.compare = function(id, b, executor) {", "\tvar a = this;\n\tvar ak = {};\n\tvar bk = {};\n\tvar al = a.length;\n\tvar bl = b.length;\n\tvar tl = Math.max(al, bl);\n\tvar processed = {};", "\tfor (var i = 0; i < tl; i++) {\n\t\tvar av = a[i];\n\t\tif (av)\n\t\t\tak[av[id]] = i;\n\t\tvar bv = b[i];\n\t\tif (bv)\n\t\t\tbk[bv[id]] = i;\n\t}", "\tvar index = -1;", "\tfor (var i = 0; i < tl; i++) {", "\t\tvar av = a[i];\n\t\tvar bv = b[i];\n\t\tvar akk;\n\t\tvar bkk;", "\t\tif (av) {\n\t\t\takk = av[id];\n\t\t\tif (processed[akk])\n\t\t\t\tcontinue;\n\t\t\tprocessed[akk] = true;\n\t\t\tindex = bk[akk];\n\t\t\tif (index === undefined)\n\t\t\t\texecutor(av, undefined, i, -1);\n\t\t\telse\n\t\t\t\texecutor(av, b[index], i, index);\n\t\t}", "\t\tif (bv) {\n\t\t\tbkk = bv[id];\n\t\t\tif (processed[bkk])\n\t\t\t\tcontinue;\n\t\t\tprocessed[bkk] = true;\n\t\t\tindex = ak[bkk];\n\t\t\tif (index === undefined)\n\t\t\t\texecutor(undefined, bv, -1, i);\n\t\t\telse\n\t\t\t\texecutor(a[index], bv, index, i);\n\t\t}\n\t}", "\tOBSOLETE('Array.compare()', 'Use U.diff() insteadof Array.compare()');\n};", "/**\n * Pair arrays\n * @param {Array} arr\n * @param {String} property\n * @param {Function(itemA, itemB)} fn Paired items (itemA == this, itemB == arr)\n * @param {Boolean} remove Optional, remove item from this array if the item doesn't exist int arr (default: false).\n * @return {Array}\n */\nAP.pair = function(property, arr, fn, remove) {", "\tif (property instanceof Array) {\n\t\tvar tmp = property;\n\t\tproperty = arr;\n\t\tarr = tmp;\n\t}", "\tif (!arr)\n\t\tarr = new Array(0);", "\tvar length = arr.length;\n\tvar index = 0;", "\twhile (true) {\n\t\tvar item = this[index++];\n\t\tif (!item)\n\t\t\tbreak;", "\t\tvar is = false;", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\tif (item[property] !== arr[i][property])\n\t\t\t\tcontinue;\n\t\t\tfn(item, arr[i]);\n\t\t\tis = true;\n\t\t\tbreak;\n\t\t}", "\t\tif (is || !remove)\n\t\t\tcontinue;", "\t\tindex--;\n\t\tthis.splice(index, 1);\n\t}", "\tOBSOLETE('Array.pair()', 'The method will be removed in Total.js v4');\n\treturn this;\n};", "/**\n * Last item in array\n * @param {Object} def Default value.\n * @return {Object}\n */\nAP.last = function(def) {\n\tvar item = this[this.length - 1];\n\treturn item === undefined ? def : item;\n};", "AP.quicksort = AP.orderBy = function(name, asc) {", "\tvar length = this.length;\n\tif (!length || length === 1)\n\t\treturn this;", "\tif (typeof(name) === 'boolean') {\n\t\tasc = name;\n\t\tname = undefined;\n\t} else if (asc === undefined)\n\t\tasc = true;\n\telse {\n\t\tswitch (asc) {\n\t\t\tcase 'asc':\n\t\t\tcase 'ASC':\n\t\t\t\tasc = true;\n\t\t\t\tbreak;\n\t\t\tcase 'desc':\n\t\t\tcase 'DESC':\n\t\t\t\tasc = false;\n\t\t\t\tbreak;\n\t\t}\n\t}", "\tvar self = this;\n\tvar type = 0;\n\tvar field = name ? self[0][name] : self[0];", "\tswitch (typeof(field)) {\n\t\tcase 'string':\n\t\t\tif (field.isJSONDate())\n\t\t\t\ttype = 4;\n\t\t\telse\n\t\t\t\ttype = 1;\n\t\t\tbreak;\n\t\tcase 'number':\n\t\t\ttype = 2;\n\t\t\tbreak;\n\t\tcase 'boolean':\n\t\t\ttype = 3;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!exports.isDate(field))\n\t\t\t\treturn self;\n\t\t\ttype = 4;\n\t\t\tbreak;\n\t}", "\tshellsort(self, function(a, b) {", "\t\tvar va = name ? a[name] : a;\n\t\tvar vb = name ? b[name] : b;", "\t\t// String\n\t\tif (type === 1) {\n\t\t\treturn va && vb ? (asc ? COMPARER(va, vb) : COMPARER(vb, va)) : 0;\n\t\t} else if (type === 2) {\n\t\t\treturn va > vb ? (asc ? 1 : -1) : va < vb ? (asc ? -1 : 1) : 0;\n\t\t} else if (type === 3) {\n\t\t\treturn va === true && vb === false ? (asc ? 1 : -1) : va === false && vb === true ? (asc ? -1 : 1) : 0;\n\t\t} else if (type === 4) {\n\t\t\tif (!va || !vb)\n\t\t\t\treturn 0;\n\t\t\tif (!va.getTime)\n\t\t\t\tva = new Date(va);\n\t\t\tif (!vb.getTime)\n\t\t\t\tvb = new Date(vb);\n\t\t\tvar at = va.getTime();\n\t\t\tvar bt = vb.getTime();\n\t\t\treturn at > bt ? (asc ? 1 : -1) : at < bt ? (asc ? -1 : 1) : 0;\n\t\t}\n\t\treturn 0;\n\t});", "\treturn self;\n};", "AP.trim = function() {\n\tvar self = this;\n\tvar output = [];\n\tfor (var i = 0, length = self.length; i < length; i++) {\n\t\tif (typeof(self[i]) === 'string')\n\t\t\tself[i] = self[i].trim();\n\t\tself[i] && output.push(self[i]);\n\t}\n\treturn output;\n};", "/**\n * Skip items from array\n * @param {Number} count\n * @return {Array}\n */\nAP.skip = function(count) {\n\tvar arr = [];\n\tvar self = this;\n\tvar length = self.length;\n\tfor (var i = 0; i < length; i++)\n\t\ti >= count && arr.push(self[i]);\n\treturn arr;\n};", "/**\n * Find items in Array\n * @param {Function(item, index) or String/Object} cb\n * @param {Object} value Optional.\n * @return {Array}\n */\nAP.where = AP.findAll = function(cb, value) {", "\tvar self = this;\n\tvar selected = [];\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\tcb.call(self, self[i], i) && selected.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tself[i] && self[i][cb] === value && selected.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tself[i] === cb && selected.push(self[i]);\n\t}", "\treturn selected;\n};", "/**\n * Find item in Array\n * @param {Function(item, index) or String/Object} cb\n * @param {Object} value Optional.\n * @return {Array}\n */\nAP.findItem = function(cb, value) {\n\tvar self = this;\n\tvar index = self.findIndex(cb, value);\n\tif (index === -1)\n\t\treturn null;\n\treturn self[index];\n};", "var arrfindobsolete;", "AP.find = function(cb, value) {", "\tif (!arrfindobsolete) {\n\t\tarrfindobsolete = true;\n\t\tOBSOLETE('Array.prototype.find()', 'will be removed in v4, use alternative \"Array.prototype.findItem()\"');\n\t}", "\tvar self = this;\n\tvar index = self.findIndex(cb, value);\n\tif (index === -1)\n\t\treturn null;\n\treturn self[index];\n};", "AP.findIndex = function(cb, value) {", "\tvar self = this;\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\tif (cb.call(self, self[i], i))\n\t\t\t\treturn i;\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tif (self[i] && self[i][cb] === value)\n\t\t\t\treturn i;\n\t\t\tcontinue;\n\t\t}", "\t\tif (self[i] === cb)\n\t\t\treturn i;\n\t}", "\treturn -1;\n};", "/**\n * Remove items from Array\n * @param {Function(item, index) or Object} cb\n * @param {Object} value Optional.\n * @return {Array}\n */\nAP.remove = function(cb, value) {", "\tvar self = this;\n\tvar arr = [];\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\t!cb.call(self, self[i], i) && arr.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tself[i] && self[i][cb] !== value && arr.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tself[i] !== cb && arr.push(self[i]);\n\t}\n\treturn arr;\n};", "AP.wait = AP.waitFor = function(onItem, callback, thread, tmp) {", "\tvar self = this;\n\tvar init = false;", "\t// INIT\n\tif (!tmp) {", "\t\tif (typeof(callback) !== 'function') {\n\t\t\tthread = callback;\n\t\t\tcallback = null;\n\t\t}", "\t\ttmp = {};\n\t\ttmp.pending = 0;\n\t\ttmp.index = 0;\n\t\ttmp.thread = thread;", "\t\t// thread === Boolean then array has to be removed item by item", "\t\tinit = true;\n\t}", "\tvar item = thread === true ? self.shift() : self[tmp.index++];\n\tif (item === undefined) {\n\t\tif (!tmp.pending) {\n\t\t\tcallback && callback();\n\t\t\ttmp.cancel = true;\n\t\t}\n\t\treturn self;\n\t}", "\ttmp.pending++;\n\tonItem.call(self, item, () => setImmediate(next_wait, self, onItem, callback, thread, tmp), tmp.index);", "\tif (!init || tmp.thread === 1)\n\t\treturn self;", "\tfor (var i = 1; i < tmp.thread; i++)\n\t\tself.wait(onItem, callback, 1, tmp);", "\treturn self;\n};", "function next_wait(self, onItem, callback, thread, tmp) {\n\ttmp.pending--;\n\tself.wait(onItem, callback, thread, tmp);\n}", "/**\n * Creates a function async list\n * @param {Function} callback Optional\n * @return {Array}\n */\nAP.async = function(thread, callback, pending) {", "\tvar self = this;", "\tif (typeof(thread) === 'function') {\n\t\tcallback = thread;\n\t\tthread = 1;\n\t} else if (thread === undefined)\n\t\tthread = 1;", "\tif (pending === undefined)\n\t\tpending = 0;", "\tvar item = self.shift();\n\tif (item === undefined) {\n\t\tif (!pending) {\n\t\t\tpending = undefined;\n\t\t\tcallback && callback();\n\t\t}\n\t\treturn self;\n\t}", "\tfor (var i = 0; i < thread; i++) {", "\t\tif (i)\n\t\t\titem = self.shift();", "\t\tpending++;\n\t\titem(function() {\n\t\t\tsetImmediate(function() {\n\t\t\t\tpending--;\n\t\t\t\tself.async(1, callback, pending);\n\t\t\t});\n\t\t});\n\t}", "\treturn self;\n};", "AP.randomize = function() {\n\tOBSOLETE('Array.randomize()', 'Use Array.random().');\n\treturn this.random();\n};", "// Fisher-Yates shuffle\nAP.random = function() {\n\tfor (var i = this.length - 1; i > 0; i--) {\n\t\tvar j = Math.floor(Math.random() * (i + 1));\n\t\tvar temp = this[i];\n\t\tthis[i] = this[j];\n\t\tthis[j] = temp;\n\t}\n\treturn this;\n};", "AP.limit = function(max, fn, callback, index) {", "\tif (index === undefined)\n\t\tindex = 0;", "\tvar current = [];\n\tvar self = this;\n\tvar length = index + max;", "\tfor (var i = index; i < length; i++) {\n\t\tvar item = self[i];", "\t\tif (item !== undefined) {\n\t\t\tcurrent.push(item);\n\t\t\tcontinue;\n\t\t}", "\t\tif (!current.length) {\n\t\t\tcallback && callback();\n\t\t\treturn self;\n\t\t}", "\t\tfn(current, () => callback && callback(), index, index + max);\n\t\treturn self;\n\t}", "\tif (!current.length) {\n\t\tcallback && callback();\n\t\treturn self;\n\t}", "\tfn(current, function() {\n\t\tif (length < self.length)\n\t\t\tself.limit(max, fn, callback, length);\n\t\telse\n\t\t\tcallback && callback();\n\t}, index, index + max);", "\treturn self;\n};", "/**\n * Get unique elements from Array\n * @return {[type]} [description]\n */\nAP.unique = function(property) {", "\tvar self = this;\n\tvar result = [];\n\tvar sublength = 0;", "\tfor (var i = 0, length = self.length; i < length; i++) {\n\t\tvar value = self[i];", "\t\tif (!property) {\n\t\t\tresult.indexOf(value) === -1 && result.push(value);\n\t\t\tcontinue;\n\t\t}", "\t\tif (sublength === 0) {\n\t\t\tresult.push(value);\n\t\t\tsublength++;\n\t\t\tcontinue;\n\t\t}", "\t\tvar is = true;\n\t\tfor (var j = 0; j < sublength; j++) {\n\t\t\tif (result[j][property] === value[property]) {\n\t\t\t\tis = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (is) {\n\t\t\tresult.push(value);\n\t\t\tsublength++;\n\t\t}\n\t}", "\treturn result;\n};", "ArrayBuffer.prototype.toBuffer = function() {\n\tvar buf = new Buffer(this.byteLength);\n\tvar view = new Uint8Array(this);\n\tfor (var i = 0, length = buf.length; i < length; ++i)\n\t\tbuf[i] = view[i];\n\treturn buf;\n};", "function AsyncTask(owner, name, fn, cb, waiting) {\n\tthis.isRunning = 0;\n\tthis.owner = owner;\n\tthis.name = name;\n\tthis.fn = fn;\n\tthis.cb = cb;\n\tthis.waiting = waiting;\n\tthis.interval = null;\n\tthis.isCanceled = false;\n}", "AsyncTask.prototype.run = function() {\n\tvar self = this;\n\ttry\n\t{", "\t\tif (self.isCanceled) {\n\t\t\tself.complete();\n\t\t\treturn self;\n\t\t}", "\t\tself.isRunning = 1;\n\t\tself.owner.tasksWaiting[self.name] = true;\n\t\tself.owner.emit('begin', self.name);", "\t\tvar timeout = self.owner.tasksTimeout[self.name];\n\t\tif (timeout > 0)\n\t\t\tself.interval = setTimeout(function() { self.timeout(); }, timeout);", "\t\tself.fn(function() {\n\t\t\tsetImmediate(() => self.complete());\n\t\t});", "\t} catch (ex) {\n\t\tself.owner.emit('error', self.name, ex);\n\t\tself.complete();\n\t}\n\treturn self;\n};", "AsyncTask.prototype.timeout = function(timeout) {", "\tvar self = this;", "\tif (timeout > 0) {\n\t\tclearTimeout(self.interval);\n\t\tsetTimeout(function() { self.timeout(); }, timeout);\n\t\treturn self;\n\t}", "\tif (timeout <= 0) {\n\t\tclearTimeout(self.interval);\n\t\tsetTimeout(function() { self.timeout(); }, timeout);\n\t\treturn self;\n\t}", "\tsetImmediate(() => self.cancel(true));\n\treturn self;\n};", "AsyncTask.prototype.cancel = function(isTimeout) {\n\tvar self = this;", "\tself.isCanceled = true;", "\tif (isTimeout)\n\t\tself.owner.emit('timeout', self.name);\n\telse\n\t\tself.owner.emit('cancel', self.name);", "\tself.fn = null;\n\tself.cb = null;\n\tself.complete();\n\treturn self;\n};", "AsyncTask.prototype.complete = function() {", "\tvar item = this;\n\tvar self = item.owner;", "\titem.isRunning = 2;", "\tdelete self.tasksPending[item.name];\n\tdelete self.tasksWaiting[item.name];", "\tif (!item.isCanceled) {\n\t\ttry\n\t\t{\n\t\t\tself.emit('end', item.name);\n\t\t\titem.cb && item.cb();\n\t\t} catch (ex) {\n\t\t\tself.emit('error', ex, item.name);\n\t\t}\n\t}", "\tsetImmediate(function() {\n\t\tself.reload();\n\t\tself.refresh();\n\t});", "\treturn self;\n};", "function Async(owner) {", "\tthis._max = 0;\n\tthis._count = 0;\n\tthis._isRunning = false;\n\tthis._isEnd = false;", "\tthis.owner = owner;\n\tthis.onComplete = [];", "\tthis.tasksPending = {};\n\tthis.tasksWaiting = {};\n\tthis.tasksAll = [];\n\tthis.tasksTimeout = {};\n\tthis.isCanceled = false;", "\tEvents.EventEmitter.call(this);\n}", "Async.prototype = {\n\tget count() {\n\t\treturn this._count;\n\t},", "\tget percentage() {\n\t\tvar p = 100 - Math.floor((this._count * 100) / this._max);\n\t\treturn p ? p : 0;\n\t}\n};", "const ACP = Async.prototype;", "ACP.__proto__ = Object.create(Events.EventEmitter.prototype, {\n\tconstructor: {\n\t\tvalue: Async,\n\t\tenumberable: false\n\t}\n});", "ACP.reload = function() {\n\tvar self = this;\n\tself.tasksAll = Object.keys(self.tasksPending);\n\tself.emit('percentage', self.percentage);\n\treturn self;\n};", "ACP.cancel = function(name) {", "\tvar self = this;", "\tif (name === undefined) {\n\t\tself.isCanceled = true;\n\t\tfor (var i = 0; i < self._count; i++)\n\t\t\tself.cancel(self.tasksAll[i]);\n\t\treturn true;\n\t}", "\tvar task = self.tasksPending[name];\n\tif (!task)\n\t\treturn false;", "\tdelete self.tasksPending[name];\n\tdelete self.tasksWaiting[name];", "\ttask.cancel();\n\ttask = null;\n\tself.reload();\n\tself.refresh();", "\treturn true;\n};", "ACP.await = function(name, fn, cb) {", "\tvar self = this;", "\tif (self.isCanceled)\n\t\treturn false;", "\tif (typeof(name) === 'function') {\n\t\tcb = fn;\n\t\tfn = name;\n\t\tname = exports.GUID(6);\n\t}", "\tif (self.tasksPending[name])\n\t\treturn false;", "\tself.tasksPending[name] = new AsyncTask(self, name, fn, cb, null);\n\tself._max++;\n\tself.reload();\n\tself.refresh();\n\treturn true;\n};", "ACP.wait = function(name, waitingFor, fn, cb) {", "\tvar self = this;", "\tif (self.isCanceled)\n\t\treturn false;", "\tif (typeof(waitingFor) === 'function') {\n\t\tcb = fn;\n\t\tfn = waitingFor;\n\t\twaitingFor = null;\n\t}", "\tif (self.tasksPending[name])\n\t\treturn false;", "\tself.tasksPending[name] = new AsyncTask(self, name, fn, cb, waitingFor);\n\tself._max++;\n\tself.reload();\n\tself.refresh();\n\treturn true;\n};", "ACP.complete = function(fn) {\n\treturn this.run(fn);\n};", "ACP.run = function(fn) {\n\tthis._isRunning = true;\n\tfn && this.onComplete.push(fn);\n\tthis.refresh();\n\treturn this;\n};", "ACP.isRunning = function(name) {\n\tif (!name)\n\t\treturn this._isRunning;\n\tvar task = this.tasksPending[name];\n\treturn task ? task.isRunning === 1 : false;\n};", "ACP.isWaiting = function(name) {\n\tvar task = this.tasksPending[name];\n\treturn task ? task.isRunning === 0 : false;\n};", "ACP.isPending = function(name) {\n\treturn this.tasksPending[name] ? true : false;\n};", "ACP.timeout = function(name, timeout) {\n\tif (timeout)\n\t\tthis.tasksTimeout[name] = timeout;\n\telse\n\t\tthis.tasksTimeout[name] = undefined;\n\treturn this;\n};", "ACP.refresh = function(name) {", "\tvar self = this;", "\tif (!self._isRunning || self._isEnd)\n\t\treturn self;", "\tself._count = self.tasksAll.length;\n\tvar index = 0;", "\twhile (true) {\n\t\tvar name = self.tasksAll[index++];\n\t\tif (!name)\n\t\t\tbreak;", "\t\tvar task = self.tasksPending[name];\n\t\tif (!task)\n\t\t\tbreak;", "\t\tif (self.isCanceled || task.isCanceled) {\n\t\t\tdelete self.tasksPending[name];\n\t\t\tdelete self.tasksWaiting[name];\n\t\t\tself.tasksAll.splice(index, 1);\n\t\t\tself._count = self.tasksAll.length;\n\t\t\tindex--;\n\t\t\tcontinue;\n\t\t}", "\t\tif (task.isRunning !== 0 || (task.waiting && self.tasksPending[task.waiting]))\n\t\t\tcontinue;", "\t\ttask.run();\n\t}", "\tif (self._count === 0) {\n\t\tself._isRunning = false;\n\t\tself._isEnd = true;\n\t\tself.emit('complete');\n\t\tself.emit('percentage', 100);\n\t\tself._max = 0;\n\t\tvar complete = self.onComplete;\n\t\tvar length = complete.length;\n\t\tself.onComplete = [];\n\t\tfor (var i = 0; i < length; i++) {\n\t\t\ttry\n\t\t\t{\n\t\t\t\tcomplete[i]();\n\t\t\t} catch (ex) {\n\t\t\t\tself.emit('error', ex);\n\t\t\t}\n\t\t}\n\t\tsetImmediate(() => self._isEnd = false);\n\t}", "\treturn self;\n};", "function FileList() {\n\tthis.pending = [];\n\tthis.pendingDirectory = [];\n\tthis.directory = [];\n\tthis.file = [];\n\tthis.onComplete = null;\n\tthis.onFilter = null;\n\tthis.advanced = false;\n}", "const FLP = FileList.prototype;", "FLP.reset = function() {\n\tthis.file.length = 0;\n\tthis.directory.length = 0;\n\tthis.pendingDirectory.length = 0;\n\treturn this;\n};", "FLP.walk = function(directory) {", "\tvar self = this;", "\tif (directory instanceof Array) {\n\t\tvar length = directory.length;\n\t\tfor (var i = 0; i < length; i++)\n\t\t\tself.pendingDirectory.push(directory[i]);\n\t\tself.next();\n\t\treturn;\n\t}", "\tFs.readdir(directory, function(err, arr) {\n\t\tif (err)\n\t\t\treturn self.next();\n\t\tvar length = arr.length;\n\t\tfor (var i = 0; i < length; i++)\n\t\t\tself.pending.push(Path.join(directory, arr[i]));\n\t\tself.next();\n\t});\n};", "FLP.stat = function(path) {\n\tvar self = this;", "\tFs.stat(path, function(err, stats) {", "\t\tif (err)\n\t\t\treturn self.next();", "\t\tif (stats.isDirectory()) {\n\t\t\tpath = self.clean(path);\n\t\t\tif (!self.onFilter || self.onFilter(path, true)) {\n\t\t\t\tself.directory.push(path);\n\t\t\t\tself.pendingDirectory.push(path);\n\t\t\t}\n\t\t} else if (!self.onFilter || self.onFilter(path, false))\n\t\t\tself.file.push(self.advanced ? { filename: path, stats: stats } : path);", "\t\tself.next();\n\t});\n};", "FLP.clean = function(path) {\n\treturn path[path.length - 1] === Path.sep ? path : path + Path.sep;\n};", "FLP.next = function() {\n\tvar self = this;", "\tif (self.pending.length) {\n\t\tvar item = self.pending.shift();\n\t\tself.stat(item);\n\t\treturn;\n\t}", "\tif (self.pendingDirectory.length) {\n\t\tvar directory = self.pendingDirectory.shift();\n\t\tself.walk(directory);\n\t\treturn;\n\t}", "\tself.onComplete(self.file, self.directory);\n};", "exports.Async = Async;", "exports.sync = function(fn, owner) {\n\treturn function() {", "\t\tvar args = [].slice.call(arguments);\n\t\tvar params;\n\t\tvar callback;\n\t\tvar executed = false;\n\t\tvar self = owner || this;", "\t\targs.push(function() {\n\t\t\tparams = arguments;\n\t\t\tif (!executed && callback) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t});", "\t\tfn.apply(self, args);", "\t\treturn function(cb) {\n\t\t\tcallback = cb;\n\t\t\tif (!executed && params) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t};\n\t};\n};", "exports.sync2 = function(fn, owner) {\n\treturn (function() {", "\t\tvar params;\n\t\tvar callback;\n\t\tvar executed = false;\n\t\tvar self = owner || this;\n\t\tvar args = [].slice.call(arguments);", "\t\targs.push(function() {\n\t\t\tparams = arguments;\n\t\t\tif (!executed && callback) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t});", "\t\tfn.apply(self, args);", "\t\treturn function(cb) {\n\t\t\tcallback = cb;\n\t\t\tif (!executed && params) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t};\n\t})();\n};", "exports.async = function(fn, isApply) {\n\tvar context = this;\n\treturn function(complete) {", "\t\tvar self = this;\n\t\tvar argv;", "\t\tif (arguments.length) {", "\t\t\tif (isApply) {\n\t\t\t\t// index.js/Subscribe.prototype.doExecute\n\t\t\t\targv = arguments[1];\n\t\t\t} else {\n\t\t\t\targv = [];\n\t\t\t\tfor (var i = 1; i < arguments.length; i++)\n\t\t\t\t\targv.push(arguments[i]);\n\t\t\t}\n\t\t} else\n\t\t\targv = new Array(0);", "\t\tvar generator = fn.apply(context, argv);\n\t\tnext(null);", "\t\tfunction next(err, result) {", "\t\t\tvar g, type;", "\t\t\ttry\n\t\t\t{\n\t\t\t\tvar can = err ? false : true;\n\t\t\t\tswitch (can) {\n\t\t\t\t\tcase true:\n\t\t\t\t\t\tg = generator.next(result);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase false:\n\t\t\t\t\t\tg = generator.throw(err);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}", "\t\t\t} catch (e) {", "\t\t\t\tif (!complete)\n\t\t\t\t\treturn;", "\t\t\t\ttype = typeof(complete);", "\t\t\t\tif (type === 'object' && complete.isController) {\n\t\t\t\t\tif (e instanceof ErrorBuilder)\n\t\t\t\t\t\tcomplete.content(e);\n\t\t\t\t\telse\n\t\t\t\t\t\tcomplete.view500(e);\n\t\t\t\t\treturn;\n\t\t\t\t}", "\t\t\t\ttype === 'function' && setImmediate(() => complete(e));\n\t\t\t\treturn;\n\t\t\t}", "\t\t\tif (g.done) {\n\t\t\t\ttypeof(complete) === 'function' && complete(null, g.value);\n\t\t\t\treturn;\n\t\t\t}", "\t\t\tvar promise = g.value instanceof Promise;", "\t\t\tif (typeof(g.value) !== 'function' && !promise) {\n\t\t\t\tnext.call(self, null, g.value);\n\t\t\t\treturn;\n\t\t\t}", "\t\t\ttry\n\t\t\t{\n\t\t\t\tif (promise) {\n\t\t\t\t\tg.value.then((value) => next.call(self, null, value));\n\t\t\t\t\treturn;\n\t\t\t\t}", "\t\t\t\tg.value.call(self, function() {\n\t\t\t\t\tnext.apply(self, arguments);\n\t\t\t\t});", "\t\t\t} catch (e) {\n\t\t\t\tsetImmediate(() => next.call(self, e));\n\t\t\t}\n\t\t}", "\t\treturn generator.value;\n\t};\n};", "// MIT\n// Written by Jozef Gula\n// Optimized by Peter Sirka\nconst CACHE_GML1 = [null, null, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];\nconst CACHE_GML2 = [null, null, null, null, null, null, null, null];\nexports.getMessageLength = function(data, isLE) {", "\tvar length = data[1] & 0x7f;", "\tif (length === 126) {\n\t\tif (data.length < 4)\n\t\t\treturn -1;\n\t\tCACHE_GML1[0] = data[3];\n\t\tCACHE_GML1[1] = data[2];\n\t\treturn converBytesToInt64(CACHE_GML1, 0, isLE);\n\t}", "\tif (length === 127) {\n\t\tif (data.Length < 10)\n\t\t\treturn -1;\n\t\tCACHE_GML2[0] = data[9];\n\t\tCACHE_GML2[1] = data[8];\n\t\tCACHE_GML2[2] = data[7];\n\t\tCACHE_GML2[3] = data[6];\n\t\tCACHE_GML2[4] = data[5];\n\t\tCACHE_GML2[5] = data[4];\n\t\tCACHE_GML2[6] = data[3];\n\t\tCACHE_GML2[7] = data[2];\n\t\treturn converBytesToInt64(CACHE_GML2, 0, isLE);\n\t}", "\treturn length;\n};", "// MIT\n// Written by Jozef Gula\nfunction converBytesToInt64(data, startIndex, isLE) {\n\treturn isLE ? (data[startIndex] | (data[startIndex + 1] << 0x08) | (data[startIndex + 2] << 0x10) | (data[startIndex + 3] << 0x18) | (data[startIndex + 4] << 0x20) | (data[startIndex + 5] << 0x28) | (data[startIndex + 6] << 0x30) | (data[startIndex + 7] << 0x38)) : ((data[startIndex + 7] << 0x20) | (data[startIndex + 6] << 0x28) | (data[startIndex + 5] << 0x30) | (data[startIndex + 4] << 0x38) | (data[startIndex + 3]) | (data[startIndex + 2] << 0x08) | (data[startIndex + 1] << 0x10) | (data[startIndex] << 0x18));\n}", "exports.queuecache = {};", "function queue_next(name) {", "\tvar item = exports.queuecache[name];\n\tif (!item)\n\t\treturn;", "\titem.running--;", "\tif (item.running < 0)\n\t\titem.running = 0;", "\tif (item.pending.length) {\n\t\tvar fn = item.pending.shift();\n\t\tif (fn) {\n\t\t\titem.running++;\n\t\t\tsetImmediate(queue_next_callback, fn, name);\n\t\t} else\n\t\t\titem.running = 0;\n\t}\n}", "function queue_next_callback(fn, name) {\n\tfn(() => queue_next(name));\n}", "/**\n * Queue list\n * @param {String} name\n * @param {Number} max Maximum stack.\n * @param {Function(next)} fn\n */\nexports.queue = function(name, max, fn) {", "\tif (!fn)\n\t\treturn false;", "\tif (!max) {\n\t\tfn(NOOP);\n\t\treturn true;\n\t}", "\tif (!exports.queuecache[name])\n\t\texports.queuecache[name] = { limit: max, running: 0, pending: [] };", "\tvar item = exports.queuecache[name];\n\tif (item.running >= item.limit) {\n\t\titem.pending.push(fn);\n\t\treturn false;\n\t}", "\titem.running++;\n\tsetImmediate(queue_next_callback, fn, name);\n\treturn true;\n};", "exports.minifyStyle = function(val) {\n\treturn Internal.compile_css(val);\n};", "exports.minifyScript = function(val) {\n\treturn Internal.compile_javascript(val);\n};", "exports.minifyHTML = function(val) {\n\treturn Internal.compile_html(val);\n};", "exports.parseTheme = function(value) {\n\tif (value[0] !== '=')\n\t\treturn '';\n\tvar index = value.indexOf('/', 2);\n\tif (index === -1)\n\t\treturn '';\n\tvalue = value.substring(1, index);\n\treturn value === '?' ? CONF.default_theme : value;\n};", "exports.set = function(obj, path, value) {\n\tvar cachekey = 'S+' + path;", "\tif (F.temporary.other[cachekey])\n\t\treturn F.temporary.other[cachekey](obj, value);", "\tvar arr = parsepath(path);\n\tvar builder = [];", "\tfor (var i = 0; i < arr.length - 1; i++) {\n\t\tvar type = arr[i + 1] ? (REGISARR.test(arr[i + 1]) ? '[]' : '{}') : '{}';\n\t\tvar p = 'w' + (arr[i][0] === '[' ? '' : '.') + arr[i];\n\t\tbuilder.push('if(typeof(' + p + ')!==\\'object\\'||' + p + '==null)' + p + '=' + type + ';');\n\t}", "\tvar v = arr[arr.length - 1];\n\tvar ispush = v.lastIndexOf('[]') !== -1;\n\tvar a = builder.join(';') + ';var v=typeof(a)===\\'function\\'?a(U.get(b)):a;w' + (v[0] === '[' ? '' : '.') + (ispush ? v.replace(REGREPLACEARR, '.push(v)') : (v + '=v')) + ';return v';\n", "\tif ((/__proto__|constructor|prototype/).test(a))\n\t\tthrow new Error('Prototype pollution');", "\n\tvar fn = new Function('w', 'a', 'b', a);\n\tF.temporary.other[cachekey] = fn;\n\tfn(obj, value, path);\n};", "exports.get = function(obj, path) {", "\tvar cachekey = 'G=' + path;", "\tif (F.temporary.other[cachekey])\n\t\treturn F.temporary.other[cachekey](obj);", "\tvar arr = parsepath(path);\n\tvar builder = [];", "\tfor (var i = 0, length = arr.length - 1; i < length; i++)\n\t\tbuilder.push('if(!w' + (!arr[i] || arr[i][0] === '[' ? '' : '.') + arr[i] + ')return');", "\tvar v = arr[arr.length - 1];\n\tvar fn = (new Function('w', builder.join(';') + ';return w' + (v[0] === '[' ? '' : '.') + v));\n\tF.temporary.other[cachekey] = fn;\n\treturn fn(obj);\n};", "function parsepath(path) {", "\tvar arr = path.split('.');\n\tvar builder = [];\n\tvar all = [];", "\tfor (var i = 0; i < arr.length; i++) {\n\t\tvar p = arr[i];\n\t\tvar index = p.indexOf('[');\n\t\tif (index === -1) {\n\t\t\tif (p.indexOf('-') === -1) {\n\t\t\t\tall.push(p);\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t} else {\n\t\t\t\tvar a = all.splice(all.length - 1);\n\t\t\t\tall.push(a + '[\\'' + p + '\\']');\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t}\n\t\t} else {\n\t\t\tif (p.indexOf('-') === -1) {\n\t\t\t\tall.push(p.substring(0, index));\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t\tall.splice(all.length - 1);\n\t\t\t\tall.push(p);\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t} else {\n\t\t\t\tall.push('[\\'' + p.substring(0, index) + '\\']');\n\t\t\t\tbuilder.push(all.join(''));\n\t\t\t\tall.push(p.substring(index));\n\t\t\t\tbuilder.push(all.join(''));\n\t\t\t}\n\t\t}\n\t}", "\treturn builder;\n}", "global.Async = global.async = exports.async;\nglobal.sync = global.SYNCHRONIZE = exports.sync;\nglobal.sync2 = exports.sync2;", "// =============================================\n// SHELL SORT IMPLEMENTATION OF ALGORITHM\n// =============================================", "function _shellInsertionSort(list, length, gapSize, fn) {\n\tvar temp, i, j;\n\tfor (i = gapSize; i < length; i += gapSize ) {\n\t\tj = i;\n\t\twhile(j > 0 && fn(list[j - gapSize], list[j]) === 1) {\n\t\t\ttemp = list[j];\n\t\t\tlist[j] = list[j - gapSize];\n\t\t\tlist[j - gapSize] = temp;\n\t\t\tj -= gapSize;\n\t\t}\n\t}\n}", "function shellsort(arr, fn) {\n\tvar length = arr.length;\n\tvar gapSize = Math.floor(length / 2);\n\twhile(gapSize) {\n\t\t_shellInsertionSort(arr, length, gapSize, fn);\n\t\tgapSize = Math.floor(gapSize / 2);\n\t}\n\treturn arr;\n}", "function EventEmitter2(obj) {\n\tif (obj) {\n\t\t!obj.emit && EventEmitter2.extend(obj);\n\t\treturn obj;\n\t} else\n\t\tthis.$events = {};\n}", "const EE2P = EventEmitter2.prototype;", "EE2P.emit = function(name, a, b, c, d, e, f, g) {", "\tif (!this.$events)\n\t\treturn this;", "\tvar evt = this.$events[name];\n\tif (evt) {\n\t\tvar clean = false;\n\t\tfor (var i = 0, length = evt.length; i < length; i++) {\n\t\t\tif (evt[i].$once)\n\t\t\t\tclean = true;\n\t\t\tevt[i].call(this, a, b, c, d, e, f, g);\n\t\t}\n\t\tif (clean) {\n\t\t\tevt = evt.remove(n => n.$once);\n\t\t\tif (evt.length)\n\t\t\t\tthis.$events[name] = evt;\n\t\t\telse\n\t\t\t\tthis.$events[name] = undefined;\n\t\t}\n\t}\n\treturn this;\n};", "EE2P.on = function(name, fn) {\n\tif (!this.$events)\n\t\tthis.$events = {};\n\tif (this.$events[name])\n\t\tthis.$events[name].push(fn);\n\telse\n\t\tthis.$events[name] = [fn];\n\treturn this;\n};", "EE2P.once = function(name, fn) {\n\tfn.$once = true;\n\treturn this.on(name, fn);\n};", "EE2P.removeListener = function(name, fn) {\n\tif (this.$events) {\n\t\tvar evt = this.$events[name];\n\t\tif (evt) {\n\t\t\tevt = evt.remove(n => n === fn);\n\t\t\tif (evt.length)\n\t\t\t\tthis.$events[name] = evt;\n\t\t\telse\n\t\t\t\tthis.$events[name] = undefined;\n\t\t}\n\t}\n\treturn this;\n};", "EE2P.removeAllListeners = function(name) {\n\tif (this.$events) {\n\t\tif (name === true)\n\t\t\tthis.$events = EMPTYOBJECT;\n\t\telse if (name)\n\t\t\tthis.$events[name] = undefined;\n\t\telse\n\t\t\tthis.$events = {};\n\t}\n\treturn this;\n};", "EventEmitter2.extend = function(obj) {\n\tobj.emit = EE2P.emit;\n\tobj.on = EE2P.on;\n\tobj.once = EE2P.once;\n\tobj.removeListener = EE2P.removeListener;\n\tobj.removeAllListeners = EE2P.removeAllListeners;\n};", "exports.EventEmitter2 = EventEmitter2;", "function Chunker(name, max) {\n\tthis.name = name;\n\tthis.max = max || 50;\n\tthis.index = 0;\n\tthis.filename = '{0}-'.format(name);\n\tthis.stack = [];\n\tthis.flushing = 0;\n\tthis.pages = 0;\n\tthis.count = 0;\n\tthis.percentage = 0;\n\tthis.autoremove = true;\n\tthis.compress = true;\n\tthis.filename = F.path.temp(this.filename);\n}", "const CHP = Chunker.prototype;", "CHP.append = CHP.write = function(obj) {\n\tvar self = this;", "\tself.stack.push(obj);", "\tvar tmp = self.stack.length;", "\tif (tmp >= self.max) {", "\t\tself.flushing++;\n\t\tself.pages++;\n\t\tself.count += tmp;", "\t\tvar index = (self.index++);", "\t\tif (self.compress) {\n\t\t\tZlib.deflate(Buffer.from(JSON.stringify(self.stack), ENCODING), function(err, buffer) {\n\t\t\t\tFs.writeFile(self.filename + index + '.chunker', buffer, () => self.flushing--);\n\t\t\t});\n\t\t} else\n\t\t\tFs.writeFile(self.filename + index + '.chunker', JSON.stringify(self.stack), () => self.flushing--);", "\t\tself.stack = [];\n\t}", "\treturn self;\n};", "CHP.end = function() {\n\tvar self = this;\n\tvar tmp = self.stack.length;\n\tif (tmp) {\n\t\tself.flushing++;\n\t\tself.pages++;\n\t\tself.count += tmp;", "\t\tvar index = (self.index++);", "\t\tif (self.compress) {\n\t\t\tZlib.deflate(Buffer.from(JSON.stringify(self.stack), ENCODING), function(err, buffer) {\n\t\t\t\tFs.writeFile(self.filename + index + '.chunker', buffer, () => self.flushing--);\n\t\t\t});\n\t\t} else\n\t\t\tFs.writeFile(self.filename + index + '.chunker', JSON.stringify(self.stack), () => self.flushing--);", "\t\tself.stack = [];\n\t}", "\treturn self;\n};", "CHP.each = function(onItem, onEnd, indexer) {", "\tvar self = this;", "\tif (indexer == null) {\n\t\tself.percentage = 0;\n\t\tindexer = 0;\n\t}", "\tif (indexer >= self.index)\n\t\treturn onEnd && onEnd();", "\tself.read(indexer++, function(err, items) {\n\t\tself.percentage = Math.ceil((indexer / self.pages) * 100);\n\t\tonItem(items, () => self.each(onItem, onEnd, indexer), indexer - 1);\n\t});", "\treturn self;\n};", "CHP.read = function(index, callback) {\n\tvar self = this;", "\tif (self.flushing) {\n\t\tself.flushing_timeout = setTimeout(() => self.read(index, callback), 300);\n\t\treturn;\n\t}", "\tvar filename = self.filename + index + '.chunker';", "\tFs.readFile(filename, function(err, data) {", "\t\tif (err) {\n\t\t\tcallback(null, EMPTYARRAY);\n\t\t\treturn;\n\t\t}", "\t\tif (self.compress) {\n\t\t\tZlib.inflate(data, function(err, data) {\n\t\t\t\tif (err) {\n\t\t\t\t\tcallback(null, EMPTYARRAY);\n\t\t\t\t} else {\n\t\t\t\t\tself.autoremove && Fs.unlink(filename, NOOP);\n\t\t\t\t\tcallback(null, data.toString('utf8').parseJSON(true));\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tself.autoremove && Fs.unlink(filename, NOOP);\n\t\t\tcallback(null, data.toString('utf8').parseJSON(true));\n\t\t}\n\t});", "\treturn self;\n};", "CHP.clear = function() {\n\tvar files = [];\n\tfor (var i = 0; i < this.index; i++)\n\t\tfiles.push(this.filename + i + '.chunker');\n\tfiles.wait((filename, next) => Fs.unlink(filename, next));\n\treturn this;\n};", "CHP.destroy = function() {\n\tthis.clear();\n\tthis.indexer = 0;\n\tthis.flushing = 0;\n\tclearTimeout(this.flushing_timeout);\n\tthis.stack = null;\n\treturn this;\n};", "exports.chunker = function(name, max) {\n\treturn new Chunker(name, max);\n};", "exports.Chunker = Chunker;", "exports.ObjectToArray = function(obj) {\n\tif (obj == null)\n\t\treturn EMPTYARRAY;\n\tvar keys = Object.keys(obj);\n\tvar output = [];\n\tfor (var i = 0, length = keys.length; i < length; i++)\n\t\toutput.push({ key: keys[i], value: obj[keys[i]]});\n\treturn output;\n};", "if (NODEVERSION > 699) {\n\texports.createBufferSize = (size) => Buffer.alloc(size || 0);\n\texports.createBuffer = (val, type) => Buffer.from(val || '', type);\n} else {\n\texports.createBufferSize = (size) => new Buffer(size || 0);\n\texports.createBuffer = (val, type) => new Buffer(val || '', type);\n}", "function Callback(count, callback) {\n\tthis.pending = count;\n\tthis.$callback = callback;\n}\nconst CP = Callback.prototype;", "CP.done = function(callback) {\n\tthis.$callback = callback;\n\treturn this;\n};", "CP.next = function() {\n\tvar self = this;\n\tself.pending--;\n\tif (!self.pending && self.$callback) {\n\t\tself.$callback();\n\t\tself.$callback = null;\n\t}\n\treturn self;\n};", "global.Callback = Callback;", "exports.Callback = function(count, callback) {\n\treturn new Callback(count, callback);\n};", "function Reader() {\n\tvar t = this;\n\tt.$add = function(builder) {\n\t\tif (t.reader)\n\t\t\tt.reader.add(builder);\n\t\telse\n\t\t\tt.reader = new framework_nosql.NoSQLReader(builder);\n\t};\n}\nconst RP = Reader.prototype;", "RP.done = function() {\n\tvar self = this;\n\tself.reader.done();\n\treturn self;\n};", "RP.reset = function() {\n\tvar self = this;\n\tself.reader.reset();\n\treturn self;\n};", "RP.push = function(data) {\n\tif (data == null)\n\t\tthis.reader.done();\n\telse\n\t\tthis.reader.compare(data instanceof Array ? data : [data]);\n\treturn this;\n};", "RP.find = function() {\n\tvar self = this;\n\tvar builder = new framework_nosql.DatabaseBuilder();\n\tsetImmediate(self.$add, builder);\n\treturn builder;\n};", "RP.count = function() {\n\tvar builder = this.find();\n\tbuilder.$options.readertype = 1;\n\treturn builder;\n};", "RP.scalar = function(type, field) {\n\treturn this.find().scalar(type, field);\n};", "exports.reader = function() {\n\treturn new Reader();\n};", "const BUFEMPTYJSON = Buffer.from('{}');", "global.WAIT = exports.wait;\n!global.F && require('./index');" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
PreciseBugs
{"buggy_code_end_loc": [3, 6627], "buggy_code_start_loc": [3, 6625], "filenames": ["changes.txt", "utils.js"], "fixing_code_end_loc": [5, 6627], "fixing_code_start_loc": [4, 6625], "message": "The package total.js before 3.4.8 are vulnerable to Remote Code Execution (RCE) via set.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:totaljs:total.js:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "903890AB-2DE4-4BA4-83F0-AC47EEF03AFB", "versionEndExcluding": "3.4.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The package total.js before 3.4.8 are vulnerable to Remote Code Execution (RCE) via set."}, {"lang": "es", "value": "El paquete total.js versiones anteriores a 3.4.8, es vulnerable a una ejecuci\u00f3n de c\u00f3digo remota (RCE) por medio de set"}], "evaluatorComment": null, "id": "CVE-2021-23344", "lastModified": "2021-03-05T19:26:24.673", "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"}, {"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": "report@snyk.io", "type": "Secondary"}]}, "published": "2021-03-04T17:15:13.153", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/totaljs/framework/commit/c812bbcab8981797d3a1b9993fc42dad3d246f04"}, {"source": "report@snyk.io", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-TOTALJS-1077069"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-94"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/totaljs/framework/commit/c812bbcab8981797d3a1b9993fc42dad3d246f04"}, "type": "CWE-94"}
243
Determine whether the {function_name} code is vulnerable or not.
[ "// Copyright 2012-2020 (c) Peter Širka <petersirka@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.", "/**\n * @module FrameworkUtils\n * @version 3.4.4\n */", "'use strict';", "const Dns = require('dns');\nconst Url = require('url');\nconst Qs = require('querystring');\nconst Http = require('http');\nconst Https = require('https');\nconst Path = require('path');\nconst Fs = require('fs');\nconst Events = require('events');\nconst Crypto = require('crypto');\nconst Zlib = require('zlib');\nconst Tls = require('tls');\nconst KeepAlive = new Http.Agent({ keepAlive: true, timeout: 60000 });", "const COMPRESS = { gzip: 1, deflate: 1 };\nconst CONCAT = [null, null];\nconst COMPARER = global.Intl ? global.Intl.Collator().compare : function(a, b) {\n\treturn a.removeDiacritics().localeCompare(b.removeDiacritics());\n};", "if (!global.framework_utils)\n\tglobal.framework_utils = exports;", "const Internal = require('./internal');\nvar regexpSTATIC = /\\.\\w{2,8}($|\\?)+/;\nconst regexpTRIM = /^[\\s]+|[\\s]+$/g;\nconst regexpDATE = /(\\d{1,2}\\.\\d{1,2}\\.\\d{4})|(\\d{4}-\\d{1,2}-\\d{1,2})|(\\d{1,2}:\\d{1,2}(:\\d{1,2})?)/g;\nconst regexpDATEFORMAT = /YYYY|yyyy|YY|yy|MMMM|MMM|MM|M|dddd|DDDD|DDD|ddd|DD|dd|D|d|HH|H|hh|h|mm|m|ss|s|a|ww|w/g;\nconst regexpSTRINGFORMAT = /\\{\\d+\\}/g;\nconst regexpPATH = /\\\\/g;\nconst regexpTags = /<\\/?[^>]+(>|$)/g;\nconst regexpDiacritics = /[^\\u0000-\\u007e]/g;\nconst regexpUA = /[a-z]+/gi;\nconst regexpXML = /\\w+=\".*?\"/g;\nconst regexpDECODE = /&#?[a-z0-9]+;/g;\nconst regexpPARAM = /\\{{2}[^}\\n]*\\}{2}/g;\nconst regexpARG = /\\{{1,2}[a-z0-9_.-\\s]+\\}{1,2}/gi;\nconst regexpINTEGER = /(^-|\\s-)?[0-9]+/g;\nconst regexpFLOAT = /(^-|\\s-)?[0-9.,]+/g;\nconst regexpALPHA = /^[A-Za-z0-9]+$/;\nconst regexpSEARCH = /[^a-zA-Zá-žÁ-Ž\\d\\s:]/g;\nconst regexpTERMINAL = /[\\w\\S]+/g;\nconst regexpCONFIGURE = /\\[\\w+\\]/g;\nconst regexpY = /y/g;\nconst regexpN = /\\n/g;\nconst regexpCHARS = /\\W|_/g;\nconst regexpCHINA = /[\\u3400-\\u9FBF]/;\nconst regexpLINES = /\\n|\\r|\\r\\n/;\nconst regexpBASE64 = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/;\nconst SOUNDEX = { a: '', e: '', i: '', o: '', u: '', b: 1, f: 1, p: 1, v: 1, c: 2, g: 2, j: 2, k: 2, q: 2, s: 2, x: 2, z: 2, d: 3, t: 3, l: 4, m: 5, n: 5, r: 6 };\nconst ENCODING = 'utf8';\nconst NEWLINE = '\\r\\n';\nconst isWindows = require('os').platform().substring(0, 3).toLowerCase() === 'win';\nconst DIACRITICSMAP = {};\nconst STREAM_READONLY = { flags: 'r' };\nconst STREAM_END = { end: false };\nconst ALPHA_INDEX = { '&lt': '<', '&gt': '>', '&quot': '\"', '&apos': '\\'', '&amp': '&', '&lt;': '<', '&gt;': '>', '&quot;': '\"', '&apos;': '\\'', '&amp;': '&' };\nconst NODEVERSION = parseFloat(process.version.toString().replace('v', '').replace(/\\./g, ''));\nconst STREAMPIPE = { end: false };\nconst CT = 'Content-Type';\nconst CRC32TABLE = '00000000,77073096,EE0E612C,990951BA,076DC419,706AF48F,E963A535,9E6495A3,0EDB8832,79DCB8A4,E0D5E91E,97D2D988,09B64C2B,7EB17CBD,E7B82D07,90BF1D91,1DB71064,6AB020F2,F3B97148,84BE41DE,1ADAD47D,6DDDE4EB,F4D4B551,83D385C7,136C9856,646BA8C0,FD62F97A,8A65C9EC,14015C4F,63066CD9,FA0F3D63,8D080DF5,3B6E20C8,4C69105E,D56041E4,A2677172,3C03E4D1,4B04D447,D20D85FD,A50AB56B,35B5A8FA,42B2986C,DBBBC9D6,ACBCF940,32D86CE3,45DF5C75,DCD60DCF,ABD13D59,26D930AC,51DE003A,C8D75180,BFD06116,21B4F4B5,56B3C423,CFBA9599,B8BDA50F,2802B89E,5F058808,C60CD9B2,B10BE924,2F6F7C87,58684C11,C1611DAB,B6662D3D,76DC4190,01DB7106,98D220BC,EFD5102A,71B18589,06B6B51F,9FBFE4A5,E8B8D433,7807C9A2,0F00F934,9609A88E,E10E9818,7F6A0DBB,086D3D2D,91646C97,E6635C01,6B6B51F4,1C6C6162,856530D8,F262004E,6C0695ED,1B01A57B,8208F4C1,F50FC457,65B0D9C6,12B7E950,8BBEB8EA,FCB9887C,62DD1DDF,15DA2D49,8CD37CF3,FBD44C65,4DB26158,3AB551CE,A3BC0074,D4BB30E2,4ADFA541,3DD895D7,A4D1C46D,D3D6F4FB,4369E96A,346ED9FC,AD678846,DA60B8D0,44042D73,33031DE5,AA0A4C5F,DD0D7CC9,5005713C,270241AA,BE0B1010,C90C2086,5768B525,206F85B3,B966D409,CE61E49F,5EDEF90E,29D9C998,B0D09822,C7D7A8B4,59B33D17,2EB40D81,B7BD5C3B,C0BA6CAD,EDB88320,9ABFB3B6,03B6E20C,74B1D29A,EAD54739,9DD277AF,04DB2615,73DC1683,E3630B12,94643B84,0D6D6A3E,7A6A5AA8,E40ECF0B,9309FF9D,0A00AE27,7D079EB1,F00F9344,8708A3D2,1E01F268,6906C2FE,F762575D,806567CB,196C3671,6E6B06E7,FED41B76,89D32BE0,10DA7A5A,67DD4ACC,F9B9DF6F,8EBEEFF9,17B7BE43,60B08ED5,D6D6A3E8,A1D1937E,38D8C2C4,4FDFF252,D1BB67F1,A6BC5767,3FB506DD,48B2364B,D80D2BDA,AF0A1B4C,36034AF6,41047A60,DF60EFC3,A867DF55,316E8EEF,4669BE79,CB61B38C,BC66831A,256FD2A0,5268E236,CC0C7795,BB0B4703,220216B9,5505262F,C5BA3BBE,B2BD0B28,2BB45A92,5CB36A04,C2D7FFA7,B5D0CF31,2CD99E8B,5BDEAE1D,9B64C2B0,EC63F226,756AA39C,026D930A,9C0906A9,EB0E363F,72076785,05005713,95BF4A82,E2B87A14,7BB12BAE,0CB61B38,92D28E9B,E5D5BE0D,7CDCEFB7,0BDBDF21,86D3D2D4,F1D4E242,68DDB3F8,1FDA836E,81BE16CD,F6B9265B,6FB077E1,18B74777,88085AE6,FF0F6A70,66063BCA,11010B5C,8F659EFF,F862AE69,616BFFD3,166CCF45,A00AE278,D70DD2EE,4E048354,3903B3C2,A7672661,D06016F7,4969474D,3E6E77DB,AED16A4A,D9D65ADC,40DF0B66,37D83BF0,A9BCAE53,DEBB9EC5,47B2CF7F,30B5FFE9,BDBDF21C,CABAC28A,53B39330,24B4A3A6,BAD03605,CDD70693,54DE5729,23D967BF,B3667A2E,C4614AB8,5D681B02,2A6F2B94,B40BBE37,C30C8EA1,5A05DF1B,2D02EF8D'.split(',').map(s => parseInt(s, 16));\nconst REGISARR = /\\[\\d+\\]|\\[\\]$/;\nconst REGREPLACEARR = /\\[\\]/g;\nconst PROXYBLACKLIST = { 'localhost': 1, '127.0.0.1': 1, '0.0.0.0': 1 };\nconst PROXYOPTIONS = { headers: {}, method: 'CONNECT', agent: false };\nconst PROXYTLS = { headers: {}};\nconst PROXYOPTIONSHTTP = {};\nconst REG_ROOT = /@\\{#\\}(\\/)?/g;\nconst REG_NOREMAP = /@\\{noremap\\}(\\n)?/g;\nconst REG_REMAP = /href=\".*?\"|src=\".*?\"/gi;\nconst REG_AJAX = /('|\")+(!)?(GET|POST|PUT|DELETE|PATCH)\\s(\\(.*?\\)\\s)?\\//g;\nconst REG_URLEXT = /(https|http|wss|ws|file):\\/\\/|\\/\\/[a-z0-9]|[a-z]:/i;\nconst REG_TEXTAPPLICATION = /text|application/i;\nconst REG_TIME = /am|pm/i;\nconst REG_XMLKEY = /\\[|\\]|:|\\.|_/g;", "exports.MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\nexports.DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];", "var DIACRITICS=[{b:' ',c:'\\u00a0'},{b:'0',c:'\\u07c0'},{b:'A',c:'\\u24b6\\uff21\\u00c0\\u00c1\\u00c2\\u1ea6\\u1ea4\\u1eaa\\u1ea8\\u00c3\\u0100\\u0102\\u1eb0\\u1eae\\u1eb4\\u1eb2\\u0226\\u01e0\\u00c4\\u01de\\u1ea2\\u00c5\\u01fa\\u01cd\\u0200\\u0202\\u1ea0\\u1eac\\u1eb6\\u1e00\\u0104\\u023a\\u2c6f'},{b:'AA',c:'\\ua732'},{b:'AE',c:'\\u00c6\\u01fc\\u01e2'},{b:'AO',c:'\\ua734'},{b:'AU',c:'\\ua736'},{b:'AV',c:'\\ua738\\ua73a'},{b:'AY',c:'\\ua73c'},{b:'B',c:'\\u24b7\\uff22\\u1e02\\u1e04\\u1e06\\u0243\\u0181'},{b:'C',c:'\\u24b8\\uff23\\ua73e\\u1e08\\u0106C\\u0108\\u010a\\u010c\\u00c7\\u0187\\u023b'},{b:'D',c:'\\u24b9\\uff24\\u1e0a\\u010e\\u1e0c\\u1e10\\u1e12\\u1e0e\\u0110\\u018a\\u0189\\u1d05\\ua779'},{b:'Dh',c:'\\u00d0'},{b:'DZ',c:'\\u01f1\\u01c4'},{b:'Dz',c:'\\u01f2\\u01c5'},{b:'E',c:'\\u025b\\u24ba\\uff25\\u00c8\\u00c9\\u00ca\\u1ec0\\u1ebe\\u1ec4\\u1ec2\\u1ebc\\u0112\\u1e14\\u1e16\\u0114\\u0116\\u00cb\\u1eba\\u011a\\u0204\\u0206\\u1eb8\\u1ec6\\u0228\\u1e1c\\u0118\\u1e18\\u1e1a\\u0190\\u018e\\u1d07'},{b:'F',c:'\\ua77c\\u24bb\\uff26\\u1e1e\\u0191\\ua77b'}, {b:'G',c:'\\u24bc\\uff27\\u01f4\\u011c\\u1e20\\u011e\\u0120\\u01e6\\u0122\\u01e4\\u0193\\ua7a0\\ua77d\\ua77e\\u0262'},{b:'H',c:'\\u24bd\\uff28\\u0124\\u1e22\\u1e26\\u021e\\u1e24\\u1e28\\u1e2a\\u0126\\u2c67\\u2c75\\ua78d'},{b:'I',c:'\\u24be\\uff29\\u00cc\\u00cd\\u00ce\\u0128\\u012a\\u012c\\u0130\\u00cf\\u1e2e\\u1ec8\\u01cf\\u0208\\u020a\\u1eca\\u012e\\u1e2c\\u0197'},{b:'J',c:'\\u24bf\\uff2a\\u0134\\u0248\\u0237'},{b:'K',c:'\\u24c0\\uff2b\\u1e30\\u01e8\\u1e32\\u0136\\u1e34\\u0198\\u2c69\\ua740\\ua742\\ua744\\ua7a2'},{b:'L',c:'\\u24c1\\uff2c\\u013f\\u0139\\u013d\\u1e36\\u1e38\\u013b\\u1e3c\\u1e3a\\u0141\\u023d\\u2c62\\u2c60\\ua748\\ua746\\ua780'}, {b:'LJ',c:'\\u01c7'},{b:'Lj',c:'\\u01c8'},{b:'M',c:'\\u24c2\\uff2d\\u1e3e\\u1e40\\u1e42\\u2c6e\\u019c\\u03fb'},{b:'N',c:'\\ua7a4\\u0220\\u24c3\\uff2e\\u01f8\\u0143\\u00d1\\u1e44\\u0147\\u1e46\\u0145\\u1e4a\\u1e48\\u019d\\ua790\\u1d0e'},{b:'NJ',c:'\\u01ca'},{b:'Nj',c:'\\u01cb'},{b:'O',c:'\\u24c4\\uff2f\\u00d2\\u00d3\\u00d4\\u1ed2\\u1ed0\\u1ed6\\u1ed4\\u00d5\\u1e4c\\u022c\\u1e4e\\u014c\\u1e50\\u1e52\\u014e\\u022e\\u0230\\u00d6\\u022a\\u1ece\\u0150\\u01d1\\u020c\\u020e\\u01a0\\u1edc\\u1eda\\u1ee0\\u1ede\\u1ee2\\u1ecc\\u1ed8\\u01ea\\u01ec\\u00d8\\u01fe\\u0186\\u019f\\ua74a\\ua74c'}, {b:'OE',c:'\\u0152'},{b:'OI',c:'\\u01a2'},{b:'OO',c:'\\ua74e'},{b:'OU',c:'\\u0222'},{b:'P',c:'\\u24c5\\uff30\\u1e54\\u1e56\\u01a4\\u2c63\\ua750\\ua752\\ua754'},{b:'Q',c:'\\u24c6\\uff31\\ua756\\ua758\\u024a'},{b:'R',c:'\\u24c7\\uff32\\u0154\\u1e58\\u0158\\u0210\\u0212\\u1e5a\\u1e5c\\u0156\\u1e5e\\u024c\\u2c64\\ua75a\\ua7a6\\ua782'},{b:'S',c:'\\u24c8\\uff33\\u1e9e\\u015a\\u1e64\\u015c\\u1e60\\u0160\\u1e66\\u1e62\\u1e68\\u0218\\u015e\\u2c7e\\ua7a8\\ua784'},{b:'T',c:'\\u24c9\\uff34\\u1e6a\\u0164\\u1e6c\\u021a\\u0162\\u1e70\\u1e6e\\u0166\\u01ac\\u01ae\\u023e\\ua786'}, {b:'Th',c:'\\u00de'},{b:'TZ',c:'\\ua728'},{b:'U',c:'\\u24ca\\uff35\\u00d9\\u00da\\u00db\\u0168\\u1e78\\u016a\\u1e7a\\u016c\\u00dc\\u01db\\u01d7\\u01d5\\u01d9\\u1ee6\\u016e\\u0170\\u01d3\\u0214\\u0216\\u01af\\u1eea\\u1ee8\\u1eee\\u1eec\\u1ef0\\u1ee4\\u1e72\\u0172\\u1e76\\u1e74\\u0244'},{b:'V',c:'\\u24cb\\uff36\\u1e7c\\u1e7e\\u01b2\\ua75e\\u0245'},{b:'VY',c:'\\ua760'},{b:'W',c:'\\u24cc\\uff37\\u1e80\\u1e82\\u0174\\u1e86\\u1e84\\u1e88\\u2c72'},{b:'X',c:'\\u24cd\\uff38\\u1e8a\\u1e8c'},{b:'Y',c:'\\u24ce\\uff39\\u1ef2\\u00dd\\u0176\\u1ef8\\u0232\\u1e8e\\u0178\\u1ef6\\u1ef4\\u01b3\\u024e\\u1efe'}, {b:'Z',c:'\\u24cf\\uff3a\\u0179\\u1e90\\u017b\\u017d\\u1e92\\u1e94\\u01b5\\u0224\\u2c7f\\u2c6b\\ua762'},{b:'a',c:'\\u24d0\\uff41\\u1e9a\\u00e0\\u00e1\\u00e2\\u1ea7\\u1ea5\\u1eab\\u1ea9\\u00e3\\u0101\\u0103\\u1eb1\\u1eaf\\u1eb5\\u1eb3\\u0227\\u01e1\\u00e4\\u01df\\u1ea3\\u00e5\\u01fb\\u01ce\\u0201\\u0203\\u1ea1\\u1ead\\u1eb7\\u1e01\\u0105\\u2c65\\u0250\\u0251'},{b:'aa',c:'\\ua733'},{b:'ae',c:'\\u00e6\\u01fd\\u01e3'},{b:'ao',c:'\\ua735'},{b:'au',c:'\\ua737'},{b:'av',c:'\\ua739\\ua73b'},{b:'ay',c:'\\ua73d'}, {b:'b',c:'\\u24d1\\uff42\\u1e03\\u1e05\\u1e07\\u0180\\u0183\\u0253\\u0182'},{b:'c',c:'\\uff43\\u24d2\\u0107\\u0109\\u010b\\u010d\\u00e7\\u1e09\\u0188\\u023c\\ua73f\\u2184'},{b:'d',c:'\\u24d3\\uff44\\u1e0b\\u010f\\u1e0d\\u1e11\\u1e13\\u1e0f\\u0111\\u018c\\u0256\\u0257\\u018b\\u13e7\\u0501\\ua7aa'},{b:'dh',c:'\\u00f0'},{b:'dz',c:'\\u01f3\\u01c6'},{b:'e',c:'\\u24d4\\uff45\\u00e8\\u00e9\\u00ea\\u1ec1\\u1ebf\\u1ec5\\u1ec3\\u1ebd\\u0113\\u1e15\\u1e17\\u0115\\u0117\\u00eb\\u1ebb\\u011b\\u0205\\u0207\\u1eb9\\u1ec7\\u0229\\u1e1d\\u0119\\u1e19\\u1e1b\\u0247\\u01dd'}, {b:'f',c:'\\u24d5\\uff46\\u1e1f\\u0192'},{b:'ff',c:'\\ufb00'},{b:'fi',c:'\\ufb01'},{b:'fl',c:'\\ufb02'},{b:'ffi',c:'\\ufb03'},{b:'ffl',c:'\\ufb04'},{b:'g',c:'\\u24d6\\uff47\\u01f5\\u011d\\u1e21\\u011f\\u0121\\u01e7\\u0123\\u01e5\\u0260\\ua7a1\\ua77f\\u1d79'},{b:'h',c:'\\u24d7\\uff48\\u0125\\u1e23\\u1e27\\u021f\\u1e25\\u1e29\\u1e2b\\u1e96\\u0127\\u2c68\\u2c76\\u0265'},{b:'hv',c:'\\u0195'},{b:'i',c:'\\u24d8\\uff49\\u00ec\\u00ed\\u00ee\\u0129\\u012b\\u012d\\u00ef\\u1e2f\\u1ec9\\u01d0\\u0209\\u020b\\u1ecb\\u012f\\u1e2d\\u0268\\u0131'}, {b:'j',c:'\\u24d9\\uff4a\\u0135\\u01f0\\u0249'},{b:'k',c:'\\u24da\\uff4b\\u1e31\\u01e9\\u1e33\\u0137\\u1e35\\u0199\\u2c6a\\ua741\\ua743\\ua745\\ua7a3'},{b:'l',c:'\\u24db\\uff4c\\u0140\\u013a\\u013e\\u1e37\\u1e39\\u013c\\u1e3d\\u1e3b\\u017f\\u0142\\u019a\\u026b\\u2c61\\ua749\\ua781\\ua747\\u026d'},{b:'lj',c:'\\u01c9'},{b:'m',c:'\\u24dc\\uff4d\\u1e3f\\u1e41\\u1e43\\u0271\\u026f'},{b:'n',c:'\\u24dd\\uff4e\\u01f9\\u0144\\u00f1\\u1e45\\u0148\\u1e47\\u0146\\u1e4b\\u1e49\\u019e\\u0272\\u0149\\ua791\\ua7a5\\u043b\\u0509'},{b:'nj', c:'\\u01cc'},{b:'o',c:'\\u24de\\uff4f\\u00f2\\u00f3\\u00f4\\u1ed3\\u1ed1\\u1ed7\\u1ed5\\u00f5\\u1e4d\\u022d\\u1e4f\\u014d\\u1e51\\u1e53\\u014f\\u022f\\u0231\\u00f6\\u022b\\u1ecf\\u0151\\u01d2\\u020d\\u020f\\u01a1\\u1edd\\u1edb\\u1ee1\\u1edf\\u1ee3\\u1ecd\\u1ed9\\u01eb\\u01ed\\u00f8\\u01ff\\ua74b\\ua74d\\u0275\\u0254\\u1d11'},{b:'oe',c:'\\u0153'},{b:'oi',c:'\\u01a3'},{b:'oo',c:'\\ua74f'},{b:'ou',c:'\\u0223'},{b:'p',c:'\\u24df\\uff50\\u1e55\\u1e57\\u01a5\\u1d7d\\ua751\\ua753\\ua755\\u03c1'},{b:'q',c:'\\u24e0\\uff51\\u024b\\ua757\\ua759'}, {b:'r',c:'\\u24e1\\uff52\\u0155\\u1e59\\u0159\\u0211\\u0213\\u1e5b\\u1e5d\\u0157\\u1e5f\\u024d\\u027d\\ua75b\\ua7a7\\ua783'},{b:'s',c:'\\u24e2\\uff53\\u015b\\u1e65\\u015d\\u1e61\\u0161\\u1e67\\u1e63\\u1e69\\u0219\\u015f\\u023f\\ua7a9\\ua785\\u1e9b\\u0282'},{b:'ss',c:'\\u00df'},{b:'t',c:'\\u24e3\\uff54\\u1e6b\\u1e97\\u0165\\u1e6d\\u021b\\u0163\\u1e71\\u1e6f\\u0167\\u01ad\\u0288\\u2c66\\ua787'},{b:'th',c:'\\u00fe'},{b:'tz',c:'\\ua729'},{b:'u',c:'\\u24e4\\uff55\\u00f9\\u00fa\\u00fb\\u0169\\u1e79\\u016b\\u1e7b\\u016d\\u00fc\\u01dc\\u01d8\\u01d6\\u01da\\u1ee7\\u016f\\u0171\\u01d4\\u0215\\u0217\\u01b0\\u1eeb\\u1ee9\\u1eef\\u1eed\\u1ef1\\u1ee5\\u1e73\\u0173\\u1e77\\u1e75\\u0289'}, {b:'v',c:'\\u24e5\\uff56\\u1e7d\\u1e7f\\u028b\\ua75f\\u028c'},{b:'vy',c:'\\ua761'},{b:'w',c:'\\u24e6\\uff57\\u1e81\\u1e83\\u0175\\u1e87\\u1e85\\u1e98\\u1e89\\u2c73'},{b:'x',c:'\\u24e7\\uff58\\u1e8b\\u1e8d'},{b:'y',c:'\\u24e8\\uff59\\u1ef3\\u00fd\\u0177\\u1ef9\\u0233\\u1e8f\\u00ff\\u1ef7\\u1e99\\u1ef5\\u01b4\\u024f\\u1eff'},{b:'z',c:'\\u24e9\\uff5a\\u017a\\u1e91\\u017c\\u017e\\u1e93\\u1e95\\u01b6\\u0225\\u0240\\u2c6c\\ua763'}];", "for (var i=0; i <DIACRITICS.length; i+=1)\n\tfor (var chars=DIACRITICS[i].c,j=0;j<chars.length;j+=1)\n\t\tDIACRITICSMAP[chars[j]]=DIACRITICS[i].b;", "const DP = Date.prototype;\nconst SP = String.prototype;\nconst NP = Number.prototype;", "DIACRITICS = null;", "var CONTENTTYPES = {\n\taac: 'audio/aac',\n\tai: 'application/postscript',\n\tappcache: 'text/cache-manifest',\n\tavi: 'video/avi',\n\tbin: 'application/octet-stream',\n\tbmp: 'image/bmp',\n\tcoffee: 'text/coffeescript',\n\tcss: 'text/css',\n\tcsv: 'text/csv',\n\tdoc: 'application/msword',\n\tdocx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n\tdtd: 'application/xml-dtd',\n\teps: 'application/postscript',\n\texe: 'application/octet-stream',\n\tflac: 'audio/x-flac',\n\tgeojson: 'application/json',\n\tgif: 'image/gif',\n\tgzip: 'application/x-gzip',\n\theic: 'image/heic',\n\theif: 'image/heif',\n\thtm: 'text/html',\n\thtml: 'text/html',\n\tico: 'image/x-icon',\n\tics: 'text/calendar',\n\tifb: 'text/calendar',\n\tjpe: 'image/jpeg',\n\tjpeg: 'image/jpeg',\n\tjpg: 'image/jpeg',\n\tjs: 'text/javascript',\n\tjson: 'application/json',\n\tjsx: 'text/jsx',\n\tless: 'text/css',\n\tm4a: 'audio/mp4a-latm',\n\tm4v: 'video/x-m4v',\n\tmanifest: 'text/cache-manifest',\n\tmd: 'text/x-markdown',\n\tmid: 'audio/midi',\n\tmidi: 'audio/midi',\n\tmjs: 'text/javascript',\n\tmov: 'video/quicktime',\n\tmp3: 'audio/mpeg',\n\tmp4: 'video/mp4',\n\tmpe: 'video/mpeg',\n\tmpeg: 'video/mpeg',\n\tmpg: 'video/mpeg',\n\tmpga: 'audio/mpeg',\n\tmtl: 'text/plain',\n\tmv4: 'video/mv4',\n\tobj: 'text/plain',\n\togg: 'application/ogg',\n\togv: 'video/ogg',\n\tpackage: 'text/plain',\n\tpdf: 'application/pdf',\n\tpng: 'image/png',\n\tppt: 'application/vnd.ms-powerpoint',\n\tpptx: 'application/vnd.ms-powerpoint',\n\tps: 'application/postscript',\n\trar: 'application/x-rar-compressed',\n\trtf: 'text/rtf',\n\tsass: 'text/css',\n\tscss: 'text/css',\n\tsh: 'application/x-sh',\n\tstl: 'application/sla',\n\tsvg: 'image/svg+xml',\n\tswf: 'application/x-shockwave-flash',\n\ttar: 'application/x-tar',\n\ttif: 'image/tiff',\n\ttiff: 'image/tiff',\n\ttxt: 'text/plain',\n\tsql: 'text/plain',\n\twav: 'audio/x-wav',\n\twebm: 'video/webm',\n\twebp: 'image/webp',\n\twoff: 'application/font-woff',\n\twoff2: 'application/font-woff2',\n\txht: 'application/xhtml+xml',\n\txhtml: 'application/xhtml+xml',\n\txls: 'application/vnd.ms-excel',\n\txlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n\txml: 'application/xml',\n\txpm: 'image/x-xpixmap',\n\txsl: 'application/xml',\n\txslt: 'application/xslt+xml',\n\tzip: 'application/zip'\n};", "var dnscache = {};\nvar datetimeformat = {};\nconst hasOwnProperty = Object.prototype.hasOwnProperty;", "global.DIFFARR = exports.diffarr = function(prop, db, form) {", "\tvar an = [];\n\tvar au = [];\n\tvar ar = [];\n\tvar is, oa, ob;", "\tfor (var i = 0; i < db.length; i++) {\n\t\toa = db[i];\n\t\tis = false;\n\t\tfor (var j = 0; j < form.length; j++) {\n\t\t\tob = form[j];\n\t\t\tif (oa[prop] == ob[prop]) {\n\t\t\t\tau.push({ db: oa, form: ob });\n\t\t\t\tis = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!is)\n\t\t\tar.push(oa[prop]);\n\t}", "\tfor (var i = 0; i < form.length; i++) {\n\t\tob = form[i];\n\t\tis = false;\n\t\tfor (var j = 0; j < db.length; j++) {\n\t\t\toa = db[j];\n\t\t\tif (ob[prop] == oa[prop]) {\n\t\t\t\tis = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!is)\n\t\t\tan.push(ob);\n\t}", "\tvar obj = {};\n\tobj.add = an;\n\tobj.upd = au;\n\tobj.rem = ar;\n\treturn obj;\n};", "/**\n * Checks if is object empty\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isEmpty = function(obj) {", "\tif (!obj || obj instanceof Array)\n\t\treturn true;", "\tfor (var key in obj) {\n\t\tif (hasOwnProperty.call(obj, key))\n\t\t\treturn false;\n\t}", "\treturn true;\n};", "/**\n * Compare objects\n * @param {Object} obj1\n * @param {Object} obj2\n * @return {Boolean}\n */\nexports.isEqual = function(obj1, obj2, properties) {", "\tvar keys = properties ? properties : Object.keys(obj1);", "\tfor (var i = 0, length = keys.length; i < length; i++) {\n\t\tvar key = keys[i];\n\t\tvar a = obj1[key];\n\t\tvar b = obj2[key];\n\t\tvar ta = typeof(a);\n\t\tvar tb = typeof(b);", "\t\tif (ta !== tb)\n\t\t\treturn false;", "\t\tif (a === b)\n\t\t\tcontinue;", "\t\tif (a instanceof Date && b instanceof Date) {\n\t\t\tif (a.getTime() === b.getTime())\n\t\t\t\tcontinue;\n\t\t\treturn false;\n\t\t} else if (a instanceof Array && b instanceof Array) {\n\t\t\tif (JSON.stringify(a) === JSON.stringify(b))\n\t\t\t\tcontinue;\n\t\t\treturn false;\n\t\t}", "\t\tif (ta === 'object' && tb === 'object') {\n\t\t\tif (exports.isEqual(a, b))\n\t\t\t\tcontinue;\n\t\t}", "\t\treturn false;\n\t}", "\treturn true;\n};", "/**\n * Function checks a valid function and waits for it positive result\n * @param {Function} fnValid\n * @param {Function(err, success)} fnCallback\n * @param {Number} timeout Timeout, optional (default: 5000)\n * @param {Number} interval Refresh interval, optional (default: 500)\n */\nexports.wait = function(fnValid, fnCallback, timeout, interval) {", "\tif (fnValid() === true)\n\t\treturn fnCallback(null, true);", "\tvar id_timeout = null;\n\tvar id_interval = setInterval(function() {", "\t\tif (fnValid() === true) {\n\t\t\tclearInterval(id_interval);\n\t\t\tclearTimeout(id_timeout);\n\t\t\tfnCallback && fnCallback(null, true);\n\t\t}", "\t}, interval || 500);", "\tid_timeout = setTimeout(function() {\n\t\tclearInterval(id_interval);\n\t\tfnCallback && fnCallback(new Error('Timeout.'), false);\n\t}, timeout || 5000);\n};", "exports.$$wait = function(fnValid, timeout, interval) {\n\treturn function(callback) {\n\t\texports.wait(fnValid, callback, timeout, interval);\n\t};\n};", "/**\n * Resolves an IP from the URL address\n * @param {String} url\n * @param {Function(err, uri)} callback\n */\nexports.resolve = function(url, callback, param) {", "\tvar uri = Url.parse(url);", "\n\tif (!callback)\n\t\treturn dnscache[uri.host];", "\tif (dnscache[uri.host]) {\n\t\turi.host = dnscache[uri.host];\n\t\tcallback(null, uri, param);\n\t\treturn;\n\t}", "\tDns.resolve4(uri.hostname, function(e, addresses) {\n\t\tif (e)\n\t\t\tsetImmediate(dnsresolve_callback, uri, callback, param);\n\t\telse {\n\t\t\tdnscache[uri.host] = addresses[0];\n\t\t\turi.host = addresses[0];\n\t\t\tcallback(null, uri, param);\n\t\t}\n\t});\n};", "function dnsresolve_callback(uri, callback, param) {\n\tDns.resolve4(uri.hostname, function(e, addresses) {\n\t\tif (addresses && addresses.length) {\n\t\t\tdnscache[uri.host] = addresses[0];\n\t\t\turi.host = addresses[0];\n\t\t}\n\t\tcallback(e, uri, param);\n\t});\n}", "exports.$$resolve = function(url) {\n\treturn function(callback) {\n\t\treturn exports.resolve(url, callback);\n\t};\n};", "/**\n * Clears DNS cache\n */\nexports.clearDNS = function() {\n\tOBSOLETE('U.clearDNS()', 'Use CMD(\\'clear_dnscache\\')');\n\tCMD('clear_dnscache');\n};", "setImmediate(function() {\n\tif (global.F) {\n\t\tF.install('command', 'clear_dnscache', function() {\n\t\t\tdnscache = {};\n\t\t});\n\t}\n});", "\nexports.keywords = function(content, forSearch, alternative, max_count, max_length, min_length) {", "\tif (forSearch === undefined)\n\t\tforSearch = true;", "\tmin_length = min_length || 2;\n\tmax_count = max_count || 200;\n\tmax_length = max_length || 20;", "\tvar words = [];\n\tvar isSoundex = alternative === 'soundex';", "\tif (content instanceof Array) {\n\t\tfor (var i = 0, length = content.length; i < length; i++) {\n\t\t\tif (!content[i])\n\t\t\t\tcontinue;\n\t\t\tvar tmp = (forSearch ? content[i].removeDiacritics().toLowerCase().replace(regexpY, 'i') : content[i].toLowerCase()).replace(regexpN, ' ').split(' ');\n\t\t\tif (!tmp || !tmp.length)\n\t\t\t\tcontinue;\n\t\t\tfor (var j = 0, jl = tmp.length; j < jl; j++)\n\t\t\t\twords.push(tmp[j]);\n\t\t}\n\t} else\n\t\twords = (forSearch ? content.removeDiacritics().toLowerCase().replace(regexpY, 'i') : content.toLowerCase()).replace(regexpN, ' ').split(' ');", "\tif (!words)\n\t\twords = [];", "\tvar dic = {};\n\tvar counter = 0;", "\tfor (var i = 0, length = words.length; i < length; i++) {", "\t\tvar word = words[i].trim().replace(regexpCHARS, keywordscleaner);", "\t\tif (regexpCHINA.test(word)) {", "\t\t\tvar tmpw = word.split('', max_count);", "\t\t\tfor (var j = 0; j < tmpw.length; j++) {\n\t\t\t\tword = tmpw[j];\n\t\t\t\tif (dic[word])\n\t\t\t\t\tdic[word]++;\n\t\t\t\telse\n\t\t\t\t\tdic[word] = 1;\n\t\t\t\tcounter++;\n\t\t\t}", "\t\t\tif (counter >= max_count)\n\t\t\t\tbreak;", "\t\t\tcontinue;\n\t\t}", "\t\tif (word.length < min_length)\n\t\t\tcontinue;", "\t\tif (counter >= max_count)\n\t\t\tbreak;", "\t\t// Gets 80% length of word\n\t\tif (alternative) {\n\t\t\tif (isSoundex)\n\t\t\t\tword = word.soundex();\n\t\t\telse {\n\t\t\t\tvar size = (word.length / 100) * 80;\n\t\t\t\tif (size > min_length + 1)\n\t\t\t\t\tword = word.substring(0, size);\n\t\t\t}\n\t\t}", "\t\tif (word.length < min_length || word.length > max_length)\n\t\t\tcontinue;", "\t\tif (dic[word])\n\t\t\tdic[word]++;\n\t\telse\n\t\t\tdic[word] = 1;", "\t\tcounter++;\n\t}", "\tvar keys = Object.keys(dic);", "\tkeys.sort(function(a, b) {\n\t\tvar countA = dic[a];\n\t\tvar countB = dic[b];\n\t\treturn countA > countB ? -1 : countA < countB ? 1 : 0;\n\t});", "\treturn keys;\n};", "function keywordscleaner(c) {\n\treturn c.charCodeAt(0) < 200 ? '' : c;\n}", "function parseProxy(p) {\n\tvar key = 'proxy_' + p;\n\tif (F.temporary.other[key])\n\t\treturn F.temporary.other[key];", "\tif (p.indexOf('://') === -1)\n\t\tp = 'http://' + p;", "\tvar obj = Url.parse(p);", "\tif (obj.auth)\n\t\tobj._auth = 'Basic ' + Buffer.from(obj.auth).toString('base64');", "\tobj.port = +obj.port;\n\treturn F.temporary.other[key] = obj;\n}", "/**\n * Create a request to a specific URL\n * @param {String} url URL address.\n * @param {String Array} flags Request flags.\n * @param {String or Object} data Request data (optional).\n * @param {Function(error, content, statusCode, headers)} callback Callback.\n * @param {Object} headers Custom cookies (optional, default: null).\n * @param {Object} headers Custom headers (optional, default: null).\n * @param {String} encoding Encoding (optional, default: UTF8)\n * @param {Number} timeout Request timeout.\n * return {Boolean}\n */", "const NOBODY = { GET: 1, OPTIONS: 1, HEAD: 1 };", "global.REQUEST = exports.request = function(url, flags, data, callback, cookies, headers, encoding, timeout, files, param) {", "\t// No data (data is optional argument)\n\tif (typeof(data) === 'function') {\n\t\tencoding = headers;\n\t\theaders = cookies;\n\t\tcookies = callback;\n\t\tcallback = data;\n\t\tdata = '';\n\t} else if (!data)\n\t\tdata = '';", "\tif (callback === NOOP)\n\t\tcallback = null;", "\tif (global.F)\n\t\tglobal.F.stats.performance.external++;", "\tvar options = { length: 0, timeout: timeout || CONF.default_restbuilder_timeout, evt: new EventEmitter2(), encoding: typeof(encoding) !== 'string' ? ENCODING : encoding, callback: callback, post: false, redirect: 0 };\n\tvar method;\n\tvar type = 0;\n\tvar isCookies = false;\n\tvar def;\n\tvar proxy;", "\tif (headers) {\n\t\theaders = exports.extend({}, headers);\n\t\tdef = headers[CT];\n\t} else\n\t\theaders = {};", "\tif (flags instanceof Array) {\n\t\tfor (var i = 0, length = flags.length; i < length; i++) {", "\t\t\t// timeout\n\t\t\tif (flags[i] > 0) {\n\t\t\t\toptions.timeout = flags[i];\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (flags[i][0] === '<') {\n\t\t\t\toptions.max = flags[i].substring(1).trim().parseInt() * 1024; // kB\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (flags[i][0] === 'p' && flags[i][4] === 'y') {\n\t\t\t\tproxy = parseProxy(flags[i].substring(6));\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tswitch (flags[i].toLowerCase()) {\n\t\t\t\tcase 'utf8':\n\t\t\t\tcase 'ascii':\n\t\t\t\tcase 'base64':\n\t\t\t\tcase 'binary':\n\t\t\t\tcase 'hex':\n\t\t\t\t\toptions.encoding = flags[i];\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'xhr':\n\t\t\t\t\theaders['X-Requested-With'] = 'XMLHttpRequest';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'plain':\n\t\t\t\t\tif (!def)\n\t\t\t\t\t\theaders[CT] = 'text/plain';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'html':\n\t\t\t\t\tif (!def)\n\t\t\t\t\t\theaders[CT] = 'text/html';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'raw':\n\t\t\t\t\ttype = 3;\n\t\t\t\t\tif (!def)\n\t\t\t\t\t\theaders[CT] = 'application/octet-stream';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'json':\n\t\t\t\t\tif (!def)\n\t\t\t\t\t\theaders[CT] = 'application/json';\n\t\t\t\t\t!method && (method = 'POST');\n\t\t\t\t\ttype = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'xml':\n\t\t\t\t\tif (!def)\n\t\t\t\t\t\theaders[CT] = 'text/xml';\n\t\t\t\t\t!method && (method = 'POST');\n\t\t\t\t\ttype = 2;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'get':\n\t\t\t\tcase 'options':\n\t\t\t\tcase 'head':\n\t\t\t\t\tmethod = flags[i].charCodeAt(0) > 96 ? flags[i].toUpperCase() : flags[i];\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'noredirect':\n\t\t\t\t\toptions.noredirect = true;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'upload':\n\t\t\t\t\ttype = 4;\n\t\t\t\t\toptions.upload = true;\n\t\t\t\t\toptions.files = files || EMPTYARRAY;\n\t\t\t\t\toptions.boundary = '----totaljs' + Math.random().toString(16).substring(2);\n\t\t\t\t\theaders[CT] = 'multipart/form-data; boundary=' + options.boundary;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'post':\n\t\t\t\tcase 'put':\n\t\t\t\tcase 'delete':\n\t\t\t\tcase 'patch':\n\t\t\t\t\tmethod = flags[i].toUpperCase();\n\t\t\t\t\t!def && !headers[CT] && (headers[CT] = 'application/x-www-form-urlencoded');\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'dnscache':\n\t\t\t\t\toptions.resolve = true;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'keepalive':\n\t\t\t\t\toptions.keepalive = true;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'cookies':\n\t\t\t\t\tisCookies = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:", "\t\t\t\t\t// Fallback for methods (e.g. CalDAV)\n\t\t\t\t\tif (!method)\n\t\t\t\t\t\tmethod = flags[i].charCodeAt(0) > 96 ? flags[i].toUpperCase() : flags[i];", "\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "\tif (method)\n\t\toptions.post = !NOBODY[method];\n\telse\n\t\tmethod = 'GET';", "\tif (type < 3) {", "\t\tif (typeof(data) !== 'string')\n\t\t\tdata = type === 1 ? JSON.stringify(data) : Qs.stringify(data);\n\t\telse if (data[0] === '?')\n\t\t\tdata = data.substring(1);", "\t\tif (!options.post) {\n\t\t\tif (data.length) {\n\t\t\t\tif (url.indexOf('?') === -1)\n\t\t\t\t\turl += '?' + data;\n\t\t\t\telse\n\t\t\t\t\turl += '&' + data;\n\t\t\t}\n\t\t\tdata = '';\n\t\t}", "\t\t// \"null\" or \"empty string\" is valid JSON value too\n\t\tif (type === 1 && (data === EMPTYOBJECT || data === undefined) && options.post)\n\t\t\tdata = BUFEMPTYJSON;\n\t}", "\tif (data && type !== 4) {\n\t\toptions.data = data instanceof Buffer ? data : Buffer.from(data, ENCODING);\n\t\theaders['Content-Length'] = options.data.length;\n\t} else\n\t\toptions.data = data;", "\tif (cookies) {\n\t\tif (isCookies)\n\t\t\toptions.cookies = cookies;\n\t\tvar builder = '';\n\t\tfor (var m in cookies)\n\t\t\tbuilder += (builder ? '; ' : '') + m + '=' + cookies[m];\n\t\tif (builder)\n\t\t\theaders['Cookie'] = builder;\n\t}", "\tvar uri = Url.parse(url);", "\tif (!uri.hostname || !uri.host) {\n\t\tcallback && callback(new Error('URL doesn\\'t contain a hostname'), '', 0);\n\t\treturn;\n\t}", "\turi.method = method;\n\turi.headers = headers;\n\toptions.uri = uri;", "\tif (options.resolve && (uri.hostname === 'localhost' || uri.hostname.charCodeAt(0) < 64))\n\t\toptions.resolve = null;", "\tif (CONF.default_proxy && !proxy && !PROXYBLACKLIST[uri.hostname])\n\t\tproxy = parseProxy(CONF.default_proxy);", "\tif (proxy && (uri.hostname === 'localhost' || uri.hostname === '127.0.0.1'))\n\t\tproxy = null;", "\toptions.proxy = proxy;\n\toptions.param = param;", "\tif (proxy && uri.protocol === 'https:') {\n\t\tproxy.tls = true;\n\t\turi.agent = new ProxyAgent(options);\n\t\turi.agent.request = Http.request;\n\t\turi.agent.createSocket = createSecureSocket;\n\t\turi.agent.defaultPort = 443;\n\t}", "\tif (options.keepalive && !options.proxy && uri.protocol !== 'https:')\n\t\turi.agent = KeepAlive;", "\tif (proxy)\n\t\trequest_call(uri, options);\n\telse if (options.resolve)\n\t\texports.resolve(url, request_resolve, options);\n\telse\n\t\trequest_call(uri, options);", "\treturn options.evt;\n};", "function request_resolve(err, uri, options) {\n\tif (!err)\n\t\toptions.uri.host = uri.host;\n\trequest_call(options.uri, options);\n}", "function ProxyAgent(options) {\n\tvar self = this;\n\tself.options = options;\n\tself.maxSockets = Http.Agent.defaultMaxSockets;\n\tself.requests = [];\n}", "const PAP = ProxyAgent.prototype;", "PAP.createConnection = function(pending) {\n\tvar self = this;\n\tself.createSocket(pending, function(socket) {\n\t\tpending.request.onSocket(socket);\n\t});\n};", "PAP.createSocket = function(options, callback) {", "\tvar self = this;\n\tvar proxy = self.options.proxy;\n\tvar uri = self.options.uri;", "\tPROXYOPTIONS.host = proxy.hostname;\n\tPROXYOPTIONS.port = proxy.port;\n\tPROXYOPTIONS.path = PROXYOPTIONS.headers.host = uri.hostname + ':' + (uri.port || '443');", "\tif (proxy._auth)\n\t\tPROXYOPTIONS.headers['Proxy-Authorization'] = proxy._auth;", "\tvar req = self.request(PROXYOPTIONS);\n\treq.setTimeout(10000);\n\treq.on('response', proxyagent_response);\n\treq.on('connect', function(res, socket) {", "\t\tif (res.statusCode === 200) {\n\t\t\tsocket.$req = req;\n\t\t\tcallback(socket);\n\t\t} else {\n\t\t\tvar err = new Error('Proxy could not be established (maybe a problem in auth), code: ' + res.statusCode);\n\t\t\terr.code = 'ECONNRESET';\n\t\t\toptions.request.emit('error', err);\n\t\t\treq.destroy && req.destroy();\n\t\t\treq = null;\n\t\t\tself.requests = null;\n\t\t\tself.options = null;\n\t\t}\n\t});", "\treq.on('error', function(err) {\n\t\tvar e = new Error('Request Proxy \"proxy {0} --> target {1}\": {2}'.format(PROXYOPTIONS.host + ':' + proxy.port, PROXYOPTIONS.path, err.toString()));\n\t\te.code = err.code;\n\t\toptions.request.emit('error', e);\n\t\treq.destroy && req.destroy();\n\t\treq = null;\n\t\tself.requests = null;\n\t\tself.options = null;\n\t});", "\treq.end();\n};", "function proxyagent_response(res) {\n\tres.upgrade = true;\n}", "PAP.addRequest = function(req, options) {\n\tthis.createConnection({ host: options.host, port: options.port, request: req });\n};", "function createSecureSocket(options, callback) {\n\tvar self = this;\n\tPAP.createSocket.call(self, options, function(socket) {\n\t\tPROXYTLS.servername = self.options.uri.hostname;\n\t\tPROXYTLS.headers = self.options.uri.headers;\n\t\tPROXYTLS.socket = socket;\n\t\tvar tls = Tls.connect(0, PROXYTLS);\n\t\tcallback(tls);\n\t});\n}", "function request_call(uri, options) {", "\tvar opt;", "\tif (options.proxy && !options.proxy.tls) {\n\t\topt = PROXYOPTIONSHTTP;\n\t\topt.port = options.proxy.port;\n\t\topt.host = options.proxy.hostname;\n\t\topt.path = uri.href;\n\t\topt.headers = uri.headers;\n\t\topt.method = uri.method;\n\t\topt.headers.host = uri.host;\n\t\tif (options.proxy._auth)\n\t\t\topt.headers['Proxy-Authorization'] = options.proxy._auth;\n\t} else\n\t\topt = uri;", "\tvar connection = uri.protocol === 'https:' ? Https : Http;\n\tvar req = options.post ? connection.request(opt, request_response) : connection.get(opt, request_response);", "\treq.$options = options;\n\treq.$uri = uri;", "\tif (!options.callback) {\n\t\treq.on('error', NOOP);\n\t\treturn;\n\t}", "\treq.on('error', request_process_error);\n\toptions.timeoutid && clearTimeout(options.timeoutid);\n\toptions.timeoutid = setTimeout(request_process_timeout, options.timeout, req);", "\t// req.on('response', (response) => response.req = req);\n\treq.on('response', request_assign_res);", "\tif (options.upload) {\n\t\toptions.first = true;\n\t\toptions.files.wait(function(file, next) {\n\t\t\trequest_writefile(req, options, file, next);\n\t\t}, function() {\n\t\t\tvar keys = Object.keys(options.data);\n\t\t\tfor (var i = 0, length = keys.length; i < length; i++) {\n\t\t\t\tvar value = options.data[keys[i]];\n\t\t\t\tif (value != null) {\n\t\t\t\t\treq.write((options.first ? '' : NEWLINE) + '--' + options.boundary + NEWLINE + 'Content-Disposition: form-data; name=\"' + keys[i] + '\"' + NEWLINE + NEWLINE + value.toString());\n\t\t\t\t\tif (options.first)\n\t\t\t\t\t\toptions.first = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treq.end(NEWLINE + '--' + options.boundary + '--');\n\t\t});\n\t} else\n\t\treq.end(options.data);\n}", "function request_process_error(err) {\n\tvar options = this.$options;\n\tif (options.callback && !options.done) {\n\t\tif (options.timeoutid) {\n\t\t\tclearTimeout(options.timeoutid);\n\t\t\toptions.timeoutid = null;\n\t\t}\n\t\toptions.canceled = true;\n\t\toptions.callback(err, '', 0, undefined, this.$uri.host, EMPTYOBJECT, options.param);\n\t\toptions.callback = null;\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t}\n}", "function request_process_timeout(req) {\n\tvar options = req.$options;\n\tif (options.callback) {\n\t\tif (options.timeoutid) {\n\t\t\tclearTimeout(options.timeoutid);\n\t\t\toptions.timeoutid = null;\n\t\t}\n\t\treq.socket.destroy();\n\t\treq.socket.end();\n\t\treq.abort();\n\t\toptions.canceled = true;\n\t\toptions.callback(new Error(exports.httpStatus(408)), '', 0, undefined, req.$uri.host, EMPTYOBJECT, options.param);\n\t\toptions.callback = null;\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t}\n}", "function request_assign_res(response) {\n\tresponse.req = this;\n}", "function request_writefile(req, options, file, next) {", "\tvar type = typeof(file.buffer);\n\tvar filename = (type === 'string' ? file.buffer : exports.getName(file.filename));", "\treq.write((options.first ? '' : NEWLINE) + '--' + options.boundary + NEWLINE + 'Content-Disposition: form-data; name=\"' + file.name + '\"; filename=\"' + filename + '\"' + NEWLINE + 'Content-Type: ' + exports.getContentType(exports.getExtension(filename)) + NEWLINE + NEWLINE);", "\tif (options.first)\n\t\toptions.first = false;", "\t// Is Buffer\n\tif (file.buffer && type === 'object') {\n\t\treq.write(file.buffer);\n\t\tnext();\n\t} else {\n\t\tvar stream = Fs.createReadStream(file.filename);\n\t\tstream.once('close', next);\n\t\tstream.pipe(req, STREAMPIPE);\n\t}\n}", "function request_response(res) {", "\tvar options = this.$options;\n\tvar uri = this.$uri;", "\tres._buffer = null;\n\tres._bufferlength = 0;", "\t// We have redirect\n\tif (res.statusCode === 301 || res.statusCode === 302) {", "\t\tif (options.noredirect) {", "\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.canceled = true;", "\t\t\tif (options.callback) {\n\t\t\t\toptions.callback(null, '', res.statusCode, res.headers, uri.host, EMPTYOBJECT, options.param);\n\t\t\t\toptions.callback = null;\n\t\t\t}", "\t\t\tif (options.evt) {\n\t\t\t\toptions.evt.removeAllListeners();\n\t\t\t\toptions.evt = null;\n\t\t\t}", "\t\t\tres.req.removeAllListeners();\n\t\t\tres.removeAllListeners();\n\t\t\tres.req = null;\n\t\t\tres = null;\n\t\t\treturn;\n\t\t}", "\t\tif (options.redirect > 3) {", "\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.canceled = true;", "\t\t\tif (options.callback) {\n\t\t\t\toptions.callback(new Error('Too many redirects.'), '', 0, undefined, uri.host, EMPTYOBJECT, options.param);\n\t\t\t\toptions.callback = null;\n\t\t\t}", "\t\t\tif (options.evt) {\n\t\t\t\toptions.evt.removeAllListeners();\n\t\t\t\toptions.evt = null;\n\t\t\t}", "\t\t\tres.req.removeAllListeners();\n\t\t\tres.removeAllListeners();\n\t\t\tres.req = null;\n\t\t\tres = null;\n\t\t\treturn;\n\t\t}", "\t\toptions.redirect++;", "\t\tvar loc = res.headers['location'];\n\t\tvar proto = loc.substring(0, 6);", "\t\tif (proto !== 'http:/' && proto !== 'https:')\n\t\t\tloc = uri.protocol + '//' + uri.hostname + loc;", "\t\tvar tmp = Url.parse(loc);\n\t\ttmp.headers = uri.headers;\n\t\t// tmp.agent = false;\n\t\ttmp.method = uri.method;", "\t\tres.req.removeAllListeners();\n\t\tres.req = null;", "\t\tif (options.proxy && tmp.protocol === 'https:') {\n\t\t\t// TLS?\n\t\t\toptions.proxy.tls = true;\n\t\t\toptions.uri = tmp;\n\t\t\toptions.uri.agent = new ProxyAgent(options);\n\t\t\toptions.uri.agent.request = Http.request;\n\t\t\toptions.uri.agent.createSocket = createSecureSocket;\n\t\t\toptions.uri.agent.defaultPort = 443;\n\t\t}", "\t\tif (!options.resolve) {\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\treturn request_call(tmp, options);\n\t\t}", "\t\texports.resolve(tmp, function(err, u) {\n\t\t\tif (!err)\n\t\t\t\ttmp.host = u.host;\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\trequest_call(tmp, options);\n\t\t});", "\t\treturn;\n\t}", "\toptions.length = +res.headers['content-length'] || 0;\n\toptions.evt && options.evt.$events.begin && options.evt.emit('begin', options.length);", "\t// Shared cookies\n\tif (options.cookies) {\n\t\tvar arr = (res.headers['set-cookie'] || '');", "\t\t// Only the one value\n\t\tif (arr && !(arr instanceof Array))\n\t\t\tarr = [arr];", "\t\tif (arr instanceof Array) {\n\t\t\tfor (var i = 0, length = arr.length; i < length; i++) {\n\t\t\t\tvar line = arr[i];\n\t\t\t\tvar end = line.indexOf(';');\n\t\t\t\tif (end === -1)\n\t\t\t\t\tend = line.length;\n\t\t\t\tline = line.substring(0, end);\n\t\t\t\tvar index = line.indexOf('=');\n\t\t\t\tif (index !== -1)\n\t\t\t\t\toptions.cookies[line.substring(0, index)] = decodeURIComponent(line.substring(index + 1));\n\t\t\t}\n\t\t}\n\t}", "\tif (res.statusCode === 204) {\n\t\toptions.done = true;\n\t\trequest_process_end.call(res);\n\t\treturn;\n\t}", "\tvar encoding = res.headers['content-encoding'] || '';\n\tif (encoding)\n\t\tencoding = encoding.split(',')[0];", "\tif (COMPRESS[encoding]) {\n\t\tvar zlib = encoding === 'gzip' ? Zlib.createGunzip() : Zlib.createInflate();\n\t\tzlib._buffer = res.buffer;\n\t\tzlib.headers = res.headers;\n\t\tzlib.statusCode = res.statusCode;\n\t\tzlib.res = res;\n\t\tzlib.on('data', request_process_data);\n\t\tzlib.on('end', request_process_end);\n\t\tres.pipe(zlib);\n\t} else {\n\t\tres.on('data', request_process_data);\n\t\tres.on('end', request_process_end);\n\t}", "\tres.resume();\n}", "function request_process_data(chunk) {\n\tvar self = this;", "\t// Is Zlib\n\tif (!self.req)\n\t\tself = self.res;", "\tvar options = self.req.$options;\n\tif (options.canceled || (options.max && self._bufferlength > options.max))\n\t\treturn;\n\tif (self._buffer) {\n\t\tCONCAT[0] = self._buffer;\n\t\tCONCAT[1] = chunk;\n\t\tself._buffer = Buffer.concat(CONCAT);\n\t} else\n\t\tself._buffer = chunk;\n\tself._bufferlength += chunk.length;\n\toptions.evt && options.evt.$events.data && options.evt.emit('data', chunk, options.length ? (self._bufferlength / options.length) * 100 : 0);\n}", "function request_process_end() {", "\tvar res = this;", "\t// Is Zlib\n\tif (!res.req)\n\t\tres = res.res;", "\tvar self = res;\n\tvar options = self.req.$options;\n\tvar uri = self.req.$uri;\n\tvar data;", "\toptions.socket && options.uri.agent.destroy();\n\toptions.timeoutid && clearTimeout(options.timeoutid);", "\tif (options.canceled)\n\t\treturn;", "\tvar ct = self.headers['content-type'];", "\tif (!ct || REG_TEXTAPPLICATION.test(ct))\n\t\tdata = self._buffer ? (options.encoding === 'binary' ? self._buffer : self._buffer.toString(options.encoding)) : '';\n\telse\n\t\tdata = self._buffer;", "\toptions.canceled = true;", "\tself._buffer = undefined;", "\tif (options.evt) {\n\t\toptions.evt.$events.end && options.evt.emit('end', data, self.statusCode, self.headers, uri.host, options.cookies, options.param);\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t}", "\tif (options.callback) {\n\t\toptions.callback(null, uri.method === 'HEAD' ? self.headers : data, self.statusCode, self.headers, uri.host, options.cookies, options.param);\n\t\toptions.callback = null;\n\t}", "\tif (res.statusCode !== 204) {\n\t\tres.req && res.req.removeAllListeners();\n\t\tres.removeAllListeners();\n\t}\n}", "exports.$$request = function(url, flags, data, cookies, headers, encoding, timeout) {\n\treturn function(callback) {\n\t\texports.request(url, flags, data, callback, cookies, headers, encoding, timeout);\n\t};\n};", "exports.btoa = function(str) {\n\treturn (str instanceof Buffer) ? str.toString('base64') : Buffer.from(str.toString(), 'utf8').toString('base64');\n};", "exports.atob = function(str) {\n\treturn Buffer.from(str, 'base64').toString('utf8');\n};", "/**\n * Create a request to a specific URL\n * @param {String} url URL address.\n * @param {String Array} flags Request flags.\n * @param {String or Object} data Request data (optional).\n * @param {Function(error, response)} callback Callback.\n * @param {Object} cookies Custom cookies (optional, default: null).\n * @param {Object} headers Custom headers (optional, default: null).\n * @param {String} encoding Encoding (optional, default: UTF8)\n * @param {Number} timeout Request timeout.\n * return {Boolean}\n */\nexports.download = function(url, flags, data, callback, cookies, headers, encoding, timeout, param) {", "\t// No data (data is optional argument)\n\tif (typeof(data) === 'function') {\n\t\ttimeout = encoding;\n\t\tencoding = headers;\n\t\theaders = cookies;\n\t\tcookies = callback;\n\t\tcallback = data;\n\t\tdata = '';\n\t}", "\tif (typeof(cookies) === 'number') {\n\t\tcookies = null;\n\t\ttimeout = cookies;\n\t}", "\tif (typeof(headers) === 'number') {\n\t\theaders = null;\n\t\ttimeout = headers;\n\t}", "\tif (typeof(encoding) === 'number') {\n\t\tencoding = null;\n\t\ttimeout = encoding;\n\t}", "\tif (typeof(encoding) !== 'string')\n\t\tencoding = ENCODING;", "\tvar proxy, type = 0;\n\tvar method = 'GET';\n\tvar options = { callback: callback, resolve: false, length: 0, evt: new EventEmitter2(), timeout: timeout || 60000, post: false, encoding: encoding };", "\tif (headers)\n\t\theaders = exports.extend({}, headers);\n\telse\n\t\theaders = {};", "\tif (data === null)\n\t\tdata = '';", "\tif (flags instanceof Array) {\n\t\tfor (var i = 0, length = flags.length; i < length; i++) {", "\t\t\t// timeout\n\t\t\tif (flags[i] > 0) {\n\t\t\t\toptions.timeout = flags[i];\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (flags[i][0] === '<') {\n\t\t\t\t// max length is not supported\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (flags[i][0] === 'p' && flags[i][4] === 'y') {\n\t\t\t\tproxy = parseProxy(flags[i].substring(6));\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tswitch (flags[i].toLowerCase()) {", "\t\t\t\tcase 'utf8':\n\t\t\t\tcase 'ascii':\n\t\t\t\tcase 'base64':\n\t\t\t\tcase 'binary':\n\t\t\t\tcase 'hex':\n\t\t\t\t\toptions.encoding = flags[i];\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'xhr':\n\t\t\t\t\theaders['X-Requested-With'] = 'XMLHttpRequest';\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'plain':\n\t\t\t\t\theaders['Content-Type'] = 'text/plain';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'html':\n\t\t\t\t\theaders['Content-Type'] = 'text/html';\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'json':\n\t\t\t\t\theaders['Content-Type'] = 'application/json';\n\t\t\t\t\ttype = 1;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'xml':\n\t\t\t\t\theaders['Content-Type'] = 'text/xml';\n\t\t\t\t\ttype = 2;\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'get':\n\t\t\t\tcase 'head':\n\t\t\t\tcase 'options':\n\t\t\t\t\tmethod = flags[i].charCodeAt(0) > 96 ? flags[i].toUpperCase() : flags[i];\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'upload':\n\t\t\t\t\theaders['Content-Type'] = 'multipart/form-data';\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'post':\n\t\t\t\tcase 'patch':\n\t\t\t\tcase 'delete':\n\t\t\t\tcase 'put':\n\t\t\t\t\tmethod = flags[i].charCodeAt(0) > 96 ? flags[i].toUpperCase() : flags[i];\n\t\t\t\t\tif (!headers['Content-Type'])\n\t\t\t\t\t\theaders['Content-Type'] = 'application/x-www-form-urlencoded';\n\t\t\t\t\tbreak;", "\t\t\t\tcase 'dnscache':\n\t\t\t\t\toptions.resolve = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'keepalive':\n\t\t\t\t\toptions.keepalive = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t// Fallback for methods (e.g. CalDAV)\n\t\t\t\t\tmethod = flags[i].charCodeAt(0) > 96 ? flags[i].toUpperCase() : flags[i];\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "\tif (!method)\n\t\tmethod = 'GET';", "\toptions.post = !NOBODY[method];", "\tif (typeof(data) !== 'string')\n\t\tdata = type === 1 ? JSON.stringify(data) : Qs.stringify(data);\n\telse if (data[0] === '?')\n\t\tdata = data.substring(1);", "\tif (!options.post) {\n\t\tif (data.length && url.indexOf('?') === -1)\n\t\t\turl += '?' + data;\n\t\tdata = '';\n\t}", "\tif (cookies) {\n\t\tvar builder = '';\n\t\tfor (var m in cookies)\n\t\t\tbuilder += (builder ? '; ' : '') + m + '=' + cookies[m];\n\t\tif (builder)\n\t\t\theaders['Cookie'] = builder;\n\t}", "\tvar uri = Url.parse(url);\n\turi.method = method;\n\t// uri.agent = false;\n\turi.headers = headers;\n\toptions.uri = uri;\n\toptions.param = param;", "\tif (options.resolve && (uri.hostname === 'localhost' || uri.hostname.charCodeAt(0) < 64))\n\t\toptions.resolve = null;", "\tif (data.length) {\n\t\toptions.data = Buffer.from(data, ENCODING);\n\t\theaders['Content-Length'] = options.data.length;\n\t}", "\tif (CONF.default_proxy && !proxy && !PROXYBLACKLIST[uri.hostname])\n\t\tproxy = parseProxy(CONF.default_proxy);", "\toptions.proxy = proxy;", "\tif (proxy && uri.protocol === 'https:') {\n\t\tproxy.tls = true;\n\t\turi.agent = new ProxyAgent(options);\n\t\turi.agent.request = Http.request;\n\t\turi.agent.createSocket = createSecureSocket;\n\t\turi.agent.defaultPort = 443;\n\t}", "\tif (options.keepalive && !options.proxy && uri.protocol !== 'https:')\n\t\turi.agent = KeepAlive;", "\tif (global.F)\n\t\tglobal.F.stats.performance.external++;", "\tif (proxy)\n\t\tdownload_call(uri, options);\n\telse if (options.resolve)\n\t\texports.resolve(url, download_resolve, options);\n\telse\n\t\tdownload_call(uri, options);", "\treturn options.evt;\n};", "function download_resolve(err, uri, options) {\n\tif (!err)\n\t\toptions.uri.host = uri.host;\n\tdownload_call(options.uri, options);\n}", "function download_call(uri, options) {", "\tvar opt;\n\toptions.length = 0;", "\tif (options.proxy && !options.proxy.tls) {\n\t\topt = PROXYOPTIONSHTTP;\n\t\topt.port = options.proxy.port;\n\t\topt.host = options.proxy.hostname;\n\t\topt.path = uri.href;\n\t\topt.headers = uri.headers;\n\t\topt.method = uri.method;\n\t\tif (options.proxy._auth)\n\t\t\topt.headers['Proxy-Authorization'] = options.proxy._auth;\n\t} else\n\t\topt = uri;", "\tvar connection = uri.protocol === 'https:' ? Https : Http;\n\tvar req = options.post ? connection.request(opt, download_response) : connection.get(opt, download_response);", "\treq.$options = options;\n\treq.$uri = uri;", "\tif (!options.callback) {\n\t\treq.on('error', NOOP);\n\t\treturn;\n\t}", "\treq.on('error', download_process_error);\n\toptions.timeoutid && clearTimeout(options.timeoutid);\n\toptions.timeoutid = setTimeout(download_process_timeout, options.timeout);\n\treq.on('response', download_assign_res);\n\treq.end(options.data);\n}", "function download_assign_res(response) {\n\tresponse.req = this;\n\tvar options = this.$options;\n\toptions.length = +response.headers['content-length'] || 0;\n\toptions.evt && options.evt.$events.begin && options.evt.emit('begin', options.length);\n}", "function download_process_timeout(req) {\n\tvar options = req.$options;\n\tif (options.callback) {\n\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\toptions.timeoutid = null;\n\t\treq.abort();\n\t\toptions.callback(new Error(exports.httpStatus(408)), null, null, null, null, options.param);\n\t\toptions.callback = null;\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t\toptions.canceled = true;\n\t}\n}", "function download_process_error(err) {\n\tvar options = this.$options;\n\tif (options.callback && !options.done) {\n\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\toptions.timeoutid = null;\n\t\toptions.callback(err, null, null, null, null, options.param);\n\t\toptions.callback = null;\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t\toptions.canceled = true;\n\t}\n}", "function download_response(res) {", "\tvar options = this.$options;\n\tvar uri = this.$uri;", "\tres._bufferlength = 0;", "\t// We have redirect\n\tif (res.statusCode === 301 || res.statusCode === 302) {", "\t\tif (options.redirect > 3) {\n\t\t\toptions.canceled = true;\n\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.callback && options.callback(new Error('Too many redirects.'), null, null, null, null, options.param);\n\t\t\tres.req.removeAllListeners();\n\t\t\tres.req = null;\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\treturn;\n\t\t}", "\t\toptions.redirect++;", "\t\tvar loc = res.headers['location'];\n\t\tvar proto = loc.substring(0, 6);", "\t\tif (proto !== 'http:/' && proto !== 'https:')\n\t\t\tloc = uri.protocol + '//' + uri.hostname + loc;", "\t\tvar tmp = Url.parse(loc);\n\t\ttmp.headers = uri.headers;\n\t\t// tmp.agent = false;\n\t\ttmp.method = uri.method;\n\t\tres.req.removeAllListeners();\n\t\tres.req = null;", "\t\tif (options.proxy && tmp.protocol === 'https:') {\n\t\t\t// TLS?\n\t\t\toptions.uri = tmp;\n\t\t\tdownload_call(options, request_call);\n\t\t\treturn;\n\t\t}", "\t\tif (!options.resolve) {\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\treturn download_call(tmp, options);\n\t\t}", "\t\texports.resolve(loc, function(err, u) {\n\t\t\tif (!err)\n\t\t\t\ttmp.host = u.host;\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\tdownload_call(tmp, options);\n\t\t});", "\t\treturn;\n\t}", "\tres.on('data', download_process_data);\n\tres.on('end', download_process_end);", "\tres.resume();\n\toptions.timeoutid && clearTimeout(options.timeoutid);\n\toptions.callback && options.callback(null, res, res.statusCode, res.headers, uri.host, options.param);\n}", "exports.$$download = function(url, flags, data, cookies, headers, encoding, timeout) {\n\treturn function(callback) {\n\t\texports.download(url, flags, data, callback, cookies, headers, encoding, timeout);\n\t};\n};", "function download_process_end() {", "\tvar res = this;\n\tvar self = this;\n\tvar options = self.req.$options;\n\tvar uri = self.req.$uri;", "\tif (!options.canceled) {\n\t\tvar str = self._buffer ? self._buffer.toString(options.encoding) : '';\n\t\tself._buffer = undefined;\n\t\toptions.evt && options.evt.$events.end && options.evt.emit('end', str, self.statusCode, self.headers, uri.host);\n\t}", "\tif (options.evt) {\n\t\toptions.evt.removeAllListeners();\n\t\toptions.evt = null;\n\t}", "\tres.req && res.req.removeAllListeners();\n\tres.removeAllListeners();\n}", "function download_process_data(chunk) {\n\tvar self = this;\n\tvar options = self.req.$options;\n\tif (!options.canceled) {\n\t\tself._bufferlength += chunk.length;\n\t\tif (options.evt) {\n\t\t\toptions.evt.$events.data && options.evt.emit('data', chunk, options.length ? (self._bufferlength / options.length) * 100 : 0);\n\t\t\toptions.evt.$events.progress && options.evt.emit('progress', options.length ? (self._bufferlength / options.length) * 100 : 0);\n\t\t}\n\t}\n}", "/**\n * Upload a stream through HTTP\n * @param {String} name Filename with extension.\n * @param {Stream} stream Stream.\n * @param {String} url A valid URL address.\n * @param {Function} callback Callback.\n * @param {Object} headers Custom headers (optional).\n * @param {String} method HTTP method (optional, default POST).\n * @param {Number} timeout Request timeout, default: 60000 (1 minute)\n */\nexports.send = function(name, stream, url, callback, cookies, headers, method, timeout) {", "\tOBSOLETE('U.send()', 'Use U.upload() instead of U.send().');", "\tif (typeof(stream) === 'string')\n\t\tstream = Fs.createReadStream(stream, STREAM_READONLY);", "\tvar BOUNDARY = '----totaljs' + Math.random().toString(16).substring(2);\n\tvar h = {};", "\tif (headers)\n\t\texports.extend(h, headers);", "\tif (cookies) {\n\t\tvar builder = '';\n\t\tfor (var m in cookies)\n\t\t\tbuilder += (builder ? '; ' : '') + m + '=' + cookies[m];\n\t\tif (builder)\n\t\t\th['Cookie'] = builder;\n\t}", "\tname = exports.getName(name);", "\th['Cache-Control'] = 'max-age=0';\n\th['Content-Type'] = 'multipart/form-data; boundary=' + BOUNDARY;", "\tif (global.F)\n\t\tglobal.F.stats.performance.external++;", "\tvar e = new EventEmitter2();\n\tvar uri = Url.parse(url);\n\tvar options = { protocol: uri.protocol, auth: uri.auth, method: method || 'POST', hostname: uri.hostname, port: uri.port, path: uri.path, agent: false, headers: h };\n\tvar responseLength = 0;", "\tvar response = function(res) {", "\t\tres.body = Buffer.alloc(0);\n\t\tres._bufferlength = 0;", "\t\tres.on('data', function(chunk) {\n\t\t\tCONCAT[0] = res.body;\n\t\t\tCONCAT[1] = chunk;\n\t\t\tres.body = Buffer.concat(CONCAT);\n\t\t\tres._bufferlength += chunk.length;\n\t\t\te.$events.data && e.emit('data', chunk, responseLength ? (res._bufferlength / responseLength) * 100 : 0);\n\t\t});", "\t\tres.on('end', function() {\n\t\t\tvar self = this;\n\t\t\te.$events.end && e.emit('end', self.statusCode, self.headers);\n\t\t\te.removeAllListeners();\n\t\t\te = null;\n\t\t\tcallback && callback(null, self.body.toString('utf8'), self.statusCode, self.headers, uri.host);\n\t\t\tself.body = null;\n\t\t});\n\t};", "\tvar connection = options.protocol === 'https:' ? Https : Http;\n\tvar req = connection.request(options, response);", "\treq.on('response', function(response) {\n\t\tresponseLength = +response.headers['content-length'] || 0;\n\t\te.$events.begin && e.emit('begin', responseLength);\n\t});", "\treq.setTimeout(timeout || 60000, function() {\n\t\treq.removeAllListeners();\n\t\treq = null;\n\t\te.removeAllListeners();\n\t\te = null;\n\t\tcallback && callback(new Error(exports.httpStatus(408)), '', 408, undefined, uri.host);\n\t});", "\treq.on('error', function(err) {\n\t\treq.removeAllListeners();\n\t\treq = null;\n\t\te.removeAllListeners();\n\t\te = null;\n\t\tcallback && callback(err, '', 0, undefined, uri.host);\n\t});", "\treq.on('close', function() {\n\t\treq.removeAllListeners();\n\t\treq = null;\n\t});", "\tvar header = NEWLINE + NEWLINE + '--' + BOUNDARY + NEWLINE + 'Content-Disposition: form-data; name=\"File\"; filename=\"' + name + '\"' + NEWLINE + 'Content-Type: ' + exports.getContentType(exports.getExtension(name)) + NEWLINE + NEWLINE;\n\treq.write(header);", "\t// Is Buffer\n\tif (stream.length) {\n\t\treq.write(stream);\n\t\treq.end(NEWLINE + NEWLINE + '--' + BOUNDARY + '--');\n\t\treturn e;\n\t}", "\tstream.on('end', () => req.end(NEWLINE + NEWLINE + '--' + BOUNDARY + '--'));\n\tstream.pipe(req, STREAM_END);\n\treturn e;\n};", "exports.$$send = function(name, stream, url, cookies, headers, method, timeout) {\n\treturn function(callback) {\n\t\texports.send(name, stream, url, callback, cookies, headers, method, timeout);\n\t};\n};", "exports.upload = function(files, url, callback, cookies, headers, method, timeout) {", "\tvar BOUNDARY = '----totaljs' + Math.random().toString(16).substring(2);\n\tvar h = {};", "\theaders && exports.extend_headers2(h, headers);", "\tif (cookies) {\n\t\tvar builder = '';\n\t\tfor (var m in cookies)\n\t\t\tbuilder += (builder ? '; ' : '') + m + '=' + cookies[m];\n\t\tbuilder && (h['Cookie'] = builder);\n\t}", "\tif (global.F)\n\t\tglobal.F.stats.performance.external++;", "\th['Cache-Control'] = 'max-age=0';\n\th['Content-Type'] = 'multipart/form-data; boundary=' + BOUNDARY;", "\tvar e = new EventEmitter2();\n\tvar uri = Url.parse(url);\n\tvar options = { protocol: uri.protocol, auth: uri.auth, method: method || 'POST', hostname: uri.hostname, port: uri.port, path: uri.path, agent: false, headers: h };\n\tvar responseLength = 0;\n\tvar timeoutid;\n\tvar done = false;", "\tvar response = function(res) {", "\t\tres.body = Buffer.alloc(0);\n\t\tres._bufferlength = 0;", "\t\tres.on('data', function(chunk) {\n\t\t\tif (!done) {\n\t\t\t\tCONCAT[0] = res.body;\n\t\t\t\tCONCAT[1] = chunk;\n\t\t\t\tres.body = Buffer.concat(CONCAT);\n\t\t\t\tres._bufferlength += chunk.length;\n\t\t\t\te.$events.data && e.emit('data', chunk, responseLength ? (res._bufferlength / responseLength) * 100 : 0);\n\t\t\t}\n\t\t});", "\t\tres.on('end', function() {\n\t\t\tif (!done) {\n\t\t\t\tvar self = this;\n\t\t\t\te.$events.end && e.emit('end', self.statusCode, self.headers);\n\t\t\t\te.removeAllListeners();\n\t\t\t\tcallback && callback(null, self.body.toString('utf8'), self.statusCode, self.headers, uri.host);\n\t\t\t\ttimeoutid && clearTimeout(timeoutid);\n\t\t\t\tself.body = null;\n\t\t\t\te = null;\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t});\n\t};", "\tvar connection = options.protocol === 'https:' ? Https : Http;\n\tvar req = connection.request(options, response);", "\treq.on('response', function(response) {\n\t\tresponseLength = +response.headers['content-length'] || 0;\n\t\te.$events.begin && e.emit('begin', responseLength);\n\t});", "\tvar timeoutcallback = function() {\n\t\tif (!done) {\n\t\t\treq.removeAllListeners();\n\t\t\te.removeAllListeners();\n\t\t\tcallback && callback(new Error(exports.httpStatus(408)), '', 408, undefined, uri.host);\n\t\t\ttimeoutid && clearTimeout(timeoutid);\n\t\t\treq = null;\n\t\t\te = null;\n\t\t\tdone = true;\n\t\t}\n\t};", "\tif (timeout)\n\t\ttimeoutid = setTimeout(timeoutcallback, timeout);", "\treq.setTimeout(timeout || 60000, timeoutcallback);", "\treq.on('error', function(err) {\n\t\tdone = true;\n\t\treq.removeAllListeners();\n\t\te.removeAllListeners();\n\t\tcallback && callback(err, '', 0, undefined, uri.host);\n\t\ttimeoutid && clearTimeout(timeoutid);\n\t\treq = null;\n\t\te = null;\n\t});", "\treq.on('close', function() {\n\t\treq.removeAllListeners();\n\t\treq = null;\n\t});", "\tvar header = NEWLINE + NEWLINE + '--' + BOUNDARY + NEWLINE + 'Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"' + NEWLINE + 'Content-Type: {2}' + NEWLINE + NEWLINE;", "\tfiles.wait(function(item, next) {", "\t\t// item.name;\n\t\t// item.filename;\n\t\t// item.stream (optional) or item.buffer (optional)", "\t\treq.write(header.format(item.name, U.getName(item.filename), exports.getContentType(exports.getExtension(item.filename))));", "\t\tif (item.buffer) {\n\t\t\treq.write(item.buffer);\n\t\t\treturn next();\n\t\t}", "\t\t!item.stream && (item.stream = Fs.createReadStream(item.filename));\n\t\titem.stream.pipe(req, STREAM_END);\n\t\titem.stream.on('error', next);\n\t\titem.stream.on('end', next);", "\t}, () => req.end(NEWLINE + NEWLINE + '--' + BOUNDARY + '--'));\n\treturn e;\n};", "exports.$$upload = function(files, url, cookies, headers, method, timeout) {\n\treturn function(callback) {\n\t\texports.upload(files, url, callback, cookies, headers, method, timeout);\n\t};\n};", "/**\n * Trim string properties\n * @param {Object} obj\n * @return {Object}\n */\nexports.trim = function(obj, clean) {", "\tif (!obj)\n\t\treturn obj;", "\tvar type = typeof(obj);\n\tif (type === 'string') {\n\t\tobj = obj.trim();\n\t\treturn clean && !obj ? undefined : obj;\n\t}", "\tif (obj instanceof Array) {\n\t\tfor (var i = 0, length = obj.length; i < length; i++) {", "\t\t\tvar item = obj[i];\n\t\t\ttype = typeof(item);", "\t\t\tif (type === 'object') {\n\t\t\t\texports.trim(item, clean);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (type !== 'string')\n\t\t\t\tcontinue;", "\t\t\tobj[i] = item.trim();\n\t\t\tif (clean && !obj[i])\n\t\t\t\tobj[i] = undefined;\n\t\t}", "\t\treturn obj;\n\t}", "\tif (type !== 'object')\n\t\treturn obj;", "\tvar keys = Object.keys(obj);\n\tfor (var i = 0, length = keys.length; i < length; i++) {\n\t\tvar val = obj[keys[i]];\n\t\tvar type = typeof(val);\n\t\tif (type === 'object') {\n\t\t\texports.trim(val, clean);\n\t\t\tcontinue;\n\t\t} else if (type !== 'string')\n\t\t\tcontinue;\n\t\tobj[keys[i]] = val.trim();\n\t\tif (clean && !obj[keys[i]])\n\t\t\tobj[keys[i]] = undefined;\n\t}", "\treturn obj;\n};", "/**\n * Noop function\n * @return {Function} Empty function.\n */\nexports.noop = global.noop = global.NOOP = function() {};", "/**\n * Read HTTP status\n * @param {Number} code HTTP code status.\n * @param {Boolean} addCode Add code number to HTTP status.\n * @return {String}\n */\nexports.httpStatus = function(code, addCode) {\n\tif (addCode === undefined)\n\t\taddCode = true;\n\treturn (addCode ? code + ': ' : '') + Http.STATUS_CODES[code];\n};", "/**\n * Extend object\n * @param {Object} target Target object.\n * @param {Object} source Source object.\n * @param {Boolean} rewrite Rewrite exists values (optional, default true).\n * @return {Object} Modified object.\n */\nexports.extend = function(target, source, rewrite) {", "\tif (!target || !source)\n\t\treturn target;", "\tif (typeof(target) !== 'object' || typeof(source) !== 'object')\n\t\treturn target;", "\tif (rewrite === undefined)\n\t\trewrite = true;", "\tvar keys = Object.keys(source);\n\tvar i = keys.length;", "\twhile (i--) {\n\t\tvar key = keys[i];\n\t\tif (rewrite || target[key] === undefined)\n\t\t\ttarget[key] = exports.clone(source[key]);\n\t}", "\treturn target;\n};", "exports.extend_headers = function(first, second) {\n\tvar keys = Object.keys(first);\n\tvar headers = {};", "\tvar i = keys.length;\n\twhile (i--)\n\t\theaders[keys[i]] = first[keys[i]];", "\tkeys = Object.keys(second);\n\ti = keys.length;", "\twhile (i--)\n\t\theaders[keys[i]] = second[keys[i]];", "\treturn headers;\n};", "exports.extend_headers2 = function(first, second) {\n\tvar keys = Object.keys(second);\n\tvar i = keys.length;\n\twhile (i--)\n\t\tfirst[keys[i]] = second[keys[i]];\n\treturn first;\n};", "/**\n * Clones object\n * @param {Object} obj\n * @param {Object} skip Optional, can be only object e.g. { name: true, age: true }.\n * @param {Boolean} skipFunctions It doesn't clone functions, optional --> default false.\n * @return {Object}\n */\nglobal.CLONE = exports.clone = function(obj, skip, skipFunctions) {", "\tif (!obj)\n\t\treturn obj;", "\tvar type = typeof(obj);\n\tif (type !== 'object' || obj instanceof Date || obj instanceof Error)\n\t\treturn obj;", "\tvar length;\n\tvar o;", "\tif (obj instanceof Array) {", "\t\tlength = obj.length;\n\t\to = new Array(length);", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\ttype = typeof(obj[i]);\n\t\t\tif (type !== 'object' || obj[i] instanceof Date || obj[i] instanceof Error) {\n\t\t\t\tif (skipFunctions && type === 'function')\n\t\t\t\t\tcontinue;\n\t\t\t\to[i] = obj[i];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\to[i] = exports.clone(obj[i], skip, skipFunctions);\n\t\t}", "\t\treturn o;\n\t}", "\to = {};", "\tfor (var m in obj) {", "\t\tif (skip && skip[m])\n\t\t\tcontinue;", "\t\tvar val = obj[m];", "\t\tif (val instanceof Buffer) {\n\t\t\tvar copy = Buffer.alloc(val.length);\n\t\t\tval.copy(copy);\n\t\t\to[m] = copy;\n\t\t\tcontinue;\n\t\t}", "\t\tvar type = typeof(val);\n\t\tif (type !== 'object' || val instanceof Date || val instanceof Error) {\n\t\t\tif (skipFunctions && type === 'function')\n\t\t\t\tcontinue;\n\t\t\to[m] = val;\n\t\t\tcontinue;\n\t\t}", "\t\to[m] = exports.clone(obj[m], skip, skipFunctions);\n\t}", "\treturn o;\n};", "/**\n * Copy values from object to object\n * @param {Object} source Object source\n * @param {Object} target Object target (optional)\n * @return {Object} Modified object.\n */\nexports.copy = function(source, target) {", "\tif (target === undefined)\n\t\treturn exports.extend({}, source, true);", "\tif (!target || !source || typeof(target) !== 'object' || typeof(source) !== 'object')\n\t\treturn target;", "\tvar keys = Object.keys(source);\n\tvar i = keys.length;", "\twhile (i--) {\n\t\tvar key = keys[i];\n\t\ttarget[key] !== undefined && (target[key] = exports.clone(source[key]));\n\t}", "\treturn target;\n};", "/**\n * Reduce an object\n * @param {Object} source Source object.\n * @param {String Array or Object} prop Other properties than these ones will be removed.\n * @param {Boolean} reverse Reverse reducing (prop will be removed), default: false.\n * @return {Object}\n */\nexports.reduce = function(source, prop, reverse) {", "\tif (!(prop instanceof Array)) {\n\t\tif (typeof(prop) === 'object')\n\t\t\treturn exports.reduce(source, Object.keys(prop), reverse);\n\t}", "\tif (source instanceof Array) {\n\t\tvar arr = [];\n\t\tfor (var i = 0, length = source.length; i < length; i++)\n\t\t\tarr.push(exports.reduce(source[i], prop, reverse));\n\t\treturn arr;\n\t}", "\tvar output = {};", "\tvar keys = Object.keys(source);\n\tfor (var i = 0; i < keys.length; i++) {\n\t\tvar o = keys[i];\n\t\tif (reverse) {\n\t\t\tif (prop.indexOf(o) === -1)\n\t\t\t\toutput[o] = source[o];\n\t\t} else {\n\t\t\tif (prop.indexOf(o) !== -1)\n\t\t\t\toutput[o] = source[o];\n\t\t}\n\t}", "\treturn output;\n};", "/**\n * Assign value to an object according to a path\n * @param {Object} obj Source object.\n * @param {String} path Path to the update.\n * @param {Object or Function} fn Value or Function to update.\n * @return {Object}\n */\n// @TODO: deprecated, it will be removed in v4\nexports.assign = function(obj, path, fn) {", "\tif (obj == null)\n\t\treturn obj;", "\tvar arr = path.split('.');\n\tvar model = obj[arr[0]];", "\tfor (var i = 1; i < arr.length - 1; i++)\n\t\tmodel = model[arr[i]];", "\tmodel[arr[arr.length - 1]] = typeof (fn) === 'function' ? fn(model[arr[arr.length - 1]]) : fn;\n\treturn obj;\n};", "/**\n * Checks if is relative url\n * @param {String} url\n * @return {Boolean}\n */\nexports.isRelative = function(url) {\n\treturn !(url.substring(0, 2) === '//' || url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1);\n};", "/**\n * Streamer method\n * @param {String/Buffer} beg\n * @param {String/Buffer} end\n * @param {Function(value, index)} callback\n */\nexports.streamer = function(beg, end, callback, skip, stream, raw) {", "\tif (typeof(end) === 'function') {\n\t\tstream = skip;\n\t\tskip = callback;\n\t\tcallback = end;\n\t\tend = undefined;\n\t}", "\tif (typeof(skip) === 'object') {\n\t\tstream = skip;\n\t\tskip = 0;\n\t}", "\tvar indexer = 0;\n\tvar buffer = Buffer.alloc(0);\n\tvar canceled = false;\n\tvar fn;", "\tif (skip === undefined)\n\t\tskip = 0;", "\tif (!(beg instanceof Buffer))\n\t\tbeg = Buffer.from(beg, 'utf8');", "\tif (end && !(end instanceof Buffer))\n\t\tend = Buffer.from(end, 'utf8');", "\tif (!end) {\n\t\tvar length = beg.length;\n\t\tfn = function(chunk) {", "\t\t\tif (!chunk || canceled)\n\t\t\t\treturn;", "\t\t\tCONCAT[0] = buffer;\n\t\t\tCONCAT[1] = chunk;", "\t\t\tvar f = 0;", "\t\t\tif (buffer.length) {\n\t\t\t\tf = buffer.length - beg.length;\n\t\t\t\tif (f < 0)\n\t\t\t\t\tf = 0;\n\t\t\t}", "\t\t\tbuffer = Buffer.concat(CONCAT);", "\t\t\tvar index = buffer.indexOf(beg, f);\n\t\t\tif (index === -1)\n\t\t\t\treturn;", "\t\t\twhile (index !== -1) {", "\t\t\t\tif (skip)\n\t\t\t\t\tskip--;\n\t\t\t\telse {\n\t\t\t\t\tif (callback(raw ? buffer.slice(0, index + length) : buffer.toString('utf8', 0, index + length), indexer++) === false)\n\t\t\t\t\t\tcanceled = true;\n\t\t\t\t}", "\t\t\t\tif (canceled)\n\t\t\t\t\treturn;", "\t\t\t\tbuffer = buffer.slice(index + length);\n\t\t\t\tindex = buffer.indexOf(beg);\n\t\t\t\tif (index === -1)\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t};", "\t\tstream && stream.on('end', () => fn(beg));\n\t\treturn fn;\n\t}", "\tvar blength = beg.length;\n\tvar elength = end.length;\n\tvar bi = -1;\n\tvar ei = -1;\n\tvar is = false;", "\tfn = function(chunk) {", "\t\tif (!chunk || canceled)\n\t\t\treturn;", "\t\tCONCAT[0] = buffer;\n\t\tCONCAT[1] = chunk;\n\t\tbuffer = Buffer.concat(CONCAT);", "\t\tif (!is) {\n\t\t\tvar f = CONCAT[0].length - beg.length;\n\t\t\tif (f < 0)\n\t\t\t\tf = 0;\n\t\t\tbi = buffer.indexOf(beg, f);\n\t\t\tif (bi === -1)\n\t\t\t\treturn;\n\t\t\tis = true;\n\t\t}", "\t\tif (is) {\n\t\t\tei = buffer.indexOf(end, bi + blength);\n\t\t\tif (ei === -1)\n\t\t\t\treturn;\n\t\t}", "\t\twhile (bi !== -1) {", "\t\t\tif (skip)\n\t\t\t\tskip--;\n\t\t\telse {\n\t\t\t\tif (callback(raw ? buffer.slice(bi, ei + elength) : buffer.toString('utf8', bi, ei + elength), indexer++) === false)\n\t\t\t\t\tcanceled = true;\n\t\t\t}", "\t\t\tif (canceled)\n\t\t\t\treturn;", "\t\t\tbuffer = buffer.slice(ei + elength);\n\t\t\tis = false;\n\t\t\tbi = buffer.indexOf(beg);\n\t\t\tif (bi === -1)\n\t\t\t\treturn;\n\t\t\tis = true;\n\t\t\tei = buffer.indexOf(end, bi + blength);\n\t\t\tif (ei === -1)\n\t\t\t\treturn;\n\t\t}\n\t};", "\tstream && stream.on('end', () => fn(end));\n\treturn fn;\n};", "exports.streamer2 = function(beg, end, callback, skip, stream) {\n\treturn exports.streamer(beg, end, callback, skip, stream, true);\n};", "/**\n * HTML encode string\n * @param {String} str\n * @return {String}\n */\nexports.encode = function(str) {", "\tif (str == null)\n\t\treturn '';", "\tvar type = typeof(str);\n\tif (type !== 'string')\n\t\tstr = str.toString();", "\treturn str.encode();\n};", "/**\n * HTML decode string\n * @param {String} str\n * @return {String}\n */\nexports.decode = function(str) {", "\tif (str == null)\n\t\treturn '';", "\tvar type = typeof(str);\n\tif (type !== 'string')\n\t\tstr = str.toString();", "\treturn str.decode();\n};", "/**\n * Checks if URL contains file extension.\n * @param {String} url\n * @return {Boolean}\n */\nexports.isStaticFile = function(url) {\n\treturn regexpSTATIC.test(url);\n};", "/**\n * Converts Value to number\n * @param {Object} obj Value to convert.\n * @param {Number} def Default value (default: 0).\n * @return {Number}\n */\nexports.parseInt = function(obj, def) {\n\tif (obj == null || obj === '')\n\t\treturn def === undefined ? 0 : def;\n\tvar type = typeof(obj);\n\treturn type === 'number' ? obj : (type !== 'string' ? obj.toString() : obj).parseInt(def);\n};", "exports.parseBool = exports.parseBoolean = function(obj, def) {\n\tif (obj == null)\n\t\treturn def === undefined ? false : def;\n\tvar type = typeof(obj);\n\treturn type === 'boolean' ? obj : type === 'number' ? obj > 0 : (type !== 'string' ? obj.toString() : obj).parseBool(def);\n};", "/**\n * Converts Value to float number\n * @param {Object} obj Value to convert.\n * @param {Number} def Default value (default: 0).\n * @return {Number}\n */\nexports.parseFloat = function(obj, def) {\n\tif (obj == null || obj === '')\n\t\treturn def === undefined ? 0 : def;\n\tvar type = typeof(obj);\n\treturn type === 'number' ? obj : (type !== 'string' ? obj.toString() : obj).parseFloat(def);\n};", "/**\n * Check if the object is Array.\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isArray = function(obj) {\n\treturn obj instanceof Array;\n};", "/**\n * Check if the object is RegExp\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isRegExp = function(obj) {\n\treturn obj && typeof(obj.test) === 'function' ? true : false;\n};", "/**\n * Check if the object is Date\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isDate = function(obj) {\n\treturn obj instanceof Date && !isNaN(obj.getTime()) ? true : false;\n};", "/**\n * Check if the object is Date\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isError = function(obj) {\n\treturn (obj && obj.stack) ? true : false;\n};", "/**\n * Check if the value is object\n * @param {Object} value\n * @return {Boolean}\n */\nexports.isObject = function(value) {\n\ttry {\n\t\treturn (value && Object.getPrototypeOf(value) === Object.prototype) ? true : false;\n\t} catch (e) {\n\t\treturn false;\n\t}\n};", "/**\n * Get ContentType from file extension.\n * @param {String} ext File extension.\n * @return {String}\n */\nexports.getContentType = function(ext) {\n\tif (ext[0] === '.')\n\t\text = ext.substring(1);\n\treturn CONTENTTYPES[ext] || 'application/octet-stream';\n};", "/**\n * Get extension from filename\n * @param {String} filename\n * @return {String}\n */\nexports.getExtension = function(filename, raw) {\n\tvar end = filename.length;\n\tfor (var i = filename.length - 1; i > 0; i--) {\n\t\tvar c = filename[i];\n\t\tif (c === ' ' || c === '?')\n\t\t\tend = i;\n\t\telse if (c === '.') {\n\t\t\tc = filename.substring(i + 1, end);\n\t\t\treturn raw ? c : c.toLowerCase();\n\t\t}\n\t\telse if (c === '/' || c === '\\\\')\n\t\t\treturn '';\n\t}\n\treturn '';\n};", "/**\n * Get base name from path\n * @param {String} path\n * @return {String}\n */\nexports.getName = function(path) {\n\tvar l = path.length - 1;\n\tvar c = path[l];\n\tif (c === '/' || c === '\\\\')\n\t\tpath = path.substring(0, l);\n\tvar index = path.lastIndexOf('/');\n\tif (index !== -1)\n\t\treturn path.substring(index + 1);\n\tindex = path.lastIndexOf('\\\\');\n\treturn index === -1 ? path : path.substring(index + 1);\n};", "/**\n * Add a new content type to content types\n * @param {String} ext File extension.\n * @param {String} type Content type (example: application/json).\n */\nexports.setContentType = function(ext, type) {\n\tif (ext[0] === '.')\n\t\text = ext.substring(1);", "\tif (ext.length > 8) {\n\t\tvar tmp = regexpSTATIC.toString().replace(/,\\d+\\}/, ',' + ext.length + '}').substring(1);\n\t\tregexpSTATIC = new RegExp(tmp.substring(0, tmp.length - 1));\n\t}", "\tCONTENTTYPES[ext] = type;\n\treturn true;\n};", "exports.path = function(path, delimiter) {\n\tif (!path)\n\t\tpath = '';\n\tdelimiter = delimiter || '/';\n\treturn path[path.length - 1] === delimiter ? path : path + delimiter;\n};", "exports.join = function() {\n\tvar path = [''];", "\tfor (var i = 0; i < arguments.length; i++) {\n\t\tvar current = arguments[i];\n\t\tif (!current)\n\t\t\tcontinue;\n\t\tif (current[0] === '/')\n\t\t\tcurrent = current.substring(1);\n\t\tvar l = current.length - 1;\n\t\tif (current[l] === '/')\n\t\t\tcurrent = current.substring(0, l);\n\t\tpath.push(current);\n\t}", "\tpath = path.join('/');\n\treturn !isWindows ? path : path.indexOf(':') > -1 ? path.substring(1) : path;\n};", "/**\n * Prepares Windows path to UNIX like format\n * @internal\n * @param {String} path\n * @return {String}\n */\nexports.$normalize = function(path) {\n\treturn isWindows ? path.replace(regexpPATH, '/') : path;\n};", "exports.random = function(max, min) {\n\tmax = (max || 100000);\n\tmin = (min || 0);\n\treturn Math.floor(Math.random() * (max - min + 1)) + min;\n};", "function rnd() {\n\treturn Math.floor(Math.random() * 65536).toString(36);\n}", "global.GUID = exports.GUID = function(max) {\n\tmax = max || 40;\n\tvar str = '';\n\tfor (var i = 0; i < (max / 3) + 1; i++)\n\t\tstr += rnd();\n\treturn str.substring(0, max);\n};", "function validate_builder_default(name, value, entity) {", "\tvar type = typeof(value);", "\tif (entity.type === 12)\n\t\treturn value != null && type === 'object' && !(value instanceof Array);", "\tif (entity.type === 11)\n\t\treturn type === 'number';", "\t// Enum + KeyValue + Custom (8+9+10)\n\tif (entity.type > 7)\n\t\treturn value !== undefined;", "\tswitch (entity.subtype) {\n\t\tcase 'uid':\n\t\t\treturn value.isUID();\n\t\tcase 'zip':\n\t\t\treturn value.isZIP();\n\t\tcase 'email':\n\t\t\treturn value.isEmail();\n\t\tcase 'json':\n\t\t\treturn value.isJSON();\n\t\tcase 'url':\n\t\t\treturn value.isURL();\n\t\tcase 'phone':\n\t\t\treturn value.isPhone();\n\t\tcase 'base64':\n\t\t\treturn value.isBase64();\n\t}", "\tif (type === 'number')\n\t\treturn value > 0;", "\tif (type === 'string' || value instanceof Array)\n\t\treturn value.length > 0;", "\tif (type === 'boolean')\n\t\treturn value === true;", "\tif (value == null)\n\t\treturn false;", "\tif (value instanceof Date)\n\t\treturn value.toString()[0] !== 'I'; // Invalid Date", "\treturn true;\n}", "exports.validate_builder = function(model, error, schema, path, index, fields, pluspath) {", "\tvar prepare = schema.onValidate || F.onValidate || NOOP;\n\tvar current = path ? path + '.' : '';\n\tvar properties = model && model.$$keys ? model.$$keys : schema.properties;\n\tvar result;", "\tif (!pluspath)\n\t\tpluspath = '';", "\tif (model == null)\n\t\tmodel = {};", "\tfor (var i = 0; i < properties.length; i++) {", "\t\tvar name = properties[i];", "\t\tif (fields && fields.indexOf(name) === -1)\n\t\t\tcontinue;", "\t\tvar TYPE = schema.schema[name];\n\t\tif (!TYPE)\n\t\t\tcontinue;", "\t\tif (TYPE.can && !TYPE.can(model, model.$$workflow || EMPTYOBJECT))\n\t\t\tcontinue;", "\t\tvar value = model[name];\n\t\tvar type = typeof(value);\n\t\tvar prefix = schema.resourcePrefix ? (schema.resourcePrefix + name) : name;", "\t\tif (value === undefined) {\n\t\t\terror.push(pluspath + name, '@', current + name, undefined, prefix);\n\t\t\tcontinue;\n\t\t} else if (type === 'function')\n\t\t\tvalue = model[name]();", "\t\tif (TYPE.isArray) {\n\t\t\tif (TYPE.type === 7 && value instanceof Array && value.length) {\n\t\t\t\tvar nestedschema = schema.parent.collection[TYPE.raw] || GETSCHEMA(TYPE.raw);\n\t\t\t\tif (nestedschema) {\n\t\t\t\t\tfor (var j = 0, jl = value.length; j < jl; j++)\n\t\t\t\t\t\texports.validate_builder(value[j], error, nestedschema, current + name + '[' + j + ']', j, undefined, pluspath);\n\t\t\t\t} else\n\t\t\t\t\tthrow new Error('Nested schema \"{0}\" not found in \"{1}\".'.format(TYPE.raw, schema.parent.name));\n\t\t\t} else {", "\t\t\t\tif (!TYPE.required)\n\t\t\t\t\tcontinue;", "\t\t\t\tresult = TYPE.validate ? TYPE.validate(value, model) : prepare(name, value, current + name, model, schema.name, TYPE);\n\t\t\t\tif (result == null) {\n\t\t\t\t\tresult = value instanceof Array ? value.length > 0 : false;\n\t\t\t\t\tif (result == null || result === true)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}", "\t\t\t\ttype = typeof(result);\n\t\t\t\tif (type === 'string') {\n\t\t\t\t\tif (result[0] === '@')\n\t\t\t\t\t\terror.push(pluspath + name, '@', current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\t\t\telse\n\t\t\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t\t\t} else if (type === 'boolean') {\n\t\t\t\t\t!result && error.push(pluspath + name, '@', current + name, index, prefix);\n\t\t\t\t} else if (result.isValid === false)\n\t\t\t\t\terror.push(pluspath + name, result.error, current + name, index, prefix);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}", "\t\tif (TYPE.type === 7) {", "\t\t\tif (!value && !TYPE.required)\n\t\t\t\tcontinue;", "\t\t\t// Another schema\n\t\t\tresult = TYPE.validate ? TYPE.validate(value, model) : null;", "\t\t\tif (result == null) {\n\t\t\t\tvar nestedschema = schema.parent.collection[TYPE.raw] || GETSCHEMA(TYPE.raw);\n\t\t\t\tif (nestedschema)\n\t\t\t\t\texports.validate_builder(value, error, nestedschema, current + name, undefined, undefined, pluspath);\n\t\t\t\telse\n\t\t\t\t\tthrow new Error('Nested schema \"{0}\" not found in \"{1}\".'.format(TYPE.raw, schema.parent.name));\n\t\t\t} else {\n\t\t\t\ttype = typeof(result);\n\t\t\t\tif (type === 'string') {\n\t\t\t\t\tif (result[0] === '@')\n\t\t\t\t\t\terror.push(pluspath + name, '@', current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\t\t\telse\n\t\t\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t\t\t} else if (type === 'boolean') {\n\t\t\t\t\t!result && error.push(pluspath + name, '@', current + name, index, prefix);\n\t\t\t\t} else if (result.isValid === false)\n\t\t\t\t\terror.push(pluspath + name, result.error, current + name, index, prefix);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}", "\t\tif (!TYPE.required)\n\t\t\tcontinue;", "\t\tresult = TYPE.validate ? TYPE.validate(value, model) : prepare(name, value, current + name, model, schema.name, TYPE);\n\t\tif (result == null) {\n\t\t\tresult = validate_builder_default(name, value, TYPE);\n\t\t\tif (result == null || result === true)\n\t\t\t\tcontinue;\n\t\t}", "\t\ttype = typeof(result);", "\t\tif (type === 'string') {\n\t\t\tif (result[0] === '@')\n\t\t\t\terror.push(pluspath + name, '@', current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\telse\n\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t} else if (type === 'boolean') {\n\t\t\t!result && error.push(pluspath + name, '@', current + name, index, prefix);\n\t\t} else if (result.isValid === false)\n\t\t\terror.push(pluspath + name, result.error, current + name, index, prefix);\n\t}", "\treturn error;\n};", "/**\n * Combine paths\n * @return {String}\n */\nexports.combine = function() {", "\tvar p = F.directory;", "\tfor (var i = 0, length = arguments.length; i < length; i++) {\n\t\tvar v = arguments[i];\n\t\tif (!v)\n\t\t\tcontinue;\n\t\tif (v[0] === '/')\n\t\t\tv = v.substring(1);", "\t\tif (v[0] === '~')\n\t\t\tp = v.substring(1);\n\t\telse\n\t\t\tp += (p[p.length - 1] !== '/' ? '/' : '') + v;\n\t}\n\treturn exports.$normalize(p);\n};", "/**\n * Remove diacritics\n * @param {String} str\n * @return {String}\n */\nexports.removeDiacritics = function(str) {\n\treturn str.replace(regexpDiacritics, c => DIACRITICSMAP[c] || c);\n};", "/**\n * Simple XML parser\n * @param {String} xml\n * @return {Object}\n */\nexports.parseXML = function(xml, replace) {", "\tvar beg = -1;\n\tvar end = 0;\n\tvar tmp = 0;\n\tvar current = [];\n\tvar obj = {};\n\tvar from = -1;", "\twhile (true) {\n\t\tbeg = xml.indexOf('<![CDATA[', beg);\n\t\tif (beg === -1)\n\t\t\tbreak;\n\t\tend = xml.indexOf(']]>', beg + 9);\n\t\txml = xml.substring(0, beg) + xml.substring(beg + 9, end).trim().encode() + xml.substring(end + 3);\n\t\tbeg += 9;\n\t}", "\tbeg = -1;\n\tend = 0;", "\twhile (true) {", "\t\tbeg = xml.indexOf('<', beg + 1);\n\t\tif (beg === -1)\n\t\t\tbreak;", "\t\tend = xml.indexOf('>', beg + 1);\n\t\tif (end === -1)\n\t\t\tbreak;", "\t\tvar el = xml.substring(beg, end + 1);\n\t\tvar c = el[1];", "\t\tif (c === '?' || c === '/') {", "\t\t\tvar o = current.pop();", "\t\t\tif (from === -1 || o !== el.substring(2, el.length - 1))\n\t\t\t\tcontinue;", "\t\t\tvar path = (current.length ? current.join('.') + '.' : '') + o;\n\t\t\tvar value = xml.substring(from, beg).decode();", "\t\t\tif (replace)\n\t\t\t\tpath = path.replace(REG_XMLKEY, '_');", "\t\t\tif (obj[path] === undefined)\n\t\t\t\tobj[path] = value;\n\t\t\telse if (obj[path] instanceof Array)\n\t\t\t\tobj[path].push(value);\n\t\t\telse\n\t\t\t\tobj[path] = [obj[path], value];", "\t\t\tfrom = -1;\n\t\t\tcontinue;\n\t\t}", "\t\ttmp = el.indexOf(' ');\n\t\tvar hasAttributes = true;", "\t\tif (tmp === -1) {\n\t\t\ttmp = el.length - 1;\n\t\t\thasAttributes = false;\n\t\t}", "\t\tfrom = beg + el.length;", "\t\tvar isSingle = el[el.length - 2] === '/';\n\t\tvar name = el.substring(1, tmp);", "\t\tif (!isSingle)\n\t\t\tcurrent.push(name);", "\t\tif (!hasAttributes)\n\t\t\tcontinue;", "\t\tvar match = el.match(regexpXML);\n\t\tif (!match)\n\t\t\tcontinue;", "\t\tvar attr = {};\n\t\tvar length = match.length;", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\tvar index = match[i].indexOf('\"');\n\t\t\tattr[match[i].substring(0, index - 1)] = match[i].substring(index + 1, match[i].length - 1).decode();\n\t\t}", "\t\tvar k = current.join('.') + (isSingle ? '.' + name : '') + '[]';\n\t\tif (replace)\n\t\t\tk = k.replace(REG_XMLKEY, '_');\n\t\tobj[k] = attr;\n\t}", "\treturn obj;\n};", "exports.parseJSON = function(value, date) {\n\ttry {\n\t\treturn JSON.parse(value, date ? jsonparser : undefined);\n\t} catch(e) {\n\t}\n};", "exports.parseQuery = function(value) {\n\treturn F.onParseQuery(value);\n};", "function jsonparser(key, value) {\n\treturn typeof(value) === 'string' && value.isJSONDate() ? new Date(value) : value;\n}", "/**\n * Get WebSocket frame\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} code\n * @param {Buffer or String} message\n * @param {Hexa} type\n * @return {Buffer}\n */\nexports.getWebSocketFrame = function(code, message, type, compress) {\n\tvar messageBuffer = getWebSocketFrameMessageBytes(code, message);\n\tvar lengthBuffer = getWebSocketFrameLengthBytes(messageBuffer.length);\n\tvar frameBuffer = Buffer.alloc(1 + lengthBuffer.length + messageBuffer.length);\n\tframeBuffer[0] = 0x80 | type;\n\tcompress && (frameBuffer[0] |= 0x40);\n\tlengthBuffer.copy(frameBuffer, 1, 0, lengthBuffer.length);\n\tmessageBuffer.copy(frameBuffer, lengthBuffer.length + 1, 0, messageBuffer.length);\n\treturn frameBuffer;\n};", "/**\n * Get bytes of WebSocket frame message\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} code\n * @param {Buffer or String} message\n * @return {Buffer}\n */\nfunction getWebSocketFrameMessageBytes(code, message) {", "\tvar index = code ? 2 : 0;\n\tvar binary = message instanceof Int8Array || message instanceof Buffer;\n\tvar length = message.length;", "\tvar messageBuffer = Buffer.alloc(length + index);", "\tfor (var i = 0; i < length; i++) {\n\t\tif (binary)\n\t\t\tmessageBuffer[i + index] = message[i];\n\t\telse\n\t\t\tmessageBuffer[i + index] = message.charCodeAt(i);\n\t}", "\tif (code) {\n\t\tmessageBuffer[0] = code >> 8;\n\t\tmessageBuffer[1] = code;\n\t}", "\treturn messageBuffer;\n}", "/**\n * Get length of WebSocket frame\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} length\n * @return {Number}\n */\nfunction getWebSocketFrameLengthBytes(length) {\n\tvar lengthBuffer = null;", "\tif (length <= 125) {\n\t\tlengthBuffer = Buffer.alloc(1);\n\t\tlengthBuffer[0] = length;\n\t\treturn lengthBuffer;\n\t}", "\tif (length <= 65535) {\n\t\tlengthBuffer = Buffer.alloc(3);\n\t\tlengthBuffer[0] = 126;\n\t\tlengthBuffer[1] = (length >> 8) & 255;\n\t\tlengthBuffer[2] = (length) & 255;\n\t\treturn lengthBuffer;\n\t}", "\tlengthBuffer = Buffer.alloc(9);", "\tlengthBuffer[0] = 127;\n\tlengthBuffer[1] = 0x00;\n\tlengthBuffer[2] = 0x00;\n\tlengthBuffer[3] = 0x00;\n\tlengthBuffer[4] = 0x00;\n\tlengthBuffer[5] = (length >> 24) & 255;\n\tlengthBuffer[6] = (length >> 16) & 255;\n\tlengthBuffer[7] = (length >> 8) & 255;\n\tlengthBuffer[8] = (length) & 255;", "\treturn lengthBuffer;\n}", "/**\n * GPS distance in KM\n * @param {Number} lat1\n * @param {Number} lon1\n * @param {Number} lat2\n * @param {Number} lon2\n * @return {Number}\n */\nexports.distance = function(lat1, lon1, lat2, lon2) {\n\tvar R = 6371;\n\tvar dLat = (lat2 - lat1).toRad();\n\tvar dLon = (lon2 - lon1).toRad();\n\tvar a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon / 2) * Math.sin(dLon / 2);\n\tvar c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\treturn (R * c).floor(3);\n};", "function ls(path, callback, advanced, filter) {\n\tvar filelist = new FileList();\n\tvar tmp;", "\tfilelist.advanced = advanced;\n\tfilelist.onComplete = callback;", "\tif (typeof(filter) === 'string') {\n\t\ttmp = filter.toLowerCase();\n\t\tfilelist.onFilter = function(filename, is) {\n\t\t\treturn is ? true : filename.toLowerCase().indexOf(tmp) !== -1;\n\t\t};\n\t} else if (exports.isRegExp(filter)) {\n\t\ttmp = filter;\n\t\tfilelist.onFilter = function(filename, is) {\n\t\t\treturn is ? true : tmp.test(filename);\n\t\t};\n\t} else\n\t\tfilelist.onFilter = filter || null;", "\tfilelist.walk(path);\n}", "/**\n * Directory listing\n * @param {String} path Path.\n * @param {Function(files, directories)} callback Callback\n * @param {Function(filename, isDirectory) or String or RegExp} filter Custom filter (optional).\n */\nexports.ls = function(path, callback, filter) {\n\tls(path, callback, false, filter);\n};", "/**\n * Advanced Directory listing\n * @param {String} path Path.\n * @param {Function(files, directories)} callback Callback\n * @param {Function(filename ,isDirectory) or String or RegExp} filter Custom filter (optional).\n */\nexports.ls2 = function(path, callback, filter) {\n\tls(path, callback, true, filter);\n};", "DP.setTimeZone = function(timezone) {\n\tvar dt = this.toLocaleString('en-US', { timeZone: timezone, hour12: false, dateStyle: 'short', timeStyle: 'short' });\n\treturn new Date(Date.parse(dt));\n};", "DP.add = function(type, value) {", "\tvar self = this;", "\tif (type.constructor === Number)\n\t\treturn new Date(self.getTime() + (type - type % 1));", "\tif (value === undefined) {\n\t\tvar arr = type.split(' ');\n\t\ttype = arr[1];\n\t\tvalue = exports.parseInt(arr[0]);\n\t}", "\tvar dt = new Date(self.getTime());", "\tswitch(type) {\n\t\tcase 's':\n\t\tcase 'ss':\n\t\tcase 'sec':\n\t\tcase 'second':\n\t\tcase 'seconds':\n\t\t\tdt.setUTCSeconds(dt.getUTCSeconds() + value);\n\t\t\treturn dt;\n\t\tcase 'm':\n\t\tcase 'mm':\n\t\tcase 'minute':\n\t\tcase 'min':\n\t\tcase 'minutes':\n\t\t\tdt.setUTCMinutes(dt.getUTCMinutes() + value);\n\t\t\treturn dt;\n\t\tcase 'h':\n\t\tcase 'hh':\n\t\tcase 'hour':\n\t\tcase 'hours':\n\t\t\tdt.setUTCHours(dt.getUTCHours() + value);\n\t\t\treturn dt;\n\t\tcase 'd':\n\t\tcase 'dd':\n\t\tcase 'day':\n\t\tcase 'days':\n\t\t\tdt.setUTCDate(dt.getUTCDate() + value);\n\t\t\treturn dt;\n\t\tcase 'w':\n\t\tcase 'ww':\n\t\tcase 'week':\n\t\tcase 'weeks':\n\t\t\tdt.setUTCDate(dt.getUTCDate() + (value * 7));\n\t\t\treturn dt;\n\t\tcase 'M':\n\t\tcase 'MM':\n\t\tcase 'month':\n\t\tcase 'months':\n\t\t\tdt.setUTCMonth(dt.getUTCMonth() + value);\n\t\t\treturn dt;\n\t\tcase 'y':\n\t\tcase 'yyyy':\n\t\tcase 'year':\n\t\tcase 'years':\n\t\t\tdt.setUTCFullYear(dt.getUTCFullYear() + value);\n\t\t\treturn dt;\n\t}\n\treturn dt;\n};", "/**\n * Date difference\n * @param {Date/Number/String} date Optional.\n * @param {String} type Date type: minutes, seconds, hours, days, months, years\n * @return {Number}\n */\nDP.diff = function(date, type) {", "\tif (arguments.length === 1) {\n\t\ttype = date;\n\t\tdate = Date.now();\n\t} else {\n\t\tvar to = typeof(date);\n\t\tif (to === 'string')\n\t\t\tdate = Date.parse(date);\n\t\telse if (exports.isDate(date))\n\t\t\tdate = date.getTime();\n\t}", "\tvar r = this.getTime() - date;", "\tswitch (type) {\n\t\tcase 's':\n\t\tcase 'ss':\n\t\tcase 'second':\n\t\tcase 'seconds':\n\t\t\treturn Math.ceil(r / 1000);\n\t\tcase 'm':\n\t\tcase 'mm':\n\t\tcase 'minute':\n\t\tcase 'minutes':\n\t\t\treturn Math.ceil((r / 1000) / 60);\n\t\tcase 'h':\n\t\tcase 'hh':\n\t\tcase 'hour':\n\t\tcase 'hours':\n\t\t\treturn Math.ceil(((r / 1000) / 60) / 60);\n\t\tcase 'd':\n\t\tcase 'dd':\n\t\tcase 'day':\n\t\tcase 'days':\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / 24);\n\t\tcase 'M':\n\t\tcase 'MM':\n\t\tcase 'month':\n\t\tcase 'months':\n\t\t\t// avg: 28 days per month\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / (24 * 28));", "\t\tcase 'y':\n\t\tcase 'yyyy':\n\t\tcase 'year':\n\t\tcase 'years':\n\t\t\t// avg: 28 days per month\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / (24 * 28 * 12));\n\t}", "\treturn NaN;\n};", "DP.extend = function(date) {\n\tvar dt = new Date(this);\n\tvar match = date.match(regexpDATE);", "\tif (!match)\n\t\treturn dt;", "\tfor (var i = 0, length = match.length; i < length; i++) {\n\t\tvar m = match[i];\n\t\tvar arr, tmp;", "\t\tif (m.indexOf(':') !== -1) {", "\t\t\tarr = m.split(':');\n\t\t\ttmp = +arr[0];\n\t\t\ttmp >= 0 && dt.setUTCHours(tmp);", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\ttmp >= 0 && dt.setUTCMinutes(tmp);\n\t\t\t}", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\ttmp >= 0 && dt.setUTCSeconds(tmp);\n\t\t\t}", "\t\t\tcontinue;\n\t\t}", "\t\tif (m.indexOf('-') !== -1) {\n\t\t\tarr = m.split('-');", "\t\t\ttmp = +arr[0];\n\t\t\ttmp && dt.setUTCFullYear(tmp);", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\ttmp >= 0 && dt.setUTCMonth(tmp - 1);\n\t\t\t}", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\ttmp >= 0 && dt.setUTCDate(tmp);\n\t\t\t}", "\t\t\tcontinue;\n\t\t}", "\t\tif (m.indexOf('.') !== -1) {\n\t\t\tarr = m.split('.');", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\t!isNaN(tmp) && dt.setUTCFullYear(tmp);\n\t\t\t}", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\t!isNaN(tmp) && dt.setUTCMonth(tmp - 1);\n\t\t\t}", "\t\t\ttmp = +arr[0];\n\t\t\t!isNaN(tmp) && dt.setUTCDate(tmp);", "\t\t\tcontinue;\n\t\t}\n\t}", "\treturn dt;\n};", "/**\n * Compare dates\n * @param {Date} date\n * @return {Number} Results: -1 = current date is earlier than @date, 0 = current date is same as @date, 1 = current date is later than @date\n */\nDP.compare = function(date) {", "\tvar self = this;\n\tvar r = self.getTime() - date.getTime();", "\tif (r === 0)\n\t\treturn 0;", "\tif (r < 0)\n\t\treturn -1;", "\treturn 1;\n};", "/**\n * Compare two dates\n * @param {String or Date} d1\n * @param {String or Date} d2\n * @return {Number} Results: -1 = @d1 is earlier than @d2, 0 = @d1 is same as @d2, 1 = @d1 is later than @d2\n */\nDate.compare = function(d1, d2) {", "\tif (typeof(d1) === 'string')\n\t\td1 = d1.parseDate();", "\tif (typeof(d2) === 'string')\n\t\td2 = d2.parseDate();", "\treturn d1.compare(d2);\n};", "/**\n * Format datetime\n * @param {String} format\n * @return {String}\n */\nDP.format = function(format, resource) {", "\tif (!format)\n\t\treturn this.getUTCFullYear() + '-' + (this.getUTCMonth() + 1).toString().padLeft(2, '0') + '-' + this.getUTCDate().toString().padLeft(2, '0') + 'T' + this.getUTCHours().toString().padLeft(2, '0') + ':' + this.getUTCMinutes().toString().padLeft(2, '0') + ':' + this.getUTCSeconds().toString().padLeft(2, '0') + '.' + this.getUTCMilliseconds().toString().padLeft(3, '0') + 'Z';", "\tif (datetimeformat[format])\n\t\treturn datetimeformat[format](this, resource);", "\tvar key = format;\n\tvar half = false;", "\tif (format && format[0] === '!') {\n\t\thalf = true;\n\t\tformat = format.substring(1);\n\t}", "\tvar beg = '\\'+';\n\tvar end = '+\\'';\n\tvar before = [];", "\tvar ismm = false;\n\tvar isdd = false;\n\tvar isww = false;", "\tformat = format.replace(regexpDATEFORMAT, function(key) {\n\t\tswitch (key) {\n\t\t\tcase 'yyyy':\n\t\t\tcase 'YYYY':\n\t\t\t\treturn beg + 'd.getFullYear()' + end;\n\t\t\tcase 'yy':\n\t\t\tcase 'YY':\n\t\t\t\treturn beg + 'd.getFullYear().toString().substring(2)' + end;\n\t\t\tcase 'MMM':\n\t\t\t\tismm = true;\n\t\t\t\treturn beg + '(F.resource(resource, mm) || mm).substring(0, 3)' + end;\n\t\t\tcase 'MMMM':\n\t\t\t\tismm = true;\n\t\t\t\treturn beg + '(F.resource(resource, mm) || mm)' + end;\n\t\t\tcase 'MM':\n\t\t\t\treturn beg + '(d.getMonth() + 1).toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'M':\n\t\t\t\treturn beg + '(d.getMonth() + 1)' + end;\n\t\t\tcase 'ddd':\n\t\t\tcase 'DDD':\n\t\t\t\tisdd = true;\n\t\t\t\treturn beg + '(F.resource(resource, dd) || dd).substring(0, 2).toUpperCase()' + end;\n\t\t\tcase 'dddd':\n\t\t\tcase 'DDDD':\n\t\t\t\tisdd = true;\n\t\t\t\treturn beg + '(F.resource(resource, dd) || dd)' + end;\n\t\t\tcase 'dd':\n\t\t\tcase 'DD':\n\t\t\t\treturn beg + 'd.getDate().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'd':\n\t\t\tcase 'D':\n\t\t\t\treturn beg + 'd.getDate()' + end;\n\t\t\tcase 'HH':\n\t\t\tcase 'hh':\n\t\t\t\treturn beg + (half ? 'framework_utils.$pmam(d.getHours()).toString().padLeft(2, \\'0\\')' : 'd.getHours().toString().padLeft(2, \\'0\\')') + end;\n\t\t\tcase 'H':\n\t\t\tcase 'h':\n\t\t\t\treturn beg + (half ? 'framework_utils(d.getHours())' : 'd.getHours()') + end;\n\t\t\tcase 'mm':\n\t\t\t\treturn beg + 'd.getMinutes().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'm':\n\t\t\t\treturn beg + 'd.getMinutes()' + end;\n\t\t\tcase 'ss':\n\t\t\t\treturn beg + 'd.getSeconds().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 's':\n\t\t\t\treturn beg + 'd.getSeconds()' + end;\n\t\t\tcase 'w':\n\t\t\tcase 'ww':\n\t\t\t\tisww = true;\n\t\t\t\treturn beg + (key === 'ww' ? 'ww.toString().padLeft(2, \\'0\\')' : 'ww') + end;\n\t\t\tcase 'a':\n\t\t\t\tvar b = \"'PM':'AM'\";\n\t\t\t\treturn beg + '(d.getHours() >= 12 ? ' + b + ')' + end;\n\t\t}\n\t});", "\tismm && before.push('var mm = framework_utils.MONTHS[d.getMonth()];');\n\tisdd && before.push('var dd = framework_utils.DAYS[d.getDay()];');\n\tisww && before.push('var ww = new Date(+d);ww.setHours(0, 0, 0);ww.setDate(ww.getDate() + 4 - (ww.getDay() || 7));ww = Math.ceil((((ww - new Date(ww.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7);');", "\tdatetimeformat[key] = new Function('d', 'resource', before.join('\\n') + 'return \\'' + format + '\\';');\n\treturn datetimeformat[key](this, resource);\n};", "exports.$pmam = function(value) {\n\treturn value >= 12 ? value - 12 : value;\n};", "DP.toUTC = function(ticks) {\n\tvar dt = this.getTime() + this.getTimezoneOffset() * 60000;\n\treturn ticks ? dt : new Date(dt);\n};", "// +v2.2.0 parses JSON dates as dates and this is the fallback for backward compatibility\nDP.parseDate = function() {\n\treturn this;\n};", "SP.isJSONDate = function() {\n\tvar l = this.length - 1;\n\treturn l > 22 && l < 30 && this[l] === 'Z' && this[10] === 'T' && this[4] === '-' && this[13] === ':' && this[16] === ':';\n};", "SP.ROOT = function(noremap) {", "\tvar str = this;", "\tstr = str.replace(REG_NOREMAP, function() {\n\t\tnoremap = true;\n\t\treturn '';\n\t}).replace(REG_ROOT, $urlmaker);", "\tif (!noremap && CONF.default_root)\n\t\tstr = str.replace(REG_REMAP, $urlremap).replace(REG_AJAX, $urlajax);", "\treturn str;\n};", "function $urlremap(text) {\n\tvar pos = text[0] === 'h' ? 6 : 5;\n\treturn REG_URLEXT.test(text) ? text : ((text[0] === 'h' ? 'href' : 'src') + '=\"' + CONF.default_root + (text[pos] === '/' ? text.substring(pos + 1) : text));\n}", "function $urlajax(text) {\n\treturn text.substring(0, text.length - 1) + CONF.default_root;\n}", "function $urlmaker(text) {\n\tvar c = text[4];\n\treturn CONF.default_root ? CONF.default_root : (c || '');\n}", "if (!SP.trim) {\n\tSP.trim = function() {\n\t\treturn this.replace(regexpTRIM, '');\n\t};\n}", "if (!SP.replaceAt) {\n\tSP.replaceAt = function(index, character) {\n\t\treturn this.substr(0, index) + character + this.substr(index + character.length);\n\t};\n}", "/**\n * Checks if the string starts with the text\n * @see {@link http://docs.totaljs.com/SP/#SP.startsWith|Documentation}\n * @param {String} text Text to find.\n * @param {Boolean/Number} ignoreCase Ingore case sensitive or position in the string.\n * @return {Boolean}\n */\nSP.startsWith = function(text, ignoreCase) {\n\tvar self = this;\n\tvar length = text.length;\n\tvar tmp;", "\tif (ignoreCase === true) {\n\t\ttmp = self.substring(0, length);\n\t\treturn tmp.length === length && tmp.toLowerCase() === text.toLowerCase();\n\t}", "\tif (ignoreCase)\n\t\ttmp = self.substr(ignoreCase, length);\n\telse\n\t\ttmp = self.substring(0, length);", "\treturn tmp.length === length && tmp === text;\n};", "/**\n * Checks if the string ends with the text\n * @see {@link http://docs.totaljs.com/SP/#SP.endsWith|Documentation}\n * @param {String} text Text to find.\n * @param {Boolean/Number} ignoreCase Ingore case sensitive or position in the string.\n * @return {Boolean}\n */\nSP.endsWith = function(text, ignoreCase) {\n\tvar self = this;\n\tvar length = text.length;\n\tvar tmp;", "\tif (ignoreCase === true) {\n\t\ttmp = self.substring(self.length - length);\n\t\treturn tmp.length === length && tmp.toLowerCase() === text.toLowerCase();\n\t}", "\tif (ignoreCase)\n\t\ttmp = self.substr((self.length - ignoreCase) - length, length);\n\telse\n\t\ttmp = self.substring(self.length - length);", "\treturn tmp.length === length && tmp === text;\n};", "SP.replacer = function(find, text) {\n\tvar self = this;\n\tvar beg = self.indexOf(find);\n\treturn beg === -1 ? self : (self.substring(0, beg) + text + self.substring(beg + find.length));\n};", "/**\n * Hash string\n * @param {String} type Hash type.\n * @param {String} salt Optional, salt.\n * @return {String}\n */\nSP.hash = function(type, salt) {\n\tvar str = salt ? this + salt : this;\n\tswitch (type) {\n\t\tcase 'md5':\n\t\t\treturn str.md5();\n\t\tcase 'sha1':\n\t\t\treturn str.sha1();\n\t\tcase 'sha256':\n\t\t\treturn str.sha256();\n\t\tcase 'sha512':\n\t\t\treturn str.sha512();\n\t\tcase 'crc32':\n\t\t\treturn str.crc32();\n\t\tcase 'crc32unsigned':\n\t\t\treturn str.crc32(true);\n\t\tdefault:\n\t\t\tvar val = string_hash(str);\n\t\t\treturn type === true ? val >>> 0 : val;\n\t}\n};", "global.HASH = function(value, type) {\n\treturn value.hash(type ? type : true);\n};", "SP.makeid = function() {\n\treturn this.hash(true).toString(16);\n};", "SP.crc32 = function(unsigned) {\n\tvar crc = -1;\n\tfor (var i = 0, length = this.length; i < length; i++)\n\t\tcrc = (crc >>> 8) ^ CRC32TABLE[(crc ^ this.charCodeAt(i)) & 0xFF];\n\tvar val = crc ^ (-1);\n\treturn unsigned ? val >>> 0 : val;\n};", "function string_hash(s, convert) {\n\tvar hash = 0;\n\tif (s.length === 0)\n\t\treturn convert ? '' : hash;\n\tfor (var i = 0, l = s.length; i < l; i++) {\n\t\tvar char = s.charCodeAt(i);\n\t\thash = ((hash << 5) - hash) + char;\n\t\thash |= 0;\n\t}\n\treturn hash;\n}", "SP.count = function(text) {\n\tvar index = 0;\n\tvar count = 0;\n\tdo {\n\t\tindex = this.indexOf(text, index + text.length);\n\t\tif (index > 0)\n\t\t\tcount++;\n\t} while (index > 0);\n\treturn count;\n};", "SP.parseXML = function(replace) {\n\treturn F.onParseXML(this, replace);\n};", "SP.parseJSON = function(date) {\n\treturn exports.parseJSON(this, date);\n};", "SP.parseQuery = function() {\n\treturn exports.parseQuery(this);\n};", "SP.parseUA = function(structured) {", "\tvar ua = this;", "\tif (!ua)\n\t\treturn '';", "\tvar arr = ua.match(regexpUA);\n\tvar uid = '';", "\tif (arr) {", "\t\tvar data = {};", "\t\tfor (var i = 0; i < arr.length; i++) {", "\t\t\tif (arr[i] === 'like' && arr[i + 1] === 'Gecko') {\n\t\t\t\ti += 1;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tvar key = arr[i].toLowerCase();\n\t\t\tif (key === 'like')\n\t\t\t\tbreak;", "\t\t\tswitch (key) {\n\t\t\t\tcase 'linux':\n\t\t\t\tcase 'windows':\n\t\t\t\tcase 'mac':\n\t\t\t\tcase 'symbian':\n\t\t\t\tcase 'symbos':\n\t\t\t\tcase 'tizen':\n\t\t\t\tcase 'android':\n\t\t\t\t\tdata[arr[i]] = 2;\n\t\t\t\t\tif (key === 'tizen' || key === 'android')\n\t\t\t\t\t\tdata.Mobile = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'webos':\n\t\t\t\t\tdata.WebOS = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'media':\n\t\t\t\tcase 'center':\n\t\t\t\tcase 'tv':\n\t\t\t\tcase 'smarttv':\n\t\t\t\tcase 'smart':\n\t\t\t\t\tdata[arr[i]] = 5;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'iemobile':\n\t\t\t\tcase 'mobile':\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'ipad':\n\t\t\t\tcase 'ipod':\n\t\t\t\tcase 'iphone':\n\t\t\t\t\tdata.iOS = 2;\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tif (key === 'ipad')\n\t\t\t\t\t\tdata.Tablet = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'phone':\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'tizenbrowser':\n\t\t\t\tcase 'blackberry':\n\t\t\t\tcase 'mini':\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'samsungbrowser':\n\t\t\t\tcase 'chrome':\n\t\t\t\tcase 'firefox':\n\t\t\t\tcase 'msie':\n\t\t\t\tcase 'opera':\n\t\t\t\tcase 'brave':\n\t\t\t\tcase 'vivaldi':\n\t\t\t\tcase 'outlook':\n\t\t\t\tcase 'safari':\n\t\t\t\tcase 'mail':\n\t\t\t\tcase 'edge':\n\t\t\t\tcase 'maxthon':\n\t\t\t\tcase 'electron':\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'trident':\n\t\t\t\t\tdata.MSIE = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'opr':\n\t\t\t\t\tdata.Opera = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'tablet':\n\t\t\t\t\tdata.Tablet = 4;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (data.MSIE) {\n\t\t\tdata.IE = 1;\n\t\t\tdelete data.MSIE;\n\t\t}", "\t\tif (data.WebOS || data.Android)\n\t\t\tdelete data.Linux;", "\t\tif (data.IEMobile) {\n\t\t\tif (data.Android)\n\t\t\t\tdelete data.Android;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t} else if (data.MSIE) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Edge) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Opera || data.Electron) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Chrome) {\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t\tif (data.SamsungBrowser)\n\t\t\t\tdelete data.SamsungBrowser;\n\t\t} else if (data.SamsungBrowser) {\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t}", "\t\tif (structured) {\n\t\t\tvar keys = Object.keys(data);\n\t\t\tvar output = { os: '', browser: '', device: 'desktop' };", "\t\t\tif (data.Tablet)\n\t\t\t\toutput.device = 'tablet';\n\t\t\telse if (data.Mobile)\n\t\t\t\toutput.device = 'mobile';", "\t\t\tfor (var i = 0; i < keys.length; i++) {\n\t\t\t\tvar val = data[keys[i]];\n\t\t\t\tswitch (val) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\toutput.browser += (output.browser ? ' ' : '') + keys[i];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\toutput.os += (output.os ? ' ' : '') + keys[i];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\toutput.device = 'tv';\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn output;\n\t\t}", "\t\tuid = Object.keys(data).join(' ');\n\t}", "\treturn uid;\n};", "SP.parseCSV = function(delimiter) {", "\tif (!delimiter)\n\t\tdelimiter = ',';", "\tvar delimiterstring = '\"';\n\tvar t = this;\n\tvar scope;\n\tvar tmp = {};\n\tvar index = 1;\n\tvar data = [];\n\tvar current = 'a';", "\tfor (var i = 0; i < t.length; i++) {\n\t\tvar c = t[i];", "\t\tif (!scope) {", "\t\t\tif (c === '\\n' || c === '\\r') {\n\t\t\t\ttmp && data.push(tmp);\n\t\t\t\tindex = 1;\n\t\t\t\tcurrent = 'a';\n\t\t\t\ttmp = null;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (c === delimiter) {\n\t\t\t\tcurrent = String.fromCharCode(97 + index);\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (c === delimiterstring) {\n\t\t\t// Check escaped quotes\n\t\t\tif (scope && t[i + 1] === delimiterstring) {\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\tscope = c === scope ? '' : c;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (!tmp)\n\t\t\ttmp = {};", "\t\tif (tmp[current])\n\t\t\ttmp[current] += c;\n\t\telse\n\t\t\ttmp[current] = c;\n\t}", "\ttmp && data.push(tmp);\n\treturn data;\n};", "SP.parseTerminal = function(fields, fn, skip, take) {", "\tvar lines = this.split('\\n');", "\tif (typeof(fields) === 'function') {\n\t\ttake = skip;\n\t\tskip = fn;\n\t\tfn = fields;\n\t\tparseTerminal2(lines, fn, skip, take);\n\t\treturn this;\n\t}", "\tif (skip === undefined)\n\t\tskip = 0;\n\tif (take === undefined)\n\t\ttake = lines.length;", "\tvar headers = [];\n\tvar indexer = 0;\n\tvar line = lines[0];", "\tif (!line) {\n\t\tline = lines[1];\n\t\tskip++;\n\t}", "\tif (!line) {\n\t\tline = lines[2];\n\t\tskip++;\n\t}", "\tif (!line)\n\t\treturn this;", "\tvar fieldslength = fields.length;\n\tvar tmp;", "\tfor (var i = 0, length = fieldslength; i < length; i++) {\n\t\tvar field = fields[i];", "\t\tvar beg = -1;\n\t\tvar end = -1;\n\t\tvar type = typeof(field);", "\t\tif (type === 'object' && field.test) {\n\t\t\ttmp = line.match(field);\n\t\t\tif (tmp) {\n\t\t\t\tbeg = tmp.index;\n\t\t\t\tend = beg + tmp.toString().length;\n\t\t\t} else {\n\t\t\t\tbeg = -1;\n\t\t\t\tend = -1;\n\t\t\t}\n\t\t} else if (type === 'string') {\n\t\t\ttmp = line.indexOf(field);\n\t\t\tif (tmp === -1) {\n\t\t\t\tbeg = -1;\n\t\t\t\tend = -1;\n\t\t\t} else {\n\t\t\t\tbeg = tmp;\n\t\t\t\tend = line.indexOf(' ', beg + field.length);\n\t\t\t}\n\t\t}", "\t\theaders.push({ beg: beg, end: end });\n\t}", "\tfor (var i = skip + 1, length = skip + 1 + take; i < length; i++) {", "\t\tvar line = lines[i];\n\t\tif (!line)\n\t\t\tcontinue;", "\t\tvar arr = [];\n\t\tvar is = false;\n\t\tvar beg;", "\t\tfor (var j = 0; j < fieldslength; j++) {\n\t\t\tvar header = headers[j];\n\t\t\tif (header.beg !== -1) {\n\t\t\t\tis = true;\n\t\t\t\tbeg = 0;", "\t\t\t\tfor (var k = header.beg; k > -1; k--) {\n\t\t\t\t\tif (line[k] === ' ') {\n\t\t\t\t\t\tbeg = k + 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tarr.push(line.substring(beg, header.end === -1 ? undefined : header.end).trim());\n\t\t\t} else\n\t\t\t\tarr.push('');\n\t\t}", "\t\tis && fn(arr, indexer++, length, i);\n\t}", "\treturn this;\n};", "function parseTerminal2(lines, fn, skip, take) {\n\tvar indexer = 0;", "\tif (skip === undefined)\n\t\tskip = 0;\n\tif (take === undefined)\n\t\ttake = lines.length;", "\tfor (var i = skip, length = skip + take; i < length; i++) {\n\t\tvar line = lines[i];\n\t\tif (!line)\n\t\t\tcontinue;\n\t\tvar m = line.match(regexpTERMINAL);\n\t\tm && fn(m, indexer++, length, i);\n\t}\n}", "function parseDateFormat(format, val) {", "\tvar tmp = [];\n\tvar tmpformat = [];\n\tvar prev = '';\n\tvar prevformat = '';\n\tvar allowed = { y: 1, Y: 1, M: 1, m: 1, d: 1, D: 1, H: 1, s: 1, a: 1, w: 1 };", "\tfor (var i = 0; i < format.length; i++) {", "\t\tvar c = format[i];", "\t\tif (!allowed[c])\n\t\t\tcontinue;", "\t\tif (prev !== c) {\n\t\t\tprevformat && tmpformat.push(prevformat);\n\t\t\tprevformat = c;\n\t\t\tprev = c;\n\t\t} else\n\t\t\tprevformat += c;\n\t}", "\tprev = '';", "\tfor (var i = 0; i < val.length; i++) {\n\t\tvar code = val.charCodeAt(i);\n\t\tif (code >= 48 && code <= 57)\n\t\t\tprev += val[i];\n\t}", "\tprevformat && tmpformat.push(prevformat);", "\tvar f = 0;\n\tfor (var i = 0; i < tmpformat.length; i++) {\n\t\tvar l = tmpformat[i].length;\n\t\ttmp.push(prev.substring(f, f + l));\n\t\tf += l;\n\t}", "\tvar dt = {};", "\tfor (var i = 0; i < tmpformat.length; i++) {\n\t\tvar type = tmpformat[i];\n\t\tif (tmp[i])\n\t\t\tdt[type[0]] = +tmp[i];\n\t}", "\tvar h = dt.h || dt.H;", "\tif (h != null) {\n\t\tvar ampm = val.match(REG_TIME);\n\t\tif (ampm && ampm[0].toLowerCase() === 'pm')\n\t\t\th += 12;\n\t}", "\treturn new Date((dt.y || dt.Y) || 0, (dt.M || 1) - 1, dt.d || dt.D || 0, h || 0, dt.m || 0, dt.s || 0);\n}", "SP.parseDate = function(format) {", "\tif (format)\n\t\treturn parseDateFormat(format, this);", "\tvar self = this.trim();\n\tvar lc = self.charCodeAt(self.length - 1);", "\t// Classic date\n\tif (lc === 41)\n\t\treturn new Date(self);", "\t// JSON format\n\tif (lc === 90)\n\t\treturn new Date(Date.parse(self));", "\tvar arr = self.indexOf(' ') === -1 ? self.split('T') : self.split(' ');\n\tvar index = arr[0].indexOf(':');\n\tvar length = arr[0].length;", "\tif (index !== -1) {\n\t\tvar tmp = arr[1];\n\t\tarr[1] = arr[0];\n\t\tarr[0] = tmp;\n\t}", "\tif (arr[0] === undefined)\n\t\tarr[0] = '';", "\tvar noTime = arr[1] === undefined ? true : arr[1].length === 0;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar c = arr[0].charCodeAt(i);\n\t\tif (c === 45 || c === 46 || (c > 47 && c < 58))\n\t\t\tcontinue;\n\t\tif (noTime)\n\t\t\treturn new Date(self);\n\t}", "\tif (arr[1] === undefined)\n\t\tarr[1] = '00:00:00';", "\tvar firstDay = arr[0].indexOf('-') === -1;", "\tvar date = (arr[0] || '').split(firstDay ? '.' : '-');\n\tvar time = (arr[1] || '').split(':');\n\tvar parsed = [];", "\tif (date.length < 4 && time.length < 2)\n\t\treturn new Date(self);", "\tindex = (time[2] || '').indexOf('.');", "\t// milliseconds\n\tif (index !== -1) {\n\t\ttime[3] = time[2].substring(index + 1);\n\t\ttime[2] = time[2].substring(0, index);\n\t} else\n\t\ttime[3] = '0';", "\tparsed.push(+date[firstDay ? 2 : 0]); // year\n\tparsed.push(+date[1]); // month\n\tparsed.push(+date[firstDay ? 0 : 2]); // day\n\tparsed.push(+time[0]); // hours\n\tparsed.push(+time[1]); // minutes\n\tparsed.push(+time[2]); // seconds\n\tparsed.push(+time[3]); // miliseconds", "\tvar def = new Date();", "\tfor (var i = 0, length = parsed.length; i < length; i++) {\n\t\tif (isNaN(parsed[i]))\n\t\t\tparsed[i] = 0;", "\t\tvar value = parsed[i];\n\t\tif (value !== 0)\n\t\t\tcontinue;", "\t\tswitch (i) {\n\t\t\tcase 0:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getFullYear();\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getMonth() + 1;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getDate();\n\t\t\t\tbreak;\n\t\t}\n\t}", "\treturn new Date(parsed[0], parsed[1] - 1, parsed[2], parsed[3], parsed[4] - NOW.getTimezoneOffset(), parsed[5]);\n};", "SP.parseDateExpiration = function() {\n\tvar self = this;", "\tvar arr = self.split(' ');\n\tvar dt = new Date();\n\tvar length = arr.length;", "\tfor (var i = 0; i < length; i += 2) {\n\t\tvar num = arr[i].parseInt();\n\t\tif (num === 0)\n\t\t\tcontinue;\n\t\tvar type = arr[i + 1];\n\t\tif (type)\n\t\t\tdt = dt.add(type, num);\n\t}", "\treturn dt;\n};", "SP.contains = function(value, mustAll) {\n\tvar str = this;", "\tif (typeof(value) === 'string')\n\t\treturn str.indexOf(value, typeof(mustAll) === 'number' ? mustAll : 0) !== -1;", "\tfor (var i = 0, length = value.length; i < length; i++) {\n\t\tvar exists = str.indexOf(value[i]) !== -1;\n\t\tif (mustAll) {\n\t\t\tif (!exists)\n\t\t\t\treturn false;\n\t\t} else if (exists)\n\t\t\treturn true;\n\t}", "\treturn mustAll;\n};", "/**\n * Same functionality as as String.localeCompare() but this method works with latin.\n * @param {String} value\n * @return {Number}\n */\nSP.localeCompare2 = function(value) {\n\treturn COMPARER(this, value);\n};", "var configurereplace = function(text) {\n\tvar val = CONF[text.substring(1, text.length - 1)];\n\treturn val == null ? '' : val;\n};", "SP.env = function() {\n\treturn this.replace(regexpCONFIGURE, configurereplace);\n};", "/**\n * Parse configuration from a string\n * @param {Object} def\n * @onerr {Function} error handling\n * @return {Object}\n */\nSP.parseConfig = function(def, onerr) {", "\tif (typeof(def) === 'function') {\n\t\tonerr = def;\n\t\tdef = null;\n\t}", "\tvar arr = this.split('\\n');\n\tvar length = arr.length;\n\tvar obj = def ? exports.extend({}, def) : {};\n\tvar subtype;\n\tvar name;\n\tvar index;\n\tvar value;", "\tfor (var i = 0; i < length; i++) {", "\t\tvar str = arr[i];\n\t\tif (!str || str[0] === '#' || str.substring(0, 2) === '//')\n\t\t\tcontinue;", "\t\tindex = str.indexOf(':');\n\t\tif (index === -1) {\n\t\t\tindex = str.indexOf('\\t:');\n\t\t\tif (index === -1)\n\t\t\t\tcontinue;\n\t\t}", "\t\tname = str.substring(0, index).trim();\n\t\tvalue = str.substring(index + 2).trim();", "\t\tindex = name.indexOf('(');\n\t\tif (index !== -1) {\n\t\t\tsubtype = name.substring(index + 1, name.indexOf(')')).trim().toLowerCase();\n\t\t\tname = name.substring(0, index).trim();\n\t\t} else\n\t\t\tsubtype = '';", "\t\tswitch (subtype) {\n\t\t\tcase 'string':\n\t\t\t\tobj[name] = value;\n\t\t\t\tbreak;\n\t\t\tcase 'number':\n\t\t\tcase 'float':\n\t\t\tcase 'double':\n\t\t\tcase 'currency':\n\t\t\t\tobj[name] = value.isNumber(true) ? value.parseFloat2() : value.parseInt2();\n\t\t\t\tbreak;\n\t\t\tcase 'boolean':\n\t\t\tcase 'bool':\n\t\t\t\tobj[name] = (/true|on|1|enabled/i).test(value);\n\t\t\t\tbreak;\n\t\t\tcase 'config':\n\t\t\t\tobj[name] = CONF[value];\n\t\t\t\tbreak;\n\t\t\tcase 'eval':\n\t\t\tcase 'object':\n\t\t\tcase 'array':\n\t\t\t\ttry {\n\t\t\t\t\tobj[name] = new Function('return ' + value)();\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (onerr)\n\t\t\t\t\t\tonerr(e, arr[i]);\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow new Error('A value of \"{0}\" can\\'t be converted to \"{1}\": '.format(name, subtype) + e.toString());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'json':\n\t\t\t\tobj[name] = value.parseJSON(true);\n\t\t\t\tbreak;\n\t\t\tcase 'env':\n\t\t\tcase 'environment':\n\t\t\t\tobj[name] = process.env[value];\n\t\t\t\tbreak;\n\t\t\tcase 'date':\n\t\t\tcase 'time':\n\t\t\tcase 'datetime':\n\t\t\t\tobj[name] = value.parseDate();\n\t\t\t\tbreak;\n\t\t\tcase 'random':\n\t\t\t\tobj[name] = GUID((value || '0').parseInt() || 10);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tobj[name] = value;\n\t\t\t\tbreak;\n\t\t}\n\t}", "\treturn obj;\n};", "SP.format = function() {\n\tvar arg = arguments;\n\treturn this.replace(regexpSTRINGFORMAT, function(text) {\n\t\tvar value = arg[+text.substring(1, text.length - 1)];\n\t\treturn value == null ? '' : value;\n\t});\n};", "SP.encryptUID = function(key) {\n\treturn exports.encryptUID(this, key);\n};", "SP.decryptUID = function(key) {\n\treturn exports.decryptUID(this, key);\n};", "SP.encode = function() {\n\tvar output = '';\n\tfor (var i = 0, length = this.length; i < length; i++) {\n\t\tvar c = this[i];\n\t\tswitch (c) {\n\t\t\tcase '<':\n\t\t\t\toutput += '&lt;';\n\t\t\t\tbreak;\n\t\t\tcase '>':\n\t\t\t\toutput += '&gt;';\n\t\t\t\tbreak;\n\t\t\tcase '\"':\n\t\t\t\toutput += '&quot;';\n\t\t\t\tbreak;\n\t\t\tcase '\\'':\n\t\t\t\toutput += '&apos;';\n\t\t\t\tbreak;\n\t\t\tcase '&':\n\t\t\t\toutput += '&amp;';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\toutput += c;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn output;\n};", "SP.decode = function() {\n\treturn this.replace(regexpDECODE, function(s) {\n\t\tif (s.charAt(1) !== '#')\n\t\t\treturn ALPHA_INDEX[s] || s;\n\t\tvar code = s[2].toLowerCase() === 'x' ? parseInt(s.substr(3), 16) : parseInt(s.substr(2));\n\t\treturn !code || code < -32768 || code > 65535 ? '' : String.fromCharCode(code);\n\t});\n};", "SP.urlEncode = function() {\n\treturn encodeURIComponent(this);\n};", "SP.urlDecode = function() {\n\treturn decodeURIComponent(this);\n};", "SP.arg = function(obj, encode, def) {\n\tif (typeof(encode) === 'string')\n\t\tdef = encode;\n\treturn this.replace(regexpARG, function(text) {\n\t\t// Is double?\n\t\tvar l = text[1] === '{' ? 2 : 1;\n\t\tvar val = obj[text.substring(l, text.length - l).trim()];\n\t\tif (encode && encode === 'json')\n\t\t\treturn JSON.stringify(val);\n\t\treturn val == null ? (def == null ? text : def) : encode ? encode === 'html' ? (val + '').encode() : encodeURIComponent(val + '') : val;\n\t});\n};", "SP.params = function(obj) {", "\tOBSOLETE('String.params()', 'The method is deprecated instead of it use F.viewCompile() or String.format().');", "\tvar formatted = this;\n\tif (obj == null)\n\t\treturn formatted;", "\treturn formatted.replace(regexpPARAM, function(prop) {", "\t\tvar isEncode = false;\n\t\tvar name = prop.substring(2, prop.length - 2).trim();", "\t\tvar format = '';\n\t\tvar index = name.indexOf('|');", "\t\tif (index !== -1) {\n\t\t\tformat = name.substring(index + 1, name.length).trim();\n\t\t\tname = name.substring(0, index).trim();\n\t\t}", "\t\tif (name[0] === '!')\n\t\t\tname = name.substring(1);\n\t\telse\n\t\t\tisEncode = true;", "\t\tvar val;", "\t\tif (name.indexOf('.') !== -1) {\n\t\t\tvar arr = name.split('.');\n\t\t\tif (arr.length === 2) {\n\t\t\t\tif (obj[arr[0]])\n\t\t\t\t\tval = obj[arr[0]][arr[1]];\n\t\t\t} else if (arr.length === 3) {\n\t\t\t\tif (obj[arr[0]] && obj[arr[0]][arr[1]])\n\t\t\t\t\tval = obj[arr[0]][arr[1]][arr[2]];\n\t\t\t} else if (arr.length === 4) {\n\t\t\t\tif (obj[arr[0]] && obj[arr[0]][arr[1]] && obj[arr[0]][arr[1]][arr[2]])\n\t\t\t\t\tval = obj[arr[0]][arr[1]][arr[2]][arr[3]];\n\t\t\t} else if (arr.length === 5) {\n\t\t\t\tif (obj[arr[0]] && obj[arr[0]][arr[1]] && obj[arr[0]][arr[1]][arr[2]] && obj[arr[0]][arr[1]][arr[2]][arr[3]])\n\t\t\t\t\tval = obj[arr[0]][arr[1]][arr[2]][arr[3]][arr[4]];\n\t\t\t}\n\t\t} else\n\t\t\tval = name.length ? obj[name] : obj;", "\t\tif (typeof(val) === 'function')\n\t\t\tval = val(index);", "\t\tif (val === undefined)\n\t\t\treturn prop;", "\t\tif (format.length) {\n\t\t\tvar type = typeof(val);\n\t\t\tif (type === 'string') {\n\t\t\t\tvar max = +format;\n\t\t\t\tif (!isNaN(max))\n\t\t\t\t\tval = val.max(max + 3, '...');", "\t\t\t} else if (type === 'number' || exports.isDate(val)) {\n\t\t\t\tif (format.isNumber())\n\t\t\t\t\tformat = +format;\n\t\t\t\tval = val.format(format);\n\t\t\t}\n\t\t}", "\t\tval = val.toString();\n\t\treturn isEncode ? exports.encode(val) : val;\n\t});\n};", "SP.max = function(length, chars) {\n\tvar str = this;\n\tif (typeof(chars) !== 'string')\n\t\tchars = '...';\n\treturn str.length > length ? str.substring(0, length - chars.length) + chars : str;\n};", "SP.isJSON = function() {\n\tvar self = this;\n\tif (self.length <= 1)\n\t\treturn false;", "\tvar l = self.length - 1;\n\tvar a;\n\tvar b;\n\tvar i = 0;", "\twhile (true) {\n\t\ta = self[i++];\n\t\tif (a === ' ' || a === '\\n' || a === '\\r' || a === '\\t')\n\t\t\tcontinue;\n\t\tbreak;\n\t}", "\twhile (true) {\n\t\tb = self[l--];\n\t\tif (b === ' ' || b === '\\n' || b === '\\r' || b === '\\t')\n\t\t\tcontinue;\n\t\tbreak;\n\t}", "\treturn (a === '\"' && b === '\"') || (a === '[' && b === ']') || (a === '{' && b === '}') || (a.charCodeAt(0) > 47 && b.charCodeAt(0) < 57);\n};", "SP.isURL = function() {\n\treturn this.length <= 7 ? false : F.validators.url.test(this);\n};", "SP.isZIP = function() {\n\treturn F.validators.zip.test(this);\n};", "SP.isEmail = function() {\n\treturn this.length <= 4 ? false : F.validators.email.test(this);\n};", "SP.isPhone = function() {\n\treturn this.length < 6 ? false : F.validators.phone.test(this);\n};", "SP.isBase64 = function() {\n\tvar str = this;\n\treturn str.length % 4 === 0 && regexpBASE64.test(str);\n};", "SP.isUID = function() {\n\tvar str = this;", "\tif (str.length < 12)\n\t\treturn false;", "\tvar is = DEF.validators.uid.test(str);\n\tif (is) {", "\t\tvar sum;\n\t\tvar beg;\n\t\tvar end;\n\t\tvar e = str[str.length - 1];", "\t\tif (e === 'b' || e === 'c' || e === 'd') {\n\t\t\tsum = str[str.length - 2];\n\t\t\tbeg = +str[str.length - 3];\n\t\t\tend = str.length - 5;\n\t\t\tvar tmp = e === 'c' || e === 'd' ? (+str.substring(beg, end)) : parseInt(str.substring(beg, end), 16);\n\t\t\treturn sum === (tmp % 2 ? '1' : '0');\n\t\t} else if (e === 'a') {\n\t\t\tsum = str[str.length - 2];\n\t\t\tbeg = 6;\n\t\t\tend = str.length - 4;\n\t\t} else {\n\t\t\tsum = str[str.length - 1];\n\t\t\tbeg = 10;\n\t\t\tend = str.length - 4;\n\t\t}", "\t\twhile (beg++ < end) {\n\t\t\tif (str[beg] !== '0') {\n\t\t\t\tif (((+str.substring(beg, end)) % 2 ? '1' : '0') === sum)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n};", "SP.parseUID = function() {\n\tvar self = this;\n\tvar obj = {};\n\tvar hash;\n\tvar e = self[self.length - 1];", "\tif (e === 'b' || e === 'c' || e === 'd') {\n\t\tend = +self[self.length - 3];\n\t\tvar ticks = ((e === 'b' ? (+self.substring(0, end)) : parseInt(self.substring(0, end), e=== 'd' ? 36 : 16)) * 1000 * 60) + 1580511600000; // 1.1.2020\n\t\tobj.date = new Date(ticks);\n\t\tbeg = end;\n\t\tend = self.length - 5;\n\t\thash = +self.substring(end + 3, end + 4);\n\t\tobj.century = Math.floor((obj.date.getFullYear() - 1) / 100) + 1;\n\t\tobj.hash = self.substring(end, end + 2);\n\t} else if (e === 'a') {\n\t\tvar ticks = ((+self.substring(0, 6)) * 1000 * 60) + 1548975600000; // old 1.1.2019\n\t\tobj.date = new Date(ticks);\n\t\tbeg = 7;\n\t\tend = self.length - 4;\n\t\thash = +self.substring(end + 2, end + 3);\n\t\tobj.century = Math.floor((obj.date.getFullYear() - 1) / 100) + 1;\n\t\tobj.hash = self.substring(end, end + 2);\n\t} else {\n\t\tvar y = self.substring(0, 2);\n\t\tvar M = self.substring(2, 4);\n\t\tvar d = self.substring(4, 6);\n\t\tvar H = self.substring(6, 8);\n\t\tvar m = self.substring(8, 10);", "\t\tobj.date = new Date(+('20' + y), (+M) - 1, +d, +H, +m, 0);", "\t\tvar beg = 0;\n\t\tvar end = 0;\n\t\tvar index = 10;", "\t\twhile (true) {", "\t\t\tvar c = self[index];", "\t\t\tif (!c)\n\t\t\t\tbreak;", "\t\t\tif (!beg && c !== '0')\n\t\t\t\tbeg = index;", "\t\t\tif (c.charCodeAt(0) > 96) {\n\t\t\t\tend = index;\n\t\t\t\tbreak;\n\t\t\t}", "\t\t\tindex++;\n\t\t}", "\t\tobj.century = self.substring(end + 4);", "\t\tif (obj.century) {\n\t\t\tobj.century = 20 + (+obj.century);\n\t\t\tobj.date.setYear(obj.date.getFullYear() + 100);\n\t\t} else\n\t\t\tobj.century = 21;", "\t\thash = +self.substring(end + 3, end + 4);\n\t\tobj.hash = self.substring(end, end + 3);\n\t}", "\tobj.index = +self.substring(beg, end);\n\tobj.valid = (obj.index % 2 ? 1 : 0) === hash;\n\treturn obj;\n};", "SP.parseENV = function() {", "\tvar arr = this.split(regexpLINES);\n\tvar obj = {};", "\tfor (var i = 0; i < arr.length; i++) {\n\t\tvar line = arr[i];\n\t\tif (!line || line.substring(0, 2) === '//' || line[0] === '#')\n\t\t\tcontinue;", "\t\tvar index = line.indexOf('=');\n\t\tif (index === -1)\n\t\t\tcontinue;", "\t\tvar key = line.substring(0, index);\n\t\tvar val = line.substring(index + 1).replace(/\\\\n/g, '\\n');\n\t\tvar end = val.length - 1;", "\t\tif ((val[0] === '\"' && val[end] === '\"') || (val[0] === '\\'' && val[end] === '\\''))\n\t\t\tval = val.substring(1, end);\n\t\telse\n\t\t\tval = val.trim();", "\t\tobj[key] = val;\n\t}", "\treturn obj;\n};", "SP.parseInt = function(def) {\n\tvar str = this.trim();\n\tvar num = +str;\n\treturn isNaN(num) ? (def === undefined ? 0 : def) : num;\n};", "SP.parseInt2 = function(def) {\n\tvar num = this.match(regexpINTEGER);\n\treturn num ? +num[0] : (def === undefined ? 0 : def);\n};", "SP.parseFloat2 = function(def) {\n\tvar num = this.match(regexpFLOAT);\n\treturn num ? +num[0].toString().replace(/,/g, '.') : (def === undefined ? 0 : def);\n};", "SP.parseBool = SP.parseBoolean = function() {\n\tvar self = this.toLowerCase();\n\treturn self === 'true' || self === '1' || self === 'on';\n};", "SP.parseFloat = function(def) {\n\tvar str = this.trim();\n\tif (str.indexOf(',') !== -1)\n\t\tstr = str.replace(',', '.');\n\tvar num = +str;\n\treturn isNaN(num) ? (def === undefined ? 0 : def) : num;\n};", "SP.capitalize = function(first) {", "\tif (first)\n\t\treturn (this[0] || '').toUpperCase() + this.substring(1);", "\tvar builder = '';\n\tvar c;", "\tfor (var i = 0, length = this.length; i < length; i++) {\n\t\tvar c = this[i - 1];\n\t\tif (!c || (c === ' ' || c === '\\t' || c === '\\n'))\n\t\t\tc = this[i].toUpperCase();\n\t\telse\n\t\t\tc = this[i];\n\t\tbuilder += c;\n\t}", "\treturn builder;\n};", "SP.toUnicode = function() {\n\tvar output = '';\n\tfor (var i = 0; i < this.length; i++) {\n\t\tvar c = this[i].charCodeAt(0);\n\t\tif(c > 126 || c < 32)\n\t\t\toutput += '\\\\u' + ('000' + c.toString(16)).substr(-4);\n\t\telse\n\t\t\toutput += this[i];\n\t}\n\treturn output;\n};", "SP.fromUnicode = function() {\n\tvar output = '';\n\tfor (var i = 0; i < this.length; i++) {\n\t\tif (this[i] === '\\\\' && this[i + 1] === 'u') {\n\t\t\toutput += String.fromCharCode(parseInt(this[i + 2] + this[i + 3] + this[i + 4] + this[i + 5], 16));\n\t\t\ti += 5;\n\t\t} else\n\t\t\toutput += this[i];\n\t}\n\treturn output;\n};", "SP.sha1 = function(salt) {\n\tvar hash = Crypto.createHash('sha1');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.sha256 = function(salt) {\n\tvar hash = Crypto.createHash('sha256');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.sha512 = function(salt) {\n\tvar hash = Crypto.createHash('sha512');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.md5 = function(salt) {\n\tvar hash = Crypto.createHash('md5');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.toSearch = function() {\n\tvar str = this.replace(regexpSEARCH, '').trim().toLowerCase().removeDiacritics();\n\tvar buf = [];\n\tvar prev = '';\n\tfor (var i = 0, length = str.length; i < length; i++) {\n\t\tvar c = str[i];\n\t\tif (c === 'y')\n\t\t\tc = 'i';\n\t\tif (c === prev)\n\t\t\tcontinue;\n\t\tprev = c;\n\t\tbuf.push(c);\n\t}", "\treturn buf.join('');\n};", "SP.toKeywords = SP.keywords = function(forSearch, alternative, max_count, max_length, min_length) {\n\treturn exports.keywords(this, forSearch, alternative, max_count, max_length, min_length);\n};", "function checksum(val) {\n\tvar sum = 0;\n\tfor (var i = 0; i < val.length; i++)\n\t\tsum += val.charCodeAt(i);\n\treturn sum;\n}", "SP.encrypt = function(key, isUnique, secret) {\n\tvar str = '0' + this;\n\tvar data_count = str.length;\n\tvar key_count = key.length;\n\tvar random = isUnique ? exports.random(120) + 40 : 65;\n\tvar count = data_count + (random % key_count);\n\tvar values = [];\n\tvar index = 0;", "\tvalues[0] = String.fromCharCode(random);", "\tvar counter = this.length + key.length;", "\tfor (var i = count - 1; i > 0; i--) {\n\t\tindex = str.charCodeAt(i % data_count);\n\t\tvalues[i] = String.fromCharCode(index ^ (key.charCodeAt(i % key_count) ^ random));\n\t}", "\tstr = Buffer.from(counter + '=' + values.join(''), ENCODING).toString('hex');\n\tvar sum = 0;", "\tfor (var i = 0; i < str.length; i++)\n\t\tsum += str.charCodeAt(i);", "\treturn (sum + checksum((secret || CONF.secret) + key)) + '-' + str;\n};", "SP.decrypt = function(key, secret) {", "\tvar index = this.indexOf('-');\n\tif (index === -1)\n\t\treturn null;", "\tvar cs = +this.substring(0, index);\n\tif (!cs || isNaN(cs))\n\t\treturn null;", "\tvar hash = this.substring(index + 1);\n\tvar sum = checksum((secret || CONF.secret) + key);\n\tfor (var i = 0; i < hash.length; i++)\n\t\tsum += hash.charCodeAt(i);", "\tif (sum !== cs)\n\t\treturn null;", "\tvar values = Buffer.from(hash, 'hex').toString(ENCODING);\n\tvar index = values.indexOf('=');\n\tif (index === -1)\n\t\treturn null;", "\tvar counter = +values.substring(0, index);\n\tif (isNaN(counter))\n\t\treturn null;", "\tvalues = values.substring(index + 1);", "\tvar count = values.length;\n\tvar random = values.charCodeAt(0);\n\tvar key_count = key.length;\n\tvar data_count = count - (random % key_count);\n\tvar decrypt_data = [];", "\tfor (var i = data_count - 1; i > 0; i--) {\n\t\tindex = values.charCodeAt(i) ^ (random ^ key.charCodeAt(i % key_count));\n\t\tdecrypt_data[i] = String.fromCharCode(index);\n\t}", "\tvar val = decrypt_data.join('');\n\treturn counter !== (val.length + key.length) ? null : val;\n};", "exports.encryptUID = function(val, key) {", "\tvar num = typeof(val) === 'number';\n\tvar sum = 0;", "\tif (!key)\n\t\tkey = CONF.secret;", "\tval = val + '';", "\tfor (var i = 0; i < val.length; i++)\n\t\tsum += val.charCodeAt(i);", "\tfor (var i = 0; i < key.length; i++)\n\t\tsum += key.charCodeAt(i);", "\treturn (num ? 'n' : 'x') + (CONF.secret_uid + val + sum + key).crc32(true).toString(16) + 'x' + val;\n};", "exports.decryptUID = function(val, key) {\n\tvar num = val[0] === 'n';\n\tvar raw = val.substring(val.indexOf('x', 1) + 1);", "\tif (num)\n\t\traw = +raw;", "\treturn exports.encryptUID(raw, key) === val ? raw : null;\n};", "SP.base64ToFile = function(filename, callback) {\n\tvar self = this;\n\tvar index = self.indexOf(',');\n\tif (index === -1)\n\t\tindex = 0;\n\telse\n\t\tindex++;\n\tFs.writeFile(filename, self.substring(index), 'base64', callback || exports.noop);\n\treturn this;\n};", "SP.base64ToBuffer = function() {\n\tvar self = this;", "\tvar index = self.indexOf(',');\n\tif (index === -1)\n\t\tindex = 0;\n\telse\n\t\tindex++;", "\treturn Buffer.from(self.substring(index), 'base64');\n};", "SP.base64ContentType = function() {\n\tvar self = this;\n\tvar index = self.indexOf(';');\n\treturn index === -1 ? '' : self.substring(5, index);\n};", "SP.removeDiacritics = function() {\n\treturn exports.removeDiacritics(this);\n};", "SP.indent = function(max, c) {\n\tvar plus = '';\n\tif (c === undefined)\n\t\tc = ' ';\n\twhile (max--)\n\t\tplus += c;\n\treturn plus + this;\n};", "SP.isNumber = function(isDecimal) {", "\tvar self = this;\n\tvar length = self.length;", "\tif (!length)\n\t\treturn false;", "\tisDecimal = isDecimal || false;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar ascii = self.charCodeAt(i);", "\t\tif (isDecimal) {\n\t\t\tif (ascii === 44 || ascii === 46) {\n\t\t\t\tisDecimal = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (ascii < 48 || ascii > 57)\n\t\t\treturn false;\n\t}", "\treturn true;\n};", "if (!SP.padLeft) {\n\tSP.padLeft = function(max, c) {\n\t\tvar self = this;\n\t\tvar len = max - self.length;\n\t\tif (len < 0)\n\t\t\treturn self;\n\t\tif (c === undefined)\n\t\t\tc = ' ';\n\t\twhile (len--)\n\t\t\tself = c + self;\n\t\treturn self;\n\t};\n}", "\nif (!SP.padRight) {\n\tSP.padRight = function(max, c) {\n\t\tvar self = this;\n\t\tvar len = max - self.length;\n\t\tif (len < 0)\n\t\t\treturn self;\n\t\tif (c === undefined)\n\t\t\tc = ' ';\n\t\twhile (len--)\n\t\t\tself += c;\n\t\treturn self;\n\t};\n}", "SP.insert = function(index, value) {\n\tvar str = this;\n\tvar a = str.substring(0, index);\n\tvar b = value.toString() + str.substring(index);\n\treturn a + b;\n};", "/**\n * Create a link from String\n * @param {Number} max A maximum length, default: 60 and optional.\n * @return {String}\n */\nSP.slug = SP.toSlug = SP.toLinker = SP.linker = function(max) {\n\tmax = max || 60;", "\tvar self = this.trim().toLowerCase().removeDiacritics();\n\tvar builder = '';\n\tvar length = self.length;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar c = self[i];\n\t\tvar code = self.charCodeAt(i);", "\t\tif (code > 540){\n\t\t\tbuilder = '';\n\t\t\tbreak;\n\t\t}", "\t\tif (builder.length >= max)\n\t\t\tbreak;", "\t\tif (code > 31 && code < 48) {\n\t\t\tif (builder[builder.length - 1] !== '-')\n\t\t\t\tbuilder += '-';\n\t\t\tcontinue;\n\t\t}", "\t\tif ((code > 47 && code < 58) || (code > 94 && code < 123))\n\t\t\tbuilder += c;\n\t}", "\tif (builder.length > 1) {\n\t\tlength = builder.length - 1;\n\t\treturn builder[length] === '-' ? builder.substring(0, length) : builder;\n\t} else if (!length)\n\t\treturn '';", "\tlength = self.length;\n\tself = self.replace(/\\s/g, '');\n\tbuilder = self.crc32(true).toString(36) + '';\n\treturn self[0].charCodeAt(0).toString(32) + builder + self[self.length - 1].charCodeAt(0).toString(32) + length;\n};", "SP.pluralize = function(zero, one, few, other) {\n\treturn this.parseInt().pluralize(zero, one, few, other);\n};", "SP.isBoolean = function() {\n\tvar self = this.toLowerCase();\n\treturn (self === 'true' || self === 'false') ? true : false;\n};", "/**\n * Check if the string contains only letters and numbers.\n * @return {Boolean}\n */\nSP.isAlphaNumeric = function() {\n\treturn regexpALPHA.test(this);\n};", "SP.soundex = function() {", "\tvar arr = this.toLowerCase().split('');\n\tvar first = arr.shift();\n\tvar builder = first.toUpperCase();", "\tfor (var i = 0, length = arr.length; i < length; i++) {\n\t\tvar v = SOUNDEX[arr[i]];\n\t\tif (v === undefined)\n\t\t\tcontinue;\n\t\tif (i) {\n\t\t\tif (v !== arr[i - 1])\n\t\t\t\tbuilder += v;\n\t\t} else if (v !== SOUNDEX[first])\n\t\t\tbuilder += v;\n\t}", "\treturn (builder + '000').substring(0, 4);\n};", "/**\n* Remove all Html Tags from a string\n* @return {string}\n*/\nSP.removeTags = function() {\n\treturn this.replace(regexpTags, '');\n};", "NP.floor = function(decimals) {\n\treturn Math.floor(this * Math.pow(10, decimals)) / Math.pow(10, decimals);\n};", "NP.fixed = function(decimals) {\n\treturn +this.toFixed(decimals);\n};", "NP.padLeft = function(max, c) {\n\treturn this.toString().padLeft(max, c || '0');\n};", "NP.padRight = function(max, c) {\n\treturn this.toString().padRight(max, c || '0');\n};", "NP.round = function(precision) {\n\tvar m = Math.pow(10, precision) || 1;\n\treturn Math.round(this * m) / m;\n};", "NP.currency = function(currency, a, b, c) {\n\tvar curr = DEF.currencies[currency];\n\treturn curr ? curr(this, a, b, c) : this.format(2);\n};", "/**\n * Async decrements\n * @param {Function(index, next)} fn\n * @param {Function} callback\n * @return {Number}\n */\nNP.async = function(fn, callback) {\n\tvar number = this;\n\tif (number)\n\t\tfn(number--, () => setImmediate(() => number.async(fn, callback)));\n\telse\n\t\tcallback && callback();\n\treturn number;\n};", "/**\n * Format number\n * @param {Number} decimals Maximum decimal numbers\n * @param {String} separator Number separator, default ' '\n * @param {String} separatorDecimal Decimal separator, default '.' if number separator is ',' or ' '.\n * @return {String}\n */\nNP.format = function(decimals, separator, separatorDecimal) {", "\tvar self = this;", "\tif (typeof(decimals) === 'string')\n\t\treturn self.format2(decimals);", "\tvar num = self.toString();\n\tvar dec = '';\n\tvar output = '';\n\tvar minus = num[0] === '-' ? '-' : '';\n\tif (minus)\n\t\tnum = num.substring(1);", "\tvar index = num.indexOf('.');", "\tif (typeof(decimals) === 'string') {\n\t\tvar tmp = separator;\n\t\tseparator = decimals;\n\t\tdecimals = tmp;\n\t}", "\tif (separator === undefined)\n\t\tseparator = ' ';", "\tif (index !== -1) {\n\t\tdec = num.substring(index + 1);\n\t\tnum = num.substring(0, index);\n\t}", "\tindex = -1;\n\tfor (var i = num.length - 1; i >= 0; i--) {\n\t\tindex++;\n\t\tif (index > 0 && index % 3 === 0)\n\t\t\toutput = separator + output;\n\t\toutput = num[i] + output;\n\t}", "\tif (decimals || dec.length) {\n\t\tif (dec.length > decimals)\n\t\t\tdec = dec.substring(0, decimals || 0);\n\t\telse\n\t\t\tdec = dec.padRight(decimals || 0, '0');\n\t}", "\tif (dec.length && separatorDecimal === undefined)\n\t\tseparatorDecimal = separator === '.' ? ',' : '.';", "\treturn minus + output + (dec.length ? separatorDecimal + dec : '');\n};", "NP.add = function(value, decimals) {", "\tif (value == null)\n\t\treturn this;", "\tif (typeof(value) === 'number')\n\t\treturn this + value;", "\tvar first = value.charCodeAt(0);\n\tvar is = false;", "\tif (first < 48 || first > 57) {\n\t\tis = true;\n\t\tvalue = value.substring(1);\n\t}", "\tvar length = value.length;\n\tvar num;", "\tif (value[length - 1] === '%') {\n\t\tvalue = value.substring(0, length - 1);\n\t\tif (is) {\n\t\t\tvar val = value.parseFloat();\n\t\t\tswitch (first) {\n\t\t\t\tcase 42:\n\t\t\t\t\tnum = this * ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 43:\n\t\t\t\t\tnum = this + ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 45:\n\t\t\t\t\tnum = this - ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 47:\n\t\t\t\t\tnum = this / ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn decimals !== undefined ? num.floor(decimals) : num;\n\t\t} else {\n\t\t\tnum = (this / 100) * value.parseFloat();\n\t\t\treturn decimals !== undefined ? num.floor(decimals) : num;\n\t\t}", "\t} else\n\t\tnum = value.parseFloat();", "\tswitch (first) {\n\t\tcase 42:\n\t\t\tnum = this * num;\n\t\t\tbreak;\n\t\tcase 43:\n\t\t\tnum = this + num;\n\t\t\tbreak;\n\t\tcase 45:\n\t\t\tnum = this - num;\n\t\t\tbreak;\n\t\tcase 47:\n\t\t\tnum = this / num;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tnum = this;\n\t\t\tbreak;\n\t}", "\tif (decimals !== undefined)\n\t\treturn num.floor(decimals);", "\treturn num;\n};", "NP.format2 = function(format) {\n\tvar index = 0;\n\tvar num = this.toString();\n\tvar beg = 0;\n\tvar end = 0;\n\tvar max = 0;\n\tvar output = '';\n\tvar length = 0;", "\tif (typeof(format) === 'string') {", "\t\tvar d = false;\n\t\tlength = format.length;", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\tvar c = format[i];\n\t\t\tif (c === '#') {\n\t\t\t\tif (d)\n\t\t\t\t\tend++;\n\t\t\t\telse\n\t\t\t\t\tbeg++;\n\t\t\t}", "\t\t\tif (c === '.')\n\t\t\t\td = true;\n\t\t}", "\t\tvar strBeg = num;\n\t\tvar strEnd = '';", "\t\tindex = num.indexOf('.');", "\t\tif (index !== -1) {\n\t\t\tstrBeg = num.substring(0, index);\n\t\t\tstrEnd = num.substring(index + 1);\n\t\t}", "\t\tif (strBeg.length > beg) {\n\t\t\tmax = strBeg.length - beg;\n\t\t\tvar tmp = '';\n\t\t\tfor (var i = 0; i < max; i++)\n\t\t\t\ttmp += '#';", "\t\t\tformat = tmp + format;\n\t\t}", "\t\tif (strBeg.length < beg)\n\t\t\tstrBeg = strBeg.padLeft(beg, ' ');", "\t\tif (strEnd.length < end)\n\t\t\tstrEnd = strEnd.padRight(end, '0');", "\t\tif (strEnd.length > end)\n\t\t\tstrEnd = strEnd.substring(0, end);", "\t\td = false;\n\t\tindex = 0;", "\t\tvar skip = true;\n\t\tlength = format.length;", "\t\tfor (var i = 0; i < length; i++) {", "\t\t\tvar c = format[i];", "\t\t\tif (c !== '#') {", "\t\t\t\tif (skip)\n\t\t\t\t\tcontinue;", "\t\t\t\tif (c === '.') {\n\t\t\t\t\td = true;\n\t\t\t\t\tindex = 0;\n\t\t\t\t}", "\t\t\t\toutput += c;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tvar value = d ? strEnd[index] : strBeg[index];", "\t\t\tif (skip)\n\t\t\t\tskip = [',', ' '].indexOf(value) !== -1;", "\t\t\tif (!skip)\n\t\t\t\toutput += value;", "\t\t\tindex++;\n\t\t}", "\t\treturn output;\n\t}", "\toutput = '### ### ###';\n\tbeg = num.indexOf('.');\n\tmax = format || 0;", "\tif (max === 0 && beg !== -1)\n\t\tmax = num.length - (beg + 1);", "\tif (max > 0) {\n\t\toutput += '.';\n\t\tfor (var i = 0; i < max; i++)\n\t\t\toutput += '#';\n\t}", "\treturn this.format(output);\n};", "NP.pluralize = function(zero, one, few, other) {", "\tvar num = this;\n\tvar value = '';", "\tif (num == 0)\n\t\tvalue = zero || '';\n\telse if (num == 1)\n\t\tvalue = one || '';\n\telse if (num > 1 && num < 5)\n\t\tvalue = few || '';\n\telse\n\t\tvalue = other;", "\tvar beg = value.indexOf('#');\n\tif (beg === -1)\n\t\treturn value;", "\tvar end = value.lastIndexOf('#');\n\tvar format = value.substring(beg, end + 1);\n\treturn num.format(format) + value.replace(format, '');\n};", "NP.hex = function(length) {\n\tvar str = this.toString(16).toUpperCase();\n\twhile(str.length < length)\n\t\tstr = '0' + str;\n\treturn str;\n};", "NP.VAT = function(percentage, decimals, includedVAT) {\n\tvar num = this;\n\tvar type = typeof(decimals);", "\tif (type === 'boolean') {\n\t\tvar tmp = includedVAT;\n\t\tincludedVAT = decimals;\n\t\tdecimals = tmp;\n\t\ttype = typeof(decimals);\n\t}", "\tif (type === 'undefined')\n\t\tdecimals = 2;", "\tif (includedVAT === undefined)\n\t\tincludedVAT = true;", "\tif (!percentage || !num)\n\t\treturn num;\n\treturn includedVAT ? (num / ((percentage / 100) + 1)).round(decimals) : (num * ((percentage / 100) + 1)).round(decimals);\n};", "NP.discount = function(percentage, decimals) {\n\tvar num = this;\n\tif (decimals === undefined)\n\t\tdecimals = 2;\n\treturn (num - (num / 100) * percentage).floor(decimals);\n};", "NP.parseDate = function(plus) {\n\treturn new Date(this + (plus || 0));\n};", "if (!NP.toRad) {\n\tNP.toRad = function () {\n\t\treturn this * Math.PI / 180;\n\t};\n}", "\nNP.filesize = function(decimals, type) {", "\tif (typeof(decimals) === 'string') {\n\t\tvar tmp = type;\n\t\ttype = decimals;\n\t\tdecimals = tmp;\n\t}", "\tvar value;", "\t// this === bytes\n\tswitch (type) {\n\t\tcase 'bytes':\n\t\t\tvalue = this;\n\t\t\tbreak;\n\t\tcase 'KB':\n\t\t\tvalue = this / 1024;\n\t\t\tbreak;\n\t\tcase 'MB':\n\t\t\tvalue = filesizehelper(this, 2);\n\t\t\tbreak;\n\t\tcase 'GB':\n\t\t\tvalue = filesizehelper(this, 3);\n\t\t\tbreak;\n\t\tcase 'TB':\n\t\t\tvalue = filesizehelper(this, 4);\n\t\t\tbreak;\n\t\tdefault:", "\t\t\ttype = 'bytes';\n\t\t\tvalue = this;", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'KB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'MB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'GB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'TB';\n\t\t\t}", "\t\t\tbreak;\n\t}", "\ttype = ' ' + type;\n\treturn (decimals === undefined ? value.format(2).replace('.00', '') : value.format(decimals)) + type;\n};", "function filesizehelper(number, count) {\n\twhile (count--) {\n\t\tnumber = number / 1024;\n\t\tif (number.toFixed(3) === '0.000')\n\t\t\treturn 0;\n\t}\n\treturn number;\n}", "var AP = Array.prototype;", "/**\n * Take items from array\n * @param {Number} count\n * @return {Array}\n */\nAP.take = function(count) {\n\tvar arr = [];\n\tvar self = this;\n\tvar length = self.length;\n\tfor (var i = 0; i < length; i++) {\n\t\tarr.push(self[i]);\n\t\tif (arr.length >= count)\n\t\t\treturn arr;\n\t}\n\treturn arr;\n};", "/**\n * Extend objects in Array\n * @param {Object} obj\n * @param {Boolean} rewrite Default: false.\n * @return {Array} Returns self\n */\nAP.extend = function(obj, rewrite) {\n\tvar isFn = typeof(obj) === 'function';\n\tfor (var i = 0, length = this.length; i < length; i++) {\n\t\tif (isFn)\n\t\t\tthis[i] = obj(this[i], i);\n\t\telse\n\t\t\tthis[i] = exports.extend(this[i], obj, rewrite);\n\t}\n\treturn this;\n};", "/**\n * First item in array\n * @param {Object} def Default value.\n * @return {Object}\n */\nAP.first = function(def) {\n\tvar item = this[0];\n\treturn item === undefined ? def : item;\n};", "/**\n * Create object from Array\n * @param {String} name Optional, property name.\n * @return {Object}\n */\nAP.toObject = function(name) {", "\tvar self = this;\n\tvar obj = {};", "\tfor (var i = 0, length = self.length; i < length; i++) {\n\t\tvar item = self[i];\n\t\tif (name)\n\t\t\tobj[item[name]] = item;\n\t\telse\n\t\t\tobj[item] = true;\n\t}", "\treturn obj;\n};", "/**\n * Compare two arrays\n * @param {String} id An identificator.\n * @param {Array} b Second array.\n * @param {Function(itemA, itemB, indexA, indexB)} executor\n */\nAP.compare = function(id, b, executor) {", "\tvar a = this;\n\tvar ak = {};\n\tvar bk = {};\n\tvar al = a.length;\n\tvar bl = b.length;\n\tvar tl = Math.max(al, bl);\n\tvar processed = {};", "\tfor (var i = 0; i < tl; i++) {\n\t\tvar av = a[i];\n\t\tif (av)\n\t\t\tak[av[id]] = i;\n\t\tvar bv = b[i];\n\t\tif (bv)\n\t\t\tbk[bv[id]] = i;\n\t}", "\tvar index = -1;", "\tfor (var i = 0; i < tl; i++) {", "\t\tvar av = a[i];\n\t\tvar bv = b[i];\n\t\tvar akk;\n\t\tvar bkk;", "\t\tif (av) {\n\t\t\takk = av[id];\n\t\t\tif (processed[akk])\n\t\t\t\tcontinue;\n\t\t\tprocessed[akk] = true;\n\t\t\tindex = bk[akk];\n\t\t\tif (index === undefined)\n\t\t\t\texecutor(av, undefined, i, -1);\n\t\t\telse\n\t\t\t\texecutor(av, b[index], i, index);\n\t\t}", "\t\tif (bv) {\n\t\t\tbkk = bv[id];\n\t\t\tif (processed[bkk])\n\t\t\t\tcontinue;\n\t\t\tprocessed[bkk] = true;\n\t\t\tindex = ak[bkk];\n\t\t\tif (index === undefined)\n\t\t\t\texecutor(undefined, bv, -1, i);\n\t\t\telse\n\t\t\t\texecutor(a[index], bv, index, i);\n\t\t}\n\t}", "\tOBSOLETE('Array.compare()', 'Use U.diff() insteadof Array.compare()');\n};", "/**\n * Pair arrays\n * @param {Array} arr\n * @param {String} property\n * @param {Function(itemA, itemB)} fn Paired items (itemA == this, itemB == arr)\n * @param {Boolean} remove Optional, remove item from this array if the item doesn't exist int arr (default: false).\n * @return {Array}\n */\nAP.pair = function(property, arr, fn, remove) {", "\tif (property instanceof Array) {\n\t\tvar tmp = property;\n\t\tproperty = arr;\n\t\tarr = tmp;\n\t}", "\tif (!arr)\n\t\tarr = new Array(0);", "\tvar length = arr.length;\n\tvar index = 0;", "\twhile (true) {\n\t\tvar item = this[index++];\n\t\tif (!item)\n\t\t\tbreak;", "\t\tvar is = false;", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\tif (item[property] !== arr[i][property])\n\t\t\t\tcontinue;\n\t\t\tfn(item, arr[i]);\n\t\t\tis = true;\n\t\t\tbreak;\n\t\t}", "\t\tif (is || !remove)\n\t\t\tcontinue;", "\t\tindex--;\n\t\tthis.splice(index, 1);\n\t}", "\tOBSOLETE('Array.pair()', 'The method will be removed in Total.js v4');\n\treturn this;\n};", "/**\n * Last item in array\n * @param {Object} def Default value.\n * @return {Object}\n */\nAP.last = function(def) {\n\tvar item = this[this.length - 1];\n\treturn item === undefined ? def : item;\n};", "AP.quicksort = AP.orderBy = function(name, asc) {", "\tvar length = this.length;\n\tif (!length || length === 1)\n\t\treturn this;", "\tif (typeof(name) === 'boolean') {\n\t\tasc = name;\n\t\tname = undefined;\n\t} else if (asc === undefined)\n\t\tasc = true;\n\telse {\n\t\tswitch (asc) {\n\t\t\tcase 'asc':\n\t\t\tcase 'ASC':\n\t\t\t\tasc = true;\n\t\t\t\tbreak;\n\t\t\tcase 'desc':\n\t\t\tcase 'DESC':\n\t\t\t\tasc = false;\n\t\t\t\tbreak;\n\t\t}\n\t}", "\tvar self = this;\n\tvar type = 0;\n\tvar field = name ? self[0][name] : self[0];", "\tswitch (typeof(field)) {\n\t\tcase 'string':\n\t\t\tif (field.isJSONDate())\n\t\t\t\ttype = 4;\n\t\t\telse\n\t\t\t\ttype = 1;\n\t\t\tbreak;\n\t\tcase 'number':\n\t\t\ttype = 2;\n\t\t\tbreak;\n\t\tcase 'boolean':\n\t\t\ttype = 3;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (!exports.isDate(field))\n\t\t\t\treturn self;\n\t\t\ttype = 4;\n\t\t\tbreak;\n\t}", "\tshellsort(self, function(a, b) {", "\t\tvar va = name ? a[name] : a;\n\t\tvar vb = name ? b[name] : b;", "\t\t// String\n\t\tif (type === 1) {\n\t\t\treturn va && vb ? (asc ? COMPARER(va, vb) : COMPARER(vb, va)) : 0;\n\t\t} else if (type === 2) {\n\t\t\treturn va > vb ? (asc ? 1 : -1) : va < vb ? (asc ? -1 : 1) : 0;\n\t\t} else if (type === 3) {\n\t\t\treturn va === true && vb === false ? (asc ? 1 : -1) : va === false && vb === true ? (asc ? -1 : 1) : 0;\n\t\t} else if (type === 4) {\n\t\t\tif (!va || !vb)\n\t\t\t\treturn 0;\n\t\t\tif (!va.getTime)\n\t\t\t\tva = new Date(va);\n\t\t\tif (!vb.getTime)\n\t\t\t\tvb = new Date(vb);\n\t\t\tvar at = va.getTime();\n\t\t\tvar bt = vb.getTime();\n\t\t\treturn at > bt ? (asc ? 1 : -1) : at < bt ? (asc ? -1 : 1) : 0;\n\t\t}\n\t\treturn 0;\n\t});", "\treturn self;\n};", "AP.trim = function() {\n\tvar self = this;\n\tvar output = [];\n\tfor (var i = 0, length = self.length; i < length; i++) {\n\t\tif (typeof(self[i]) === 'string')\n\t\t\tself[i] = self[i].trim();\n\t\tself[i] && output.push(self[i]);\n\t}\n\treturn output;\n};", "/**\n * Skip items from array\n * @param {Number} count\n * @return {Array}\n */\nAP.skip = function(count) {\n\tvar arr = [];\n\tvar self = this;\n\tvar length = self.length;\n\tfor (var i = 0; i < length; i++)\n\t\ti >= count && arr.push(self[i]);\n\treturn arr;\n};", "/**\n * Find items in Array\n * @param {Function(item, index) or String/Object} cb\n * @param {Object} value Optional.\n * @return {Array}\n */\nAP.where = AP.findAll = function(cb, value) {", "\tvar self = this;\n\tvar selected = [];\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\tcb.call(self, self[i], i) && selected.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tself[i] && self[i][cb] === value && selected.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tself[i] === cb && selected.push(self[i]);\n\t}", "\treturn selected;\n};", "/**\n * Find item in Array\n * @param {Function(item, index) or String/Object} cb\n * @param {Object} value Optional.\n * @return {Array}\n */\nAP.findItem = function(cb, value) {\n\tvar self = this;\n\tvar index = self.findIndex(cb, value);\n\tif (index === -1)\n\t\treturn null;\n\treturn self[index];\n};", "var arrfindobsolete;", "AP.find = function(cb, value) {", "\tif (!arrfindobsolete) {\n\t\tarrfindobsolete = true;\n\t\tOBSOLETE('Array.prototype.find()', 'will be removed in v4, use alternative \"Array.prototype.findItem()\"');\n\t}", "\tvar self = this;\n\tvar index = self.findIndex(cb, value);\n\tif (index === -1)\n\t\treturn null;\n\treturn self[index];\n};", "AP.findIndex = function(cb, value) {", "\tvar self = this;\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\tif (cb.call(self, self[i], i))\n\t\t\t\treturn i;\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tif (self[i] && self[i][cb] === value)\n\t\t\t\treturn i;\n\t\t\tcontinue;\n\t\t}", "\t\tif (self[i] === cb)\n\t\t\treturn i;\n\t}", "\treturn -1;\n};", "/**\n * Remove items from Array\n * @param {Function(item, index) or Object} cb\n * @param {Object} value Optional.\n * @return {Array}\n */\nAP.remove = function(cb, value) {", "\tvar self = this;\n\tvar arr = [];\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\t!cb.call(self, self[i], i) && arr.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tself[i] && self[i][cb] !== value && arr.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tself[i] !== cb && arr.push(self[i]);\n\t}\n\treturn arr;\n};", "AP.wait = AP.waitFor = function(onItem, callback, thread, tmp) {", "\tvar self = this;\n\tvar init = false;", "\t// INIT\n\tif (!tmp) {", "\t\tif (typeof(callback) !== 'function') {\n\t\t\tthread = callback;\n\t\t\tcallback = null;\n\t\t}", "\t\ttmp = {};\n\t\ttmp.pending = 0;\n\t\ttmp.index = 0;\n\t\ttmp.thread = thread;", "\t\t// thread === Boolean then array has to be removed item by item", "\t\tinit = true;\n\t}", "\tvar item = thread === true ? self.shift() : self[tmp.index++];\n\tif (item === undefined) {\n\t\tif (!tmp.pending) {\n\t\t\tcallback && callback();\n\t\t\ttmp.cancel = true;\n\t\t}\n\t\treturn self;\n\t}", "\ttmp.pending++;\n\tonItem.call(self, item, () => setImmediate(next_wait, self, onItem, callback, thread, tmp), tmp.index);", "\tif (!init || tmp.thread === 1)\n\t\treturn self;", "\tfor (var i = 1; i < tmp.thread; i++)\n\t\tself.wait(onItem, callback, 1, tmp);", "\treturn self;\n};", "function next_wait(self, onItem, callback, thread, tmp) {\n\ttmp.pending--;\n\tself.wait(onItem, callback, thread, tmp);\n}", "/**\n * Creates a function async list\n * @param {Function} callback Optional\n * @return {Array}\n */\nAP.async = function(thread, callback, pending) {", "\tvar self = this;", "\tif (typeof(thread) === 'function') {\n\t\tcallback = thread;\n\t\tthread = 1;\n\t} else if (thread === undefined)\n\t\tthread = 1;", "\tif (pending === undefined)\n\t\tpending = 0;", "\tvar item = self.shift();\n\tif (item === undefined) {\n\t\tif (!pending) {\n\t\t\tpending = undefined;\n\t\t\tcallback && callback();\n\t\t}\n\t\treturn self;\n\t}", "\tfor (var i = 0; i < thread; i++) {", "\t\tif (i)\n\t\t\titem = self.shift();", "\t\tpending++;\n\t\titem(function() {\n\t\t\tsetImmediate(function() {\n\t\t\t\tpending--;\n\t\t\t\tself.async(1, callback, pending);\n\t\t\t});\n\t\t});\n\t}", "\treturn self;\n};", "AP.randomize = function() {\n\tOBSOLETE('Array.randomize()', 'Use Array.random().');\n\treturn this.random();\n};", "// Fisher-Yates shuffle\nAP.random = function() {\n\tfor (var i = this.length - 1; i > 0; i--) {\n\t\tvar j = Math.floor(Math.random() * (i + 1));\n\t\tvar temp = this[i];\n\t\tthis[i] = this[j];\n\t\tthis[j] = temp;\n\t}\n\treturn this;\n};", "AP.limit = function(max, fn, callback, index) {", "\tif (index === undefined)\n\t\tindex = 0;", "\tvar current = [];\n\tvar self = this;\n\tvar length = index + max;", "\tfor (var i = index; i < length; i++) {\n\t\tvar item = self[i];", "\t\tif (item !== undefined) {\n\t\t\tcurrent.push(item);\n\t\t\tcontinue;\n\t\t}", "\t\tif (!current.length) {\n\t\t\tcallback && callback();\n\t\t\treturn self;\n\t\t}", "\t\tfn(current, () => callback && callback(), index, index + max);\n\t\treturn self;\n\t}", "\tif (!current.length) {\n\t\tcallback && callback();\n\t\treturn self;\n\t}", "\tfn(current, function() {\n\t\tif (length < self.length)\n\t\t\tself.limit(max, fn, callback, length);\n\t\telse\n\t\t\tcallback && callback();\n\t}, index, index + max);", "\treturn self;\n};", "/**\n * Get unique elements from Array\n * @return {[type]} [description]\n */\nAP.unique = function(property) {", "\tvar self = this;\n\tvar result = [];\n\tvar sublength = 0;", "\tfor (var i = 0, length = self.length; i < length; i++) {\n\t\tvar value = self[i];", "\t\tif (!property) {\n\t\t\tresult.indexOf(value) === -1 && result.push(value);\n\t\t\tcontinue;\n\t\t}", "\t\tif (sublength === 0) {\n\t\t\tresult.push(value);\n\t\t\tsublength++;\n\t\t\tcontinue;\n\t\t}", "\t\tvar is = true;\n\t\tfor (var j = 0; j < sublength; j++) {\n\t\t\tif (result[j][property] === value[property]) {\n\t\t\t\tis = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (is) {\n\t\t\tresult.push(value);\n\t\t\tsublength++;\n\t\t}\n\t}", "\treturn result;\n};", "ArrayBuffer.prototype.toBuffer = function() {\n\tvar buf = new Buffer(this.byteLength);\n\tvar view = new Uint8Array(this);\n\tfor (var i = 0, length = buf.length; i < length; ++i)\n\t\tbuf[i] = view[i];\n\treturn buf;\n};", "function AsyncTask(owner, name, fn, cb, waiting) {\n\tthis.isRunning = 0;\n\tthis.owner = owner;\n\tthis.name = name;\n\tthis.fn = fn;\n\tthis.cb = cb;\n\tthis.waiting = waiting;\n\tthis.interval = null;\n\tthis.isCanceled = false;\n}", "AsyncTask.prototype.run = function() {\n\tvar self = this;\n\ttry\n\t{", "\t\tif (self.isCanceled) {\n\t\t\tself.complete();\n\t\t\treturn self;\n\t\t}", "\t\tself.isRunning = 1;\n\t\tself.owner.tasksWaiting[self.name] = true;\n\t\tself.owner.emit('begin', self.name);", "\t\tvar timeout = self.owner.tasksTimeout[self.name];\n\t\tif (timeout > 0)\n\t\t\tself.interval = setTimeout(function() { self.timeout(); }, timeout);", "\t\tself.fn(function() {\n\t\t\tsetImmediate(() => self.complete());\n\t\t});", "\t} catch (ex) {\n\t\tself.owner.emit('error', self.name, ex);\n\t\tself.complete();\n\t}\n\treturn self;\n};", "AsyncTask.prototype.timeout = function(timeout) {", "\tvar self = this;", "\tif (timeout > 0) {\n\t\tclearTimeout(self.interval);\n\t\tsetTimeout(function() { self.timeout(); }, timeout);\n\t\treturn self;\n\t}", "\tif (timeout <= 0) {\n\t\tclearTimeout(self.interval);\n\t\tsetTimeout(function() { self.timeout(); }, timeout);\n\t\treturn self;\n\t}", "\tsetImmediate(() => self.cancel(true));\n\treturn self;\n};", "AsyncTask.prototype.cancel = function(isTimeout) {\n\tvar self = this;", "\tself.isCanceled = true;", "\tif (isTimeout)\n\t\tself.owner.emit('timeout', self.name);\n\telse\n\t\tself.owner.emit('cancel', self.name);", "\tself.fn = null;\n\tself.cb = null;\n\tself.complete();\n\treturn self;\n};", "AsyncTask.prototype.complete = function() {", "\tvar item = this;\n\tvar self = item.owner;", "\titem.isRunning = 2;", "\tdelete self.tasksPending[item.name];\n\tdelete self.tasksWaiting[item.name];", "\tif (!item.isCanceled) {\n\t\ttry\n\t\t{\n\t\t\tself.emit('end', item.name);\n\t\t\titem.cb && item.cb();\n\t\t} catch (ex) {\n\t\t\tself.emit('error', ex, item.name);\n\t\t}\n\t}", "\tsetImmediate(function() {\n\t\tself.reload();\n\t\tself.refresh();\n\t});", "\treturn self;\n};", "function Async(owner) {", "\tthis._max = 0;\n\tthis._count = 0;\n\tthis._isRunning = false;\n\tthis._isEnd = false;", "\tthis.owner = owner;\n\tthis.onComplete = [];", "\tthis.tasksPending = {};\n\tthis.tasksWaiting = {};\n\tthis.tasksAll = [];\n\tthis.tasksTimeout = {};\n\tthis.isCanceled = false;", "\tEvents.EventEmitter.call(this);\n}", "Async.prototype = {\n\tget count() {\n\t\treturn this._count;\n\t},", "\tget percentage() {\n\t\tvar p = 100 - Math.floor((this._count * 100) / this._max);\n\t\treturn p ? p : 0;\n\t}\n};", "const ACP = Async.prototype;", "ACP.__proto__ = Object.create(Events.EventEmitter.prototype, {\n\tconstructor: {\n\t\tvalue: Async,\n\t\tenumberable: false\n\t}\n});", "ACP.reload = function() {\n\tvar self = this;\n\tself.tasksAll = Object.keys(self.tasksPending);\n\tself.emit('percentage', self.percentage);\n\treturn self;\n};", "ACP.cancel = function(name) {", "\tvar self = this;", "\tif (name === undefined) {\n\t\tself.isCanceled = true;\n\t\tfor (var i = 0; i < self._count; i++)\n\t\t\tself.cancel(self.tasksAll[i]);\n\t\treturn true;\n\t}", "\tvar task = self.tasksPending[name];\n\tif (!task)\n\t\treturn false;", "\tdelete self.tasksPending[name];\n\tdelete self.tasksWaiting[name];", "\ttask.cancel();\n\ttask = null;\n\tself.reload();\n\tself.refresh();", "\treturn true;\n};", "ACP.await = function(name, fn, cb) {", "\tvar self = this;", "\tif (self.isCanceled)\n\t\treturn false;", "\tif (typeof(name) === 'function') {\n\t\tcb = fn;\n\t\tfn = name;\n\t\tname = exports.GUID(6);\n\t}", "\tif (self.tasksPending[name])\n\t\treturn false;", "\tself.tasksPending[name] = new AsyncTask(self, name, fn, cb, null);\n\tself._max++;\n\tself.reload();\n\tself.refresh();\n\treturn true;\n};", "ACP.wait = function(name, waitingFor, fn, cb) {", "\tvar self = this;", "\tif (self.isCanceled)\n\t\treturn false;", "\tif (typeof(waitingFor) === 'function') {\n\t\tcb = fn;\n\t\tfn = waitingFor;\n\t\twaitingFor = null;\n\t}", "\tif (self.tasksPending[name])\n\t\treturn false;", "\tself.tasksPending[name] = new AsyncTask(self, name, fn, cb, waitingFor);\n\tself._max++;\n\tself.reload();\n\tself.refresh();\n\treturn true;\n};", "ACP.complete = function(fn) {\n\treturn this.run(fn);\n};", "ACP.run = function(fn) {\n\tthis._isRunning = true;\n\tfn && this.onComplete.push(fn);\n\tthis.refresh();\n\treturn this;\n};", "ACP.isRunning = function(name) {\n\tif (!name)\n\t\treturn this._isRunning;\n\tvar task = this.tasksPending[name];\n\treturn task ? task.isRunning === 1 : false;\n};", "ACP.isWaiting = function(name) {\n\tvar task = this.tasksPending[name];\n\treturn task ? task.isRunning === 0 : false;\n};", "ACP.isPending = function(name) {\n\treturn this.tasksPending[name] ? true : false;\n};", "ACP.timeout = function(name, timeout) {\n\tif (timeout)\n\t\tthis.tasksTimeout[name] = timeout;\n\telse\n\t\tthis.tasksTimeout[name] = undefined;\n\treturn this;\n};", "ACP.refresh = function(name) {", "\tvar self = this;", "\tif (!self._isRunning || self._isEnd)\n\t\treturn self;", "\tself._count = self.tasksAll.length;\n\tvar index = 0;", "\twhile (true) {\n\t\tvar name = self.tasksAll[index++];\n\t\tif (!name)\n\t\t\tbreak;", "\t\tvar task = self.tasksPending[name];\n\t\tif (!task)\n\t\t\tbreak;", "\t\tif (self.isCanceled || task.isCanceled) {\n\t\t\tdelete self.tasksPending[name];\n\t\t\tdelete self.tasksWaiting[name];\n\t\t\tself.tasksAll.splice(index, 1);\n\t\t\tself._count = self.tasksAll.length;\n\t\t\tindex--;\n\t\t\tcontinue;\n\t\t}", "\t\tif (task.isRunning !== 0 || (task.waiting && self.tasksPending[task.waiting]))\n\t\t\tcontinue;", "\t\ttask.run();\n\t}", "\tif (self._count === 0) {\n\t\tself._isRunning = false;\n\t\tself._isEnd = true;\n\t\tself.emit('complete');\n\t\tself.emit('percentage', 100);\n\t\tself._max = 0;\n\t\tvar complete = self.onComplete;\n\t\tvar length = complete.length;\n\t\tself.onComplete = [];\n\t\tfor (var i = 0; i < length; i++) {\n\t\t\ttry\n\t\t\t{\n\t\t\t\tcomplete[i]();\n\t\t\t} catch (ex) {\n\t\t\t\tself.emit('error', ex);\n\t\t\t}\n\t\t}\n\t\tsetImmediate(() => self._isEnd = false);\n\t}", "\treturn self;\n};", "function FileList() {\n\tthis.pending = [];\n\tthis.pendingDirectory = [];\n\tthis.directory = [];\n\tthis.file = [];\n\tthis.onComplete = null;\n\tthis.onFilter = null;\n\tthis.advanced = false;\n}", "const FLP = FileList.prototype;", "FLP.reset = function() {\n\tthis.file.length = 0;\n\tthis.directory.length = 0;\n\tthis.pendingDirectory.length = 0;\n\treturn this;\n};", "FLP.walk = function(directory) {", "\tvar self = this;", "\tif (directory instanceof Array) {\n\t\tvar length = directory.length;\n\t\tfor (var i = 0; i < length; i++)\n\t\t\tself.pendingDirectory.push(directory[i]);\n\t\tself.next();\n\t\treturn;\n\t}", "\tFs.readdir(directory, function(err, arr) {\n\t\tif (err)\n\t\t\treturn self.next();\n\t\tvar length = arr.length;\n\t\tfor (var i = 0; i < length; i++)\n\t\t\tself.pending.push(Path.join(directory, arr[i]));\n\t\tself.next();\n\t});\n};", "FLP.stat = function(path) {\n\tvar self = this;", "\tFs.stat(path, function(err, stats) {", "\t\tif (err)\n\t\t\treturn self.next();", "\t\tif (stats.isDirectory()) {\n\t\t\tpath = self.clean(path);\n\t\t\tif (!self.onFilter || self.onFilter(path, true)) {\n\t\t\t\tself.directory.push(path);\n\t\t\t\tself.pendingDirectory.push(path);\n\t\t\t}\n\t\t} else if (!self.onFilter || self.onFilter(path, false))\n\t\t\tself.file.push(self.advanced ? { filename: path, stats: stats } : path);", "\t\tself.next();\n\t});\n};", "FLP.clean = function(path) {\n\treturn path[path.length - 1] === Path.sep ? path : path + Path.sep;\n};", "FLP.next = function() {\n\tvar self = this;", "\tif (self.pending.length) {\n\t\tvar item = self.pending.shift();\n\t\tself.stat(item);\n\t\treturn;\n\t}", "\tif (self.pendingDirectory.length) {\n\t\tvar directory = self.pendingDirectory.shift();\n\t\tself.walk(directory);\n\t\treturn;\n\t}", "\tself.onComplete(self.file, self.directory);\n};", "exports.Async = Async;", "exports.sync = function(fn, owner) {\n\treturn function() {", "\t\tvar args = [].slice.call(arguments);\n\t\tvar params;\n\t\tvar callback;\n\t\tvar executed = false;\n\t\tvar self = owner || this;", "\t\targs.push(function() {\n\t\t\tparams = arguments;\n\t\t\tif (!executed && callback) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t});", "\t\tfn.apply(self, args);", "\t\treturn function(cb) {\n\t\t\tcallback = cb;\n\t\t\tif (!executed && params) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t};\n\t};\n};", "exports.sync2 = function(fn, owner) {\n\treturn (function() {", "\t\tvar params;\n\t\tvar callback;\n\t\tvar executed = false;\n\t\tvar self = owner || this;\n\t\tvar args = [].slice.call(arguments);", "\t\targs.push(function() {\n\t\t\tparams = arguments;\n\t\t\tif (!executed && callback) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t});", "\t\tfn.apply(self, args);", "\t\treturn function(cb) {\n\t\t\tcallback = cb;\n\t\t\tif (!executed && params) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t};\n\t})();\n};", "exports.async = function(fn, isApply) {\n\tvar context = this;\n\treturn function(complete) {", "\t\tvar self = this;\n\t\tvar argv;", "\t\tif (arguments.length) {", "\t\t\tif (isApply) {\n\t\t\t\t// index.js/Subscribe.prototype.doExecute\n\t\t\t\targv = arguments[1];\n\t\t\t} else {\n\t\t\t\targv = [];\n\t\t\t\tfor (var i = 1; i < arguments.length; i++)\n\t\t\t\t\targv.push(arguments[i]);\n\t\t\t}\n\t\t} else\n\t\t\targv = new Array(0);", "\t\tvar generator = fn.apply(context, argv);\n\t\tnext(null);", "\t\tfunction next(err, result) {", "\t\t\tvar g, type;", "\t\t\ttry\n\t\t\t{\n\t\t\t\tvar can = err ? false : true;\n\t\t\t\tswitch (can) {\n\t\t\t\t\tcase true:\n\t\t\t\t\t\tg = generator.next(result);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase false:\n\t\t\t\t\t\tg = generator.throw(err);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}", "\t\t\t} catch (e) {", "\t\t\t\tif (!complete)\n\t\t\t\t\treturn;", "\t\t\t\ttype = typeof(complete);", "\t\t\t\tif (type === 'object' && complete.isController) {\n\t\t\t\t\tif (e instanceof ErrorBuilder)\n\t\t\t\t\t\tcomplete.content(e);\n\t\t\t\t\telse\n\t\t\t\t\t\tcomplete.view500(e);\n\t\t\t\t\treturn;\n\t\t\t\t}", "\t\t\t\ttype === 'function' && setImmediate(() => complete(e));\n\t\t\t\treturn;\n\t\t\t}", "\t\t\tif (g.done) {\n\t\t\t\ttypeof(complete) === 'function' && complete(null, g.value);\n\t\t\t\treturn;\n\t\t\t}", "\t\t\tvar promise = g.value instanceof Promise;", "\t\t\tif (typeof(g.value) !== 'function' && !promise) {\n\t\t\t\tnext.call(self, null, g.value);\n\t\t\t\treturn;\n\t\t\t}", "\t\t\ttry\n\t\t\t{\n\t\t\t\tif (promise) {\n\t\t\t\t\tg.value.then((value) => next.call(self, null, value));\n\t\t\t\t\treturn;\n\t\t\t\t}", "\t\t\t\tg.value.call(self, function() {\n\t\t\t\t\tnext.apply(self, arguments);\n\t\t\t\t});", "\t\t\t} catch (e) {\n\t\t\t\tsetImmediate(() => next.call(self, e));\n\t\t\t}\n\t\t}", "\t\treturn generator.value;\n\t};\n};", "// MIT\n// Written by Jozef Gula\n// Optimized by Peter Sirka\nconst CACHE_GML1 = [null, null, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];\nconst CACHE_GML2 = [null, null, null, null, null, null, null, null];\nexports.getMessageLength = function(data, isLE) {", "\tvar length = data[1] & 0x7f;", "\tif (length === 126) {\n\t\tif (data.length < 4)\n\t\t\treturn -1;\n\t\tCACHE_GML1[0] = data[3];\n\t\tCACHE_GML1[1] = data[2];\n\t\treturn converBytesToInt64(CACHE_GML1, 0, isLE);\n\t}", "\tif (length === 127) {\n\t\tif (data.Length < 10)\n\t\t\treturn -1;\n\t\tCACHE_GML2[0] = data[9];\n\t\tCACHE_GML2[1] = data[8];\n\t\tCACHE_GML2[2] = data[7];\n\t\tCACHE_GML2[3] = data[6];\n\t\tCACHE_GML2[4] = data[5];\n\t\tCACHE_GML2[5] = data[4];\n\t\tCACHE_GML2[6] = data[3];\n\t\tCACHE_GML2[7] = data[2];\n\t\treturn converBytesToInt64(CACHE_GML2, 0, isLE);\n\t}", "\treturn length;\n};", "// MIT\n// Written by Jozef Gula\nfunction converBytesToInt64(data, startIndex, isLE) {\n\treturn isLE ? (data[startIndex] | (data[startIndex + 1] << 0x08) | (data[startIndex + 2] << 0x10) | (data[startIndex + 3] << 0x18) | (data[startIndex + 4] << 0x20) | (data[startIndex + 5] << 0x28) | (data[startIndex + 6] << 0x30) | (data[startIndex + 7] << 0x38)) : ((data[startIndex + 7] << 0x20) | (data[startIndex + 6] << 0x28) | (data[startIndex + 5] << 0x30) | (data[startIndex + 4] << 0x38) | (data[startIndex + 3]) | (data[startIndex + 2] << 0x08) | (data[startIndex + 1] << 0x10) | (data[startIndex] << 0x18));\n}", "exports.queuecache = {};", "function queue_next(name) {", "\tvar item = exports.queuecache[name];\n\tif (!item)\n\t\treturn;", "\titem.running--;", "\tif (item.running < 0)\n\t\titem.running = 0;", "\tif (item.pending.length) {\n\t\tvar fn = item.pending.shift();\n\t\tif (fn) {\n\t\t\titem.running++;\n\t\t\tsetImmediate(queue_next_callback, fn, name);\n\t\t} else\n\t\t\titem.running = 0;\n\t}\n}", "function queue_next_callback(fn, name) {\n\tfn(() => queue_next(name));\n}", "/**\n * Queue list\n * @param {String} name\n * @param {Number} max Maximum stack.\n * @param {Function(next)} fn\n */\nexports.queue = function(name, max, fn) {", "\tif (!fn)\n\t\treturn false;", "\tif (!max) {\n\t\tfn(NOOP);\n\t\treturn true;\n\t}", "\tif (!exports.queuecache[name])\n\t\texports.queuecache[name] = { limit: max, running: 0, pending: [] };", "\tvar item = exports.queuecache[name];\n\tif (item.running >= item.limit) {\n\t\titem.pending.push(fn);\n\t\treturn false;\n\t}", "\titem.running++;\n\tsetImmediate(queue_next_callback, fn, name);\n\treturn true;\n};", "exports.minifyStyle = function(val) {\n\treturn Internal.compile_css(val);\n};", "exports.minifyScript = function(val) {\n\treturn Internal.compile_javascript(val);\n};", "exports.minifyHTML = function(val) {\n\treturn Internal.compile_html(val);\n};", "exports.parseTheme = function(value) {\n\tif (value[0] !== '=')\n\t\treturn '';\n\tvar index = value.indexOf('/', 2);\n\tif (index === -1)\n\t\treturn '';\n\tvalue = value.substring(1, index);\n\treturn value === '?' ? CONF.default_theme : value;\n};", "exports.set = function(obj, path, value) {\n\tvar cachekey = 'S+' + path;", "\tif (F.temporary.other[cachekey])\n\t\treturn F.temporary.other[cachekey](obj, value);", "\tvar arr = parsepath(path);\n\tvar builder = [];", "\tfor (var i = 0; i < arr.length - 1; i++) {\n\t\tvar type = arr[i + 1] ? (REGISARR.test(arr[i + 1]) ? '[]' : '{}') : '{}';\n\t\tvar p = 'w' + (arr[i][0] === '[' ? '' : '.') + arr[i];\n\t\tbuilder.push('if(typeof(' + p + ')!==\\'object\\'||' + p + '==null)' + p + '=' + type + ';');\n\t}", "\tvar v = arr[arr.length - 1];\n\tvar ispush = v.lastIndexOf('[]') !== -1;\n\tvar a = builder.join(';') + ';var v=typeof(a)===\\'function\\'?a(U.get(b)):a;w' + (v[0] === '[' ? '' : '.') + (ispush ? v.replace(REGREPLACEARR, '.push(v)') : (v + '=v')) + ';return v';\n", "\tif ((/__proto__|constructor|prototype|eval/).test(a))\n\t\tthrow new Error('Potential vulnerability');", "\n\tvar fn = new Function('w', 'a', 'b', a);\n\tF.temporary.other[cachekey] = fn;\n\tfn(obj, value, path);\n};", "exports.get = function(obj, path) {", "\tvar cachekey = 'G=' + path;", "\tif (F.temporary.other[cachekey])\n\t\treturn F.temporary.other[cachekey](obj);", "\tvar arr = parsepath(path);\n\tvar builder = [];", "\tfor (var i = 0, length = arr.length - 1; i < length; i++)\n\t\tbuilder.push('if(!w' + (!arr[i] || arr[i][0] === '[' ? '' : '.') + arr[i] + ')return');", "\tvar v = arr[arr.length - 1];\n\tvar fn = (new Function('w', builder.join(';') + ';return w' + (v[0] === '[' ? '' : '.') + v));\n\tF.temporary.other[cachekey] = fn;\n\treturn fn(obj);\n};", "function parsepath(path) {", "\tvar arr = path.split('.');\n\tvar builder = [];\n\tvar all = [];", "\tfor (var i = 0; i < arr.length; i++) {\n\t\tvar p = arr[i];\n\t\tvar index = p.indexOf('[');\n\t\tif (index === -1) {\n\t\t\tif (p.indexOf('-') === -1) {\n\t\t\t\tall.push(p);\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t} else {\n\t\t\t\tvar a = all.splice(all.length - 1);\n\t\t\t\tall.push(a + '[\\'' + p + '\\']');\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t}\n\t\t} else {\n\t\t\tif (p.indexOf('-') === -1) {\n\t\t\t\tall.push(p.substring(0, index));\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t\tall.splice(all.length - 1);\n\t\t\t\tall.push(p);\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t} else {\n\t\t\t\tall.push('[\\'' + p.substring(0, index) + '\\']');\n\t\t\t\tbuilder.push(all.join(''));\n\t\t\t\tall.push(p.substring(index));\n\t\t\t\tbuilder.push(all.join(''));\n\t\t\t}\n\t\t}\n\t}", "\treturn builder;\n}", "global.Async = global.async = exports.async;\nglobal.sync = global.SYNCHRONIZE = exports.sync;\nglobal.sync2 = exports.sync2;", "// =============================================\n// SHELL SORT IMPLEMENTATION OF ALGORITHM\n// =============================================", "function _shellInsertionSort(list, length, gapSize, fn) {\n\tvar temp, i, j;\n\tfor (i = gapSize; i < length; i += gapSize ) {\n\t\tj = i;\n\t\twhile(j > 0 && fn(list[j - gapSize], list[j]) === 1) {\n\t\t\ttemp = list[j];\n\t\t\tlist[j] = list[j - gapSize];\n\t\t\tlist[j - gapSize] = temp;\n\t\t\tj -= gapSize;\n\t\t}\n\t}\n}", "function shellsort(arr, fn) {\n\tvar length = arr.length;\n\tvar gapSize = Math.floor(length / 2);\n\twhile(gapSize) {\n\t\t_shellInsertionSort(arr, length, gapSize, fn);\n\t\tgapSize = Math.floor(gapSize / 2);\n\t}\n\treturn arr;\n}", "function EventEmitter2(obj) {\n\tif (obj) {\n\t\t!obj.emit && EventEmitter2.extend(obj);\n\t\treturn obj;\n\t} else\n\t\tthis.$events = {};\n}", "const EE2P = EventEmitter2.prototype;", "EE2P.emit = function(name, a, b, c, d, e, f, g) {", "\tif (!this.$events)\n\t\treturn this;", "\tvar evt = this.$events[name];\n\tif (evt) {\n\t\tvar clean = false;\n\t\tfor (var i = 0, length = evt.length; i < length; i++) {\n\t\t\tif (evt[i].$once)\n\t\t\t\tclean = true;\n\t\t\tevt[i].call(this, a, b, c, d, e, f, g);\n\t\t}\n\t\tif (clean) {\n\t\t\tevt = evt.remove(n => n.$once);\n\t\t\tif (evt.length)\n\t\t\t\tthis.$events[name] = evt;\n\t\t\telse\n\t\t\t\tthis.$events[name] = undefined;\n\t\t}\n\t}\n\treturn this;\n};", "EE2P.on = function(name, fn) {\n\tif (!this.$events)\n\t\tthis.$events = {};\n\tif (this.$events[name])\n\t\tthis.$events[name].push(fn);\n\telse\n\t\tthis.$events[name] = [fn];\n\treturn this;\n};", "EE2P.once = function(name, fn) {\n\tfn.$once = true;\n\treturn this.on(name, fn);\n};", "EE2P.removeListener = function(name, fn) {\n\tif (this.$events) {\n\t\tvar evt = this.$events[name];\n\t\tif (evt) {\n\t\t\tevt = evt.remove(n => n === fn);\n\t\t\tif (evt.length)\n\t\t\t\tthis.$events[name] = evt;\n\t\t\telse\n\t\t\t\tthis.$events[name] = undefined;\n\t\t}\n\t}\n\treturn this;\n};", "EE2P.removeAllListeners = function(name) {\n\tif (this.$events) {\n\t\tif (name === true)\n\t\t\tthis.$events = EMPTYOBJECT;\n\t\telse if (name)\n\t\t\tthis.$events[name] = undefined;\n\t\telse\n\t\t\tthis.$events = {};\n\t}\n\treturn this;\n};", "EventEmitter2.extend = function(obj) {\n\tobj.emit = EE2P.emit;\n\tobj.on = EE2P.on;\n\tobj.once = EE2P.once;\n\tobj.removeListener = EE2P.removeListener;\n\tobj.removeAllListeners = EE2P.removeAllListeners;\n};", "exports.EventEmitter2 = EventEmitter2;", "function Chunker(name, max) {\n\tthis.name = name;\n\tthis.max = max || 50;\n\tthis.index = 0;\n\tthis.filename = '{0}-'.format(name);\n\tthis.stack = [];\n\tthis.flushing = 0;\n\tthis.pages = 0;\n\tthis.count = 0;\n\tthis.percentage = 0;\n\tthis.autoremove = true;\n\tthis.compress = true;\n\tthis.filename = F.path.temp(this.filename);\n}", "const CHP = Chunker.prototype;", "CHP.append = CHP.write = function(obj) {\n\tvar self = this;", "\tself.stack.push(obj);", "\tvar tmp = self.stack.length;", "\tif (tmp >= self.max) {", "\t\tself.flushing++;\n\t\tself.pages++;\n\t\tself.count += tmp;", "\t\tvar index = (self.index++);", "\t\tif (self.compress) {\n\t\t\tZlib.deflate(Buffer.from(JSON.stringify(self.stack), ENCODING), function(err, buffer) {\n\t\t\t\tFs.writeFile(self.filename + index + '.chunker', buffer, () => self.flushing--);\n\t\t\t});\n\t\t} else\n\t\t\tFs.writeFile(self.filename + index + '.chunker', JSON.stringify(self.stack), () => self.flushing--);", "\t\tself.stack = [];\n\t}", "\treturn self;\n};", "CHP.end = function() {\n\tvar self = this;\n\tvar tmp = self.stack.length;\n\tif (tmp) {\n\t\tself.flushing++;\n\t\tself.pages++;\n\t\tself.count += tmp;", "\t\tvar index = (self.index++);", "\t\tif (self.compress) {\n\t\t\tZlib.deflate(Buffer.from(JSON.stringify(self.stack), ENCODING), function(err, buffer) {\n\t\t\t\tFs.writeFile(self.filename + index + '.chunker', buffer, () => self.flushing--);\n\t\t\t});\n\t\t} else\n\t\t\tFs.writeFile(self.filename + index + '.chunker', JSON.stringify(self.stack), () => self.flushing--);", "\t\tself.stack = [];\n\t}", "\treturn self;\n};", "CHP.each = function(onItem, onEnd, indexer) {", "\tvar self = this;", "\tif (indexer == null) {\n\t\tself.percentage = 0;\n\t\tindexer = 0;\n\t}", "\tif (indexer >= self.index)\n\t\treturn onEnd && onEnd();", "\tself.read(indexer++, function(err, items) {\n\t\tself.percentage = Math.ceil((indexer / self.pages) * 100);\n\t\tonItem(items, () => self.each(onItem, onEnd, indexer), indexer - 1);\n\t});", "\treturn self;\n};", "CHP.read = function(index, callback) {\n\tvar self = this;", "\tif (self.flushing) {\n\t\tself.flushing_timeout = setTimeout(() => self.read(index, callback), 300);\n\t\treturn;\n\t}", "\tvar filename = self.filename + index + '.chunker';", "\tFs.readFile(filename, function(err, data) {", "\t\tif (err) {\n\t\t\tcallback(null, EMPTYARRAY);\n\t\t\treturn;\n\t\t}", "\t\tif (self.compress) {\n\t\t\tZlib.inflate(data, function(err, data) {\n\t\t\t\tif (err) {\n\t\t\t\t\tcallback(null, EMPTYARRAY);\n\t\t\t\t} else {\n\t\t\t\t\tself.autoremove && Fs.unlink(filename, NOOP);\n\t\t\t\t\tcallback(null, data.toString('utf8').parseJSON(true));\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tself.autoremove && Fs.unlink(filename, NOOP);\n\t\t\tcallback(null, data.toString('utf8').parseJSON(true));\n\t\t}\n\t});", "\treturn self;\n};", "CHP.clear = function() {\n\tvar files = [];\n\tfor (var i = 0; i < this.index; i++)\n\t\tfiles.push(this.filename + i + '.chunker');\n\tfiles.wait((filename, next) => Fs.unlink(filename, next));\n\treturn this;\n};", "CHP.destroy = function() {\n\tthis.clear();\n\tthis.indexer = 0;\n\tthis.flushing = 0;\n\tclearTimeout(this.flushing_timeout);\n\tthis.stack = null;\n\treturn this;\n};", "exports.chunker = function(name, max) {\n\treturn new Chunker(name, max);\n};", "exports.Chunker = Chunker;", "exports.ObjectToArray = function(obj) {\n\tif (obj == null)\n\t\treturn EMPTYARRAY;\n\tvar keys = Object.keys(obj);\n\tvar output = [];\n\tfor (var i = 0, length = keys.length; i < length; i++)\n\t\toutput.push({ key: keys[i], value: obj[keys[i]]});\n\treturn output;\n};", "if (NODEVERSION > 699) {\n\texports.createBufferSize = (size) => Buffer.alloc(size || 0);\n\texports.createBuffer = (val, type) => Buffer.from(val || '', type);\n} else {\n\texports.createBufferSize = (size) => new Buffer(size || 0);\n\texports.createBuffer = (val, type) => new Buffer(val || '', type);\n}", "function Callback(count, callback) {\n\tthis.pending = count;\n\tthis.$callback = callback;\n}\nconst CP = Callback.prototype;", "CP.done = function(callback) {\n\tthis.$callback = callback;\n\treturn this;\n};", "CP.next = function() {\n\tvar self = this;\n\tself.pending--;\n\tif (!self.pending && self.$callback) {\n\t\tself.$callback();\n\t\tself.$callback = null;\n\t}\n\treturn self;\n};", "global.Callback = Callback;", "exports.Callback = function(count, callback) {\n\treturn new Callback(count, callback);\n};", "function Reader() {\n\tvar t = this;\n\tt.$add = function(builder) {\n\t\tif (t.reader)\n\t\t\tt.reader.add(builder);\n\t\telse\n\t\t\tt.reader = new framework_nosql.NoSQLReader(builder);\n\t};\n}\nconst RP = Reader.prototype;", "RP.done = function() {\n\tvar self = this;\n\tself.reader.done();\n\treturn self;\n};", "RP.reset = function() {\n\tvar self = this;\n\tself.reader.reset();\n\treturn self;\n};", "RP.push = function(data) {\n\tif (data == null)\n\t\tthis.reader.done();\n\telse\n\t\tthis.reader.compare(data instanceof Array ? data : [data]);\n\treturn this;\n};", "RP.find = function() {\n\tvar self = this;\n\tvar builder = new framework_nosql.DatabaseBuilder();\n\tsetImmediate(self.$add, builder);\n\treturn builder;\n};", "RP.count = function() {\n\tvar builder = this.find();\n\tbuilder.$options.readertype = 1;\n\treturn builder;\n};", "RP.scalar = function(type, field) {\n\treturn this.find().scalar(type, field);\n};", "exports.reader = function() {\n\treturn new Reader();\n};", "const BUFEMPTYJSON = Buffer.from('{}');", "global.WAIT = exports.wait;\n!global.F && require('./index');" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [3, 6627], "buggy_code_start_loc": [3, 6625], "filenames": ["changes.txt", "utils.js"], "fixing_code_end_loc": [5, 6627], "fixing_code_start_loc": [4, 6625], "message": "The package total.js before 3.4.8 are vulnerable to Remote Code Execution (RCE) via set.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:totaljs:total.js:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "903890AB-2DE4-4BA4-83F0-AC47EEF03AFB", "versionEndExcluding": "3.4.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The package total.js before 3.4.8 are vulnerable to Remote Code Execution (RCE) via set."}, {"lang": "es", "value": "El paquete total.js versiones anteriores a 3.4.8, es vulnerable a una ejecuci\u00f3n de c\u00f3digo remota (RCE) por medio de set"}], "evaluatorComment": null, "id": "CVE-2021-23344", "lastModified": "2021-03-05T19:26:24.673", "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"}, {"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": "report@snyk.io", "type": "Secondary"}]}, "published": "2021-03-04T17:15:13.153", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/totaljs/framework/commit/c812bbcab8981797d3a1b9993fc42dad3d246f04"}, {"source": "report@snyk.io", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-TOTALJS-1077069"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-94"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/totaljs/framework/commit/c812bbcab8981797d3a1b9993fc42dad3d246f04"}, "type": "CWE-94"}
243
Determine whether the {function_name} code is vulnerable or not.
[ "# Sidekiq Changes", "[Sidekiq Changes](https://github.com/sidekiq/sidekiq/blob/main/Changes.md) | [Sidekiq Pro Changes](https://github.com/sidekiq/sidekiq/blob/main/Pro-Changes.md) | [Sidekiq Enterprise Changes](https://github.com/sidekiq/sidekiq/blob/main/Ent-Changes.md)\n", "HEAD", "----------\n", "- Add job hash as another parameter to any `sidekiq_retry_in` block.", "\n7.0.7\n----------", "- Fix redis-client API usage which could result in stuck Redis\nconnections [#5823]\n- Fix AS::Duration with `sidekiq_retry_in` [#5806]\n- Restore dumping config options on startup with `-v` [#5822]", "7.0.5,7.0.6\n----------", "- More context for debugging json unsafe errors [#5787]", "7.0.4\n----------", "- Performance and memory optimizations [#5768, fatkodima]\n- Add 1-8 hour period selector to Metrics pages [#5694]\n- Fix process display with `sidekiqmon` [#5733]", "7.0.3\n----------", "- Don't warn about memory policy on Redis Enterprise [#5712]\n- Don't allow Quiet/Stop on embedded Sidekiq instances [#5716]\n- Fix `size: X` for configuring the default Redis pool size [#5702]\n- Improve the display of queue weights on Busy page [#5642]\n- Freeze CurrentAttributes on a job once initially set [#5692]", "7.0.2\n----------", "- Improve compatibility with custom loggers [#5673]\n- Add queue weights on Busy page [#5640]\n- Add BID link on job_info page if job is part of a Batch [#5623]\n- Allow custom extensions to add rows/links within Job detail pages [#5624]\n```ruby\nSidekiq::Web.custom_job_info_rows << AddAccountLink.new", "class AddAccountLink\n include CGI::Util\n def add_pair(job)\n # yield a (name, value) pair\n # You can include HTML tags and CSS, Sidekiq does not do any\n # escaping so beware user data injection! Note how we use CGI's\n # `h` escape helper.\n aid = job[\"account_id\"]\n yield \"Account\", \"<a href='/accounts/#{h aid}'>#{h aid}</a>\" if aid\n end\nend\n```", "7.0.1\n----------", "- Allow an embedding process to reuse its own heartbeat thread\n- Update zh-cn localization", "7.0.0\n----------", "- Embedded mode!\n- Capsules!!\n- Job Execution metrics!!!\n- See `docs/7.0-Upgrade.md` for release notes", "6.5.8\n----------", "- Fail if using a bad version of scout_apm [#5616]\n- Add pagination to Busy page [#5556]\n- Speed up WorkSet#each [#5559]\n- Adjust CurrentAttributes to work with the String class name so we aren't referencing the Class within a Rails initializer [#5536]", "6.5.7\n----------", "- Updates for JA and ZH locales\n- Further optimizations for scheduled polling [#5513]", "6.5.6\n----------", "- Fix deprecation warnings with redis-rb 4.8.0 [#5484]\n- Lock redis-rb to < 5.0 as we are moving to redis-client in Sidekiq 7.0", "6.5.5\n----------", "- Fix require issue with job_retry.rb [#5462]\n- Improve Sidekiq::Web compatibility with Rack 3.x", "6.5.4\n----------", "- Fix invalid code on Ruby 2.5 [#5460]\n- Fix further metrics dependency issues [#5457]", "6.5.3\n----------", "- Don't require metrics code without explicit opt-in [#5456]", "6.5.2\n----------", "- [Job Metrics are under active development, help wanted!](https://github.com/sidekiq/sidekiq/wiki/Metrics#contributing) **BETA**\n- Add `Context` column on queue page which shows any CurrentAttributes [#5450]\n- `sidekiq_retry_in` may now return `:discard` or `:kill` to dynamically stop job retries [#5406]\n- Smarter sorting of processes in /busy Web UI [#5398]\n- Fix broken hamburger menu in mobile UI [#5428]\n- Require redis-rb 4.5.0. Note that Sidekiq will break if you use the\n [`Redis.exists_returns_integer = false`](https://github.com/redis/redis-rb/blob/master/CHANGELOG.md#450) flag. [#5394]", "6.5.1\n----------", "- Fix `push_bulk` breakage [#5387]", "6.5.0\n---------", "- Substantial refactoring of Sidekiq server internals, part of a larger effort\n to reduce Sidekiq's internal usage of global methods and data, see [docs/global_to_local.md](docs/global_to_local.md) and [docs/middleware.md](docs/middleware.md).\n- **Add beta support for the `redis-client` gem**. This will become the default Redis driver in Sidekiq 7.0. [#5298]\n Read more: https://github.com/sidekiq/sidekiq/wiki/Using-redis-client\n- **Add beta support for DB transaction-aware client** [#5291]\n Add this line to your initializer and any jobs created during a transaction\n will only be pushed to Redis **after the transaction commits**. You will need to add the\n `after_commit_everywhere` gem to your Gemfile.\n```ruby\nSidekiq.transactional_push!\n```\n This feature does not have a lot of production usage yet; please try it out and let us\n know if you have any issues. It will be fully supported in Sidekiq 7.0 or removed if it\n proves problematic.\n- Fix regression with middleware arguments [#5312]", "6.4.2\n---------", "- Strict argument checking now runs after client-side middleware [#5246]\n- Fix page events with live polling [#5184]\n- Many under-the-hood changes to remove all usage of the term \"worker\"\n from the Sidekiq codebase and APIs. This mostly involved RDoc and local\n variable names but a few constants and public APIs were changed. The old\n APIs will be removed in Sidekiq 7.0.\n```\nSidekiq::DEFAULT_WORKER_OPTIONS -> Sidekiq.default_job_options\nSidekiq.default_worker_options -> Sidekiq.default_job_options\nSidekiq::Queues[\"default\"].jobs_by_worker(HardJob) -> Sidekiq::Queues[\"default\"].jobs_by_class(HardJob)\n```", "6.4.1\n---------", "- Fix pipeline/multi deprecations in redis-rb 4.6\n- Fix sidekiq.yml YAML load errors on Ruby 3.1 [#5141]\n- Sharding support for `perform_bulk` [#5129]\n- Refactor job logger for SPEEEEEEED", "6.4.0\n---------", "- **SECURITY**: Validate input to avoid possible DoS in Web UI.\n- Add **strict argument checking** [#5071]\n Sidekiq will now log a warning if JSON-unsafe arguments are passed to `perform_async`.\n Add `Sidekiq.strict_args!(false)` to your initializer to disable this warning.\n This warning will switch to an exception in Sidekiq 7.0.\n- Note that Delayed Extensions will be removed in Sidekiq 7.0 [#5076]\n- Add `perform_{inline,sync}` in Sidekiq::Job to run a job synchronously [#5061, hasan-ally]\n```ruby\nSomeJob.perform_async(args...)\nSomeJob.perform_sync(args...)\nSomeJob.perform_inline(args...)\n```\n You can also dynamically redirect a job to run synchronously:\n```ruby\nSomeJob.set(\"sync\": true).perform_async(args...) # will run via perform_inline\n```\n- Replace Sidekiq::Worker `app/workers` generator with Sidekiq::Job `app/sidekiq` generator [#5055]\n```\nbin/rails generate sidekiq:job ProcessOrderJob\n```\n- Fix job retries losing CurrentAttributes [#5090]\n- Tweak shutdown to give long-running threads time to cleanup [#5095]", "6.3.1\n---------", "- Fix keyword arguments error with CurrentAttributes on Ruby 3.0 [#5048]", "6.3.0\n---------", "- **BREAK**: The Web UI has been refactored to remove jQuery. Any UI extensions\n which use jQuery will break.\n- **FEATURE**: Sidekiq.logger has been enhanced so any `Rails.logger`\n output in jobs now shows up in the Sidekiq console. Remove any logger\n hacks in your initializer and see if it Just Works™ now. [#5021]\n- **FEATURE**: Add `Sidekiq::Job` alias for `Sidekiq::Worker`, to better\n reflect industry standard terminology. You can now do this:\n```ruby\nclass MyJob\n include Sidekiq::Job\n sidekiq_options ...\n def perform(args)\n end\nend\n```\n- **FEATURE**: Support for serializing ActiveSupport::CurrentAttributes into each job. [#4982]\n```ruby\n# config/initializers/sidekiq.rb\nrequire \"sidekiq/middleware/current_attributes\"\nSidekiq::CurrentAttributes.persist(Myapp::Current) # Your AS::CurrentAttributes singleton\n```\n- **FEATURE**: Add `Sidekiq::Worker.perform_bulk` for enqueuing jobs in bulk,\n similar to `Sidekiq::Client.push_bulk` [#5042]\n```ruby\nMyJob.perform_bulk([[1], [2], [3]])\n```\n- Implement `queue_as`, `wait` and `wait_until` for ActiveJob compatibility [#5003]\n- Scheduler now uses Lua to reduce Redis load and network roundtrips [#5044]\n- Retry Redis operation if we get an `UNBLOCKED` Redis error [#4985]\n- Run existing signal traps, if any, before running Sidekiq's trap [#4991]\n- Fix fetch bug when using weighted queues which caused Sidekiq to stop\n processing queues randomly [#5031]", "6.2.2\n---------", "- Reduce retry jitter, add jitter to `sidekiq_retry_in` values [#4957]\n- Minimize scheduler load on Redis at scale [#4882]\n- Improve logging of delay jobs [#4904, BuonOno]\n- Minor CSS improvements for buttons and tables, design PRs always welcome!\n- Tweak Web UI `Cache-Control` header [#4966]\n- Rename internal API class `Sidekiq::Job` to `Sidekiq::JobRecord` [#4955]", "6.2.1\n---------", "- Update RTT warning logic to handle transient RTT spikes [#4851]\n- Fix very low priority CVE on unescaped queue name [#4852]\n- Add note about sessions and Rails apps in API mode", "6.2.0\n---------", "- Store Redis RTT and log if poor [#4824]\n- Add process/thread stats to Busy page [#4806]\n- Improve Web UI on mobile devices [#4840]\n- **Refactor Web UI session usage** [#4804]\n Numerous people have hit \"Forbidden\" errors and struggled with Sidekiq's\n Web UI session requirement. If you have code in your initializer for\n Web sessions, it's quite possible it will need to be removed. Here's\n an overview:\n```\nSidekiq::Web needs a valid Rack session for CSRF protection. If this is a Rails app,\nmake sure you mount Sidekiq::Web *inside* your routes in `config/routes.rb` so\nSidekiq can reuse the Rails session:", " Rails.application.routes.draw do\n mount Sidekiq::Web => \"/sidekiq\"\n ....\n end", "If this is a bare Rack app, use a session middleware before Sidekiq::Web:", " # first, use IRB to create a shared secret key for sessions and commit it\n require 'securerandom'; File.open(\".session.key\", \"w\") {|f| f.write(SecureRandom.hex(32)) }", " # now, update your Rack app to include the secret with a session cookie middleware\n use Rack::Session::Cookie, secret: File.read(\".session.key\"), same_site: true, max_age: 86400\n run Sidekiq::Web", "If this is a Rails app in API mode, you need to enable sessions.", " https://guides.rubyonrails.org/api_app.html#using-session-middlewares\n```", "6.1.3\n---------", "- Warn if Redis is configured to evict data under memory pressure [#4752]\n- Add process RSS on the Busy page [#4717]", "6.1.2\n---------", "- Improve readability in dark mode Web UI [#4674]\n- Fix Web UI crash with corrupt session [#4672]\n- Allow middleware to yield arguments [#4673, @eugeneius]\n- Migrate CI from CircleCI to GitHub Actions [#4677]", "6.1.1\n---------", "- Jobs are now sorted by age in the Busy Workers table. [#4641]\n- Fix \"check all\" JS logic in Web UI [#4619]", "6.1.0\n---------", "- Web UI - Dark Mode fixes [#4543, natematykiewicz]\n- Ensure `Rack::ContentLength` is loaded as middleware for correct Web UI responses [#4541]\n- Avoid exception dumping SSL store in Redis connection logging [#4532]\n- Better error messages in Sidekiq::Client [#4549]\n- Remove rack-protection, reimplement CSRF protection [#4588]\n- Require redis-rb 4.2 [#4591]\n- Update to jquery 1.12.4 [#4593]\n- Refactor internal fetch logic and API [#4602]", "6.0.7\n---------", "- Refactor systemd integration to work better with custom binaries [#4511]\n- Don't connect to Redis at process exit if not needed [#4502]\n- Remove Redis connection naming [#4479]\n- Fix Redis Sentinel password redaction [#4499]\n- Add Vietnamese locale (vi) [#4528]", "6.0.6\n---------", "- **Integrate with systemd's watchdog and notification features** [#4488]\n Set `Type=notify` in [sidekiq.service](https://github.com/sidekiq/sidekiq/blob/4b8a8bd3ae42f6e48ae1fdaf95ed7d7af18ed8bb/examples/systemd/sidekiq.service#L30-L39). The integration works automatically.\n- Use `setTimeout` rather than `setInterval` to avoid thundering herd [#4480]\n- Fix edge case where a job can be pushed without a queue.\n- Flush job stats at exit [#4498]\n- Check RAILS_ENV before RACK_ENV [#4493]\n- Add Lithuanian locale [#4476]", "6.0.5\n---------", "- Fix broken Web UI response when using NewRelic and Rack 2.1.2+. [#4440]\n- Update APIs to use `UNLINK`, not `DEL`. [#4449]\n- Fix Ruby 2.7 warnings [#4412]\n- Add support for `APP_ENV` [[95fa5d9]](https://github.com/sidekiq/sidekiq/commit/95fa5d90192148026e52ca2902f1b83c70858ce8)", "6.0.4\n---------", "- Fix ActiveJob's `sidekiq_options` integration [#4404]\n- Sidekiq Pro users will now see a Pause button next to each queue in\n the Web UI, allowing them to pause queues manually [#4374, shayonj]\n- Fix Sidekiq::Workers API unintentional change in 6.0.2 [#4387]", "\n6.0.3\n---------", "- Fix `Sidekiq::Client.push_bulk` API which was erroneously putting\n invalid `at` values in the job payloads [#4321]", "6.0.2\n---------", "- Fix Sidekiq Enterprise's rolling restart functionality, broken by refactoring in 6.0.0. [#4334]\n- More internal refactoring and performance tuning [fatkodima]", "6.0.1\n---------", "- **Performance tuning**, Sidekiq should be 10-15% faster now [#4303, 4299,\n 4269, fatkodima]\n- **Dark Mode support in Web UI** (further design polish welcome!) [#4227, mperham,\n fatkodima, silent-e]\n- **Job-specific log levels**, allowing you to turn on debugging for\n problematic workers. [fatkodima, #4287]\n```ruby\nMyWorker.set(log_level: :debug).perform_async(...)\n```\n- **Ad-hoc job tags**. You can tag your jobs with, e.g, subdomain, tenant, country,\n locale, application, version, user/client, \"alpha/beta/pro/ent\", types of jobs,\n teams/people responsible for jobs, additional metadata, etc.\n Tags are shown on different pages with job listings. Sidekiq Pro users\n can filter based on them [fatkodima, #4280]\n```ruby\nclass MyWorker\n include Sidekiq::Worker\n sidekiq_options tags: ['bank-ops', 'alpha']\n ...\nend\n```\n- Fetch scheduled jobs in batches before pushing into specific queues.\n This will decrease enqueueing time of scheduled jobs by a third. [fatkodima, #4273]\n```\nScheduledSet with 10,000 jobs\nBefore: 56.6 seconds\nAfter: 39.2 seconds\n```\n- Compress error backtraces before pushing into Redis, if you are\n storing error backtraces, this will halve the size of your RetrySet\n in Redis [fatkodima, #4272]\n```\nRetrySet with 100,000 jobs\nBefore: 261 MB\nAfter: 129 MB\n```\n- Support display of ActiveJob 6.0 payloads in the Web UI [#4263]\n- Add `SortedSet#scan` for pattern based scanning. For large sets this API will be **MUCH** faster\n than standard iteration using each. [fatkodima, #4262]\n```ruby\n Sidekiq::DeadSet.new.scan(\"UnreliableApi\") do |job|\n job.retry\n end\n```\n- Dramatically speed up SortedSet#find\\_job(jid) by using Redis's ZSCAN\n support, approx 10x faster. [fatkodima, #4259]\n```\nzscan 0.179366 0.047727 0.227093 ( 1.161376)\nenum 8.522311 0.419826 8.942137 ( 9.785079)\n```\n- Respect rails' generators `test_framework` option and gracefully handle extra `worker` suffix on generator [fatkodima, #4256]\n- Add ability to sort 'Enqueued' page on Web UI by position in the queue [fatkodima, #4248]\n- Support `Client.push_bulk` with different delays [fatkodima, #4243]\n```ruby\nSidekiq::Client.push_bulk(\"class\" => FooJob, \"args\" => [[1], [2]], \"at\" => [1.minute.from_now.to_f, 5.minutes.from_now.to_f])\n```\n- Easier way to test enqueuing specific ActionMailer and ActiveRecord delayed jobs. Instead of manually\n parsing embedded class, you can now test by fetching jobs for specific classes. [fatkodima, #4292]\n```ruby\nassert_equal 1, Sidekiq::Extensions::DelayedMailer.jobs_for(FooMailer).size\n```\n- Add `sidekiqmon` to gemspec executables [#4242]\n- Gracefully handle `Sidekiq.logger = nil` [#4240]\n- Inject Sidekiq::LogContext module if user-supplied logger does not include it [#4239]", "6.0\n---------", "This release has major breaking changes. Read and test carefully in production.", "- With Rails 6.0.2+, ActiveJobs can now use `sidekiq_options` directly to configure Sidekiq\n features/internals like the retry subsystem. [#4213, pirj]\n```ruby\nclass MyJob < ActiveJob::Base\n queue_as :myqueue\n sidekiq_options retry: 10, backtrace: 20\n def perform(...)\n end\nend\n```\n- Logging has been redesigned to allow for pluggable log formatters:\n```ruby\nSidekiq.configure_server do |config|\n config.log_formatter = Sidekiq::Logger::Formatters::JSON.new\nend\n```\nSee the [Logging wiki page](https://github.com/sidekiq/sidekiq/wiki/Logging) for more details.\n- **BREAKING CHANGE** Validate proper usage of the `REDIS_PROVIDER`\n variable. This variable is meant to hold the name of the environment\n variable which contains your Redis URL, so that you can switch Redis\n providers quickly and easily with a single variable change. It is not\n meant to hold the actual Redis URL itself. If you want to manually set\n the Redis URL (not recommended as it implies you have no failover),\n then you may set `REDIS_URL` directly. [#3969]\n- **BREAKING CHANGE** Increase default shutdown timeout from 8 seconds\n to 25 seconds. Both Heroku and ECS now use 30 second shutdown timeout\n by default and we want Sidekiq to take advantage of this time. If you\n have deployment scripts which depend on the old default timeout, use `-t 8` to\n get the old behavior. [#3968]\n- **BREAKING CHANGE** Remove the daemonization, logfile and pidfile\n arguments to Sidekiq. Use a proper process supervisor (e.g. systemd or\n foreman) to manage Sidekiq. See the Deployment wiki page for links to\n more resources.\n- Integrate the StandardRB code formatter to ensure consistent code\n styling. [#4114, gearnode]", "5.2.10\n---------", "- Backport fix for CVE-2022-23837.\n- Migrate to `exists?` for redis-rb.\n- Lock redis-rb to <4.6 to avoid deprecations.", "5.2.9\n---------", "- Release Rack lock due to a cascade of CVEs. [#4566]\n Pro-tip: don't lock Rack.", "5.2.8\n---------", "- Lock to Rack 2.0.x to prevent future incompatibilities\n- Fix invalid reference in `sidekiqctl`", "5.2.7\n---------", "- Fix stale `enqueued_at` when retrying [#4149]\n- Move build to [Circle CI](https://circleci.com/gh/mperham/sidekiq) [#4120]", "5.2.6\n---------", "- Fix edge case where a job failure during Redis outage could result in a lost job [#4141]\n- Better handling of malformed job arguments in payload [#4095]\n- Restore bootstap's dropdown css component [#4099, urkle]\n- Display human-friendly time diff for longer queue latencies [#4111, interlinked]\n- Allow `Sidekiq::Worker#set` to be chained", "5.2.5\n---------", "- Fix default usage of `config/sidekiq.yml` [#4077, Tensho]", "5.2.4\n---------", "- Add warnings for various deprecations and changes coming in Sidekiq 6.0.\n See the 6-0 branch. [#4056]\n- Various improvements to the Sidekiq test suite and coverage [#4026, #4039, Tensho]", "5.2.3\n---------", "- Warning message on invalid REDIS\\_PROVIDER [#3970]\n- Add `sidekiqctl status` command [#4003, dzunk]\n- Update elapsed time calculatons to use monotonic clock [#3999]\n- Fix a few issues with mobile Web UI styling [#3973, navied]\n- Jobs with `retry: false` now go through the global `death_handlers`,\n meaning you can take action on failed ephemeral jobs. [#3980, Benjamin-Dobell]\n- Fix race condition in defining Workers. [#3997, mattbooks]", "5.2.2\n---------", "- Raise error for duplicate queue names in config to avoid unexpected fetch algorithm change [#3911]\n- Fix concurrency bug on JRuby [#3958, mattbooks]\n- Add \"Kill All\" button to the retries page [#3938]", "5.2.1\n-----------", "- Fix concurrent modification error during heartbeat [#3921]", "5.2.0\n-----------", "- **Decrease default concurrency from 25 to 10** [#3892]\n- Verify connection pool sizing upon startup [#3917]\n- Smoother scheduling for large Sidekiq clusters [#3889]\n- Switch Sidekiq::Testing impl from alias\\_method to Module#prepend, for resiliency [#3852]\n- Update Sidekiq APIs to use SCAN for scalability [#3848, ffiller]\n- Remove concurrent-ruby gem dependency [#3830]\n- Optimize Web UI's bootstrap.css [#3914]", "5.1.3\n-----------", "- Fix version comparison so Ruby 2.2.10 works. [#3808, nateberkopec]", "5.1.2\n-----------", "- Add link to docs in Web UI footer\n- Fix crash on Ctrl-C in Windows [#3775, Bernica]\n- Remove `freeze` calls on String constants. This is superfluous with Ruby\n 2.3+ and `frozen_string_literal: true`. [#3759]\n- Fix use of AR middleware outside of Rails [#3787]\n- Sidekiq::Worker `sidekiq_retry_in` block can now return nil or 0 to use\n the default backoff delay [#3796, dsalahutdinov]", "5.1.1\n-----------", "- Fix Web UI incompatibility with Redis 3.x gem [#3749]", "5.1.0\n-----------", "- **NEW** Global death handlers - called when your job exhausts all\n retries and dies. Now you can take action when a job fails permanently. [#3721]\n- **NEW** Enable ActiveRecord query cache within jobs by default [#3718, sobrinho]\n This will prevent duplicate SELECTS; cache is cleared upon any UPDATE/INSERT/DELETE.\n See the issue for how to bypass the cache or disable it completely.\n- Scheduler timing is now more accurate, 15 -> 5 seconds [#3734]\n- Exceptions during the :startup event will now kill the process [#3717]\n- Make `Sidekiq::Client.via` reentrant [#3715]\n- Fix use of Sidekiq logger outside of the server process [#3714]\n- Tweak `constantize` to better match Rails class lookup. [#3701, caffeinated-tech]", "5.0.5\n-----------", "- Update gemspec to allow newer versions of the Redis gem [#3617]\n- Refactor Worker.set so it can be memoized [#3602]\n- Fix display of Redis URL in web footer, broken in 5.0.3 [#3560]\n- Update `Sidekiq::Job#display_args` to avoid mutation [#3621]", "5.0.4\n-----------", "- Fix \"slow startup\" performance regression from 5.0.2. [#3525]\n- Allow users to disable ID generation since some redis providers disable the CLIENT command. [#3521]", "5.0.3\n-----------", "- Fix overriding `class_attribute` core extension from ActiveSupport with Sidekiq one [PikachuEXE, #3499]\n- Allow job logger to be overridden [AlfonsoUceda, #3502]\n- Set a default Redis client identifier for debugging [#3516]\n- Fix \"Uninitialized constant\" errors on startup with the delayed extensions [#3509]", "5.0.2\n-----------", "- fix broken release, thanks @nateberkopec", "5.0.1\n-----------", "- Fix incorrect server identity when daemonizing [jwilm, #3496]\n- Work around error running Web UI against Redis Cluster [#3492]\n- Remove core extensions, Sidekiq is now monkeypatch-free! [#3474]\n- Reimplement Web UI's HTTP\\_ACCEPT\\_LANGUAGE parsing because the spec is utterly\n incomprehensible for various edge cases. [johanlunds, natematykiewicz, #3449]\n- Update `class_attribute` core extension to avoid warnings\n- Expose `job_hash_context` from `Sidekiq::Logging` to support log customization", "5.0.0\n-----------", "- **BREAKING CHANGE** Job dispatch was refactored for safer integration with\n Rails 5. The **Logging** and **RetryJobs** server middleware were removed and\n functionality integrated directly into Sidekiq::Processor. These aren't\n commonly used public APIs so this shouldn't impact most users.\n```\nSidekiq::Middleware::Server::RetryJobs -> Sidekiq::JobRetry\nSidekiq::Middleware::Server::Logging -> Sidekiq::JobLogger\n```\n- Quieting Sidekiq is now done via the TSTP signal, the USR1 signal is deprecated.\n- The `delay` extension APIs are no longer available by default, you\n must opt into them.\n- The Web UI is now BiDi and can render RTL languages like Arabic, Farsi and Hebrew.\n- Rails 3.2 and Ruby 2.0 and 2.1 are no longer supported.\n- The `SomeWorker.set(options)` API was re-written to avoid thread-local state. [#2152]\n- Sidekiq Enterprise's encrypted jobs now display \"[encrypted data]\" in the Web UI instead\n of random hex bytes.\n- Please see the [5.0 Upgrade notes](docs/5.0-Upgrade.md) for more detail.", "4.2.10\n-----------", "- Scheduled jobs can now be moved directly to the Dead queue via API [#3390]\n- Fix edge case leading to job duplication when using Sidekiq Pro's\n reliability feature [#3388]\n- Fix error class name display on retry page [#3348]\n- More robust latency calculation [#3340]", "4.2.9\n-----------", "- Rollback [#3303] which broke Heroku Redis users [#3311]\n- Add support for TSTP signal, for Sidekiq 5.0 forward compatibility. [#3302]", "4.2.8\n-----------", "- Fix rare edge case with Redis driver that can create duplicate jobs [#3303]\n- Fix Rails 5 loading issue [#3275]\n- Restore missing tooltips to timestamps in Web UI [#3310]\n- Work on **Sidekiq 5.0** is now active! [#3301]", "4.2.7\n-----------", "- Add new integration testing to verify code loading and job execution\n in development and production modes with Rails 4 and 5 [#3241]\n- Fix delayed extensions in development mode [#3227, DarthSim]\n- Use Worker's `retry` default if job payload does not have a retry\n attribute [#3234, mlarraz]", "4.2.6\n-----------", "- Run Rails Executor when in production [#3221, eugeneius]", "4.2.5\n-----------", "- Re-enable eager loading of all code when running non-development Rails 5. [#3203]\n- Better root URL handling for zany web servers [#3207]", "4.2.4\n-----------", "- Log errors coming from the Rails 5 reloader. [#3212, eugeneius]\n- Clone job data so middleware changes don't appear in Busy tab", "4.2.3\n-----------", "- Disable use of Rails 5's Reloader API in non-development modes, it has proven\n to be unstable under load [#3154]\n- Allow disabling of Sidekiq::Web's cookie session to handle the\n case where the app provides a session already [#3180, inkstak]\n```ruby\nSidekiq::Web.set :sessions, false\n```\n- Fix Web UI sharding support broken in 4.2.2. [#3169]\n- Fix timestamps not updating during UI polling [#3193, shaneog]\n- Relax rack-protection version to >= 1.5.0\n- Provide consistent interface to exception handlers, changing the structure of the context hash. [#3161]", "4.2.2\n-----------", "- Fix ever-increasing cookie size with nginx [#3146, cconstantine]\n- Fix so Web UI works without trailing slash [#3158, timdorr]", "4.2.1\n-----------", "- Ensure browser does not cache JSON/AJAX responses. [#3136]\n- Support old Sinatra syntax for setting config [#3139]", "4.2.0\n-----------", "- Enable development-mode code reloading. **With Rails 5.0+, you don't need\n to restart Sidekiq to pick up your Sidekiq::Worker changes anymore!** [#2457]\n- **Remove Sinatra dependency**. Sidekiq's Web UI now uses Rack directly.\n Thank you to Sidekiq's newest committer, **badosu**, for writing the code\n and doing a lot of testing to ensure compatibility with many different\n 3rd party plugins. If your Web UI works with 4.1.4 but fails with\n 4.2.0, please open an issue. [#3075]\n- Allow tuning of concurrency with the `RAILS_MAX_THREADS` env var. [#2985]\n This is the same var used by Puma so you can tune all of your systems\n the same way:\n```sh\nweb: RAILS_MAX_THREADS=5 bundle exec puma ...\nworker: RAILS_MAX_THREADS=10 bundle exec sidekiq ...\n```\nUsing `-c` or `config/sidekiq.yml` overrides this setting. I recommend\nadjusting your `config/database.yml` to use it too so connections are\nauto-scaled:\n```yaml\n pool: <%= ENV['RAILS_MAX_THREADS'] || 5 %>\n```", "4.1.4\n-----------", "- Unlock Sinatra so a Rails 5.0 compatible version may be used [#3048]\n- Fix race condition on startup with JRuby [#3043]", "\n4.1.3\n-----------", "- Please note the Redis 3.3.0 gem has a [memory leak](https://github.com/redis/redis-rb/issues/612),\n Redis 3.2.2 is recommended until that issue is fixed.\n- Sinatra 1.4.x is now a required dependency, avoiding cryptic errors\n and old bugs due to people not upgrading Sinatra for years. [#3042]\n- Fixed race condition in heartbeat which could rarely lead to lingering\n processes on the Busy tab. [#2982]\n```ruby\n# To clean up lingering processes, modify this as necessary to connect to your Redis.\n# After 60 seconds, lingering processes should disappear from the Busy page.", "require 'redis'\nr = Redis.new(url: \"redis://localhost:6379/0\")\n# uncomment if you need a namespace\n#require 'redis-namespace'\n#r = Redis::Namespace.new(\"foo\", r)\nr.smembers(\"processes\").each do |pro|\n r.expire(pro, 60)\n r.expire(\"#{pro}:workers\", 60)\nend\n```", "\n4.1.2\n-----------", "- Fix Redis data leak with worker data when a busy Sidekiq process\n crashes. You can find and expire leaked data in Redis with this\nscript:\n```bash\n$ redis-cli keys \"*:workers\" | while read LINE ; do TTL=`redis-cli expire \"$LINE\" 60`; echo \"$LINE\"; done;\n```\n Please note that `keys` can be dangerous to run on a large, busy Redis. Caveat runner.\n- Freeze all string literals with Ruby 2.3. [#2741]\n- Client middleware can now stop bulk job push. [#2887]", "4.1.1\n-----------", "- Much better behavior when Redis disappears and comes back. [#2866]\n- Update FR locale [dbachet]\n- Don't fill logfile in case of Redis downtime [#2860]\n- Allow definition of a global retries_exhausted handler. [#2807]\n```ruby\nSidekiq.configure_server do |config|\n config.default_retries_exhausted = -> (job, ex) do\n Sidekiq.logger.info \"#{job['class']} job is now dead\"\n end\nend\n```", "4.1.0\n-----------", "- Tag quiet processes in the Web UI [#2757, jcarlson]\n- Pass last exception to sidekiq\\_retries\\_exhausted block [#2787, Nowaker]\n```ruby\nclass MyWorker\n include Sidekiq::Worker\n sidekiq_retries_exhausted do |job, exception|\n end\nend\n```\n- Add native support for ActiveJob's `set(options)` method allowing\nyou to override worker options dynamically. This should make it\neven easier to switch between ActiveJob and Sidekiq's native APIs [#2780]\n```ruby\nclass MyWorker\n include Sidekiq::Worker\n sidekiq_options queue: 'default', retry: true", " def perform(*args)\n # do something\n end\nend", "MyWorker.set(queue: 'high', retry: false).perform_async(1)\n```", "4.0.2\n-----------", "- Better Japanese translations\n- Remove `json` gem dependency from gemspec. [#2743]\n- There's a new testing API based off the `Sidekiq::Queues` namespace. All\n assertions made against the Worker class still work as expected.\n [#2676, brandonhilkert]\n```ruby\nassert_equal 0, Sidekiq::Queues[\"default\"].size\nHardWorker.perform_async(\"log\")\nassert_equal 1, Sidekiq::Queues[\"default\"].size\nassert_equal \"log\", Sidekiq::Queues[\"default\"].first['args'][0]\nSidekiq::Queues.clear_all\n```", "4.0.1\n-----------", "- Yank new queue-based testing API [#2663]\n- Fix invalid constant reference in heartbeat", "4.0.0\n-----------", "- Sidekiq's internals have been completely overhauled for performance\n and to remove dependencies. This has resulted in major speedups, as\n [detailed on my blog](http://www.mikeperham.com/2015/10/14/optimizing-sidekiq/).\n- See the [4.0 upgrade notes](docs/4.0-Upgrade.md) for more detail.", "3.5.4\n-----------", "- Ensure exception message is a string [#2707]\n- Revert racy Process.kill usage in sidekiqctl", "3.5.3\n-----------", "- Adjust shutdown event to run in parallel with the rest of system shutdown. [#2635]", "3.5.2\n-----------", "- **Sidekiq 3 is now in maintenance mode**, only major bugs will be fixed.\n- The exception triggering a retry is now passed into `sidekiq_retry_in`,\n allowing you to retry more frequently for certain types of errors.\n [#2619, kreynolds]\n```ruby\n sidekiq_retry_in do |count, ex|\n case ex\n when RuntimeError\n 5 * count\n else\n 10 * count\n end\n end\n```", "3.5.1\n-----------", "- **FIX MEMORY LEAK** Under rare conditions, threads may leak [#2598, gazay]\n- Add Ukrainian locale [#2561, elrakita]\n- Disconnect and retry Redis operations if we see a READONLY error [#2550]\n- Add server middleware testing harness; see [wiki](https://github.com/sidekiq/sidekiq/wiki/Testing#testing-server-middleware) [#2534, ryansch]", "3.5.0\n-----------", "- Polished new banner! [#2522, firedev]\n- Upgrade to Celluloid 0.17. [#2420, digitalextremist]\n- Activate sessions in Sinatra for CSRF protection, requires Rails\n monkeypatch due to rails/rails#15843. [#2460, jc00ke]", "3.4.2\n-----------", "- Don't allow `Sidekiq::Worker` in ActiveJob::Base classes. [#2424]\n- Safer display of job data in Web UI [#2405]\n- Fix CSRF vulnerability in Web UI, thanks to Egor Homakov for\n reporting. [#2422] If you are running the Web UI as a standalone Rack app,\n ensure you have a [session middleware\nconfigured](https://github.com/sidekiq/sidekiq/wiki/Monitoring#standalone):\n```ruby\nuse Rack::Session::Cookie, :secret => \"some unique secret string here\"\n```", "3.4.1\n-----------", "- Lock to Celluloid 0.16", "\n3.4.0\n-----------", "- Set a `created_at` attribute when jobs are created, set `enqueued_at` only\n when they go into a queue. Fixes invalid latency calculations with scheduled jobs.\n [#2373, mrsimo]\n- Don't log timestamp on Heroku [#2343]\n- Run `shutdown` event handlers in reverse order of definition [#2374]\n- Rename and rework `poll_interval` to be simpler, more predictable [#2317, cainlevy]\n The new setting is `average_scheduled_poll_interval`. To configure\n Sidekiq to look for scheduled jobs every 5 seconds, just set it to 5.\n```ruby\nSidekiq.configure_server do |config|\n config.average_scheduled_poll_interval = 5\nend\n```", "3.3.4\n-----------", "- **Improved ActiveJob integration** - Web UI now shows ActiveJobs in a\n nicer format and job logging shows the actual class name, requires\n Rails 4.2.2+ [#2248, #2259]\n- Add Sidekiq::Process#dump\\_threads API to trigger TTIN output [#2247]\n- Web UI polling now uses Ajax to avoid page reload [#2266, davydovanton]\n- Several Web UI styling improvements [davydovanton]\n- Add Tamil, Hindi translations for Web UI [ferdinandrosario, tejasbubane]\n- Fix Web UI to work with country-specific locales [#2243]\n- Handle circular error causes [#2285, eugenk]", "3.3.3\n-----------", "- Fix crash on exit when Redis is down [#2235]\n- Fix duplicate logging on startup\n- Undeprecate delay extension for ActionMailer 4.2+ . [#2186]", "3.3.2\n-----------", "- Add Sidekiq::Stats#queues back\n- Allows configuration of dead job set size and timeout [#2173, jonhyman]\n- Refactor scheduler enqueuing so Sidekiq Pro can override it. [#2159]", "3.3.1\n-----------", "- Dumb down ActionMailer integration so it tries to deliver if possible [#2149]\n- Stringify Sidekiq.default\\_worker\\_options's keys [#2126]\n- Add random integer to process identity [#2113, michaeldiscala]\n- Log Sidekiq Pro's Batch ID if available [#2076]\n- Refactor Processor Redis usage to avoid redis/redis-rb#490 [#2094]\n- Move /dashboard/stats to /stats. Add /stats/queues. [moserke, #2099]\n- Add processes count to /stats [ismaelga, #2141]\n- Greatly improve speed of Sidekiq::Stats [ismaelga, #2142]\n- Add better usage text for `sidekiqctl`.\n- `Sidekiq::Logging.with_context` is now a stack so you can set your\n own job context for logging purposes [grosser, #2110]\n- Remove usage of Google Fonts in Web UI so it loads in China [#2144]", "3.3.0\n-----------", "- Upgrade to Celluloid 0.16 [#2056]\n- Fix typo for generator test file name [dlackty, #2016]\n- Add Sidekiq::Middleware::Chain#prepend [seuros, #2029]", "3.2.6\n-----------", "- Deprecate delay extension for ActionMailer 4.2+ . [seuros, #1933]\n- Poll interval tuning now accounts for dead processes [epchris, #1984]\n- Add non-production environment to Web UI page titles [JacobEvelyn, #2004]", "3.2.5\n-----------", "- Lock Celluloid to 0.15.2 due to bugs in 0.16.0. This prevents the\n \"hang on shutdown\" problem with Celluloid 0.16.0.", "3.2.4\n-----------", "- Fix issue preventing ActionMailer sends working in some cases with\n Rails 4. [pbhogan, #1923]", "3.2.3\n-----------", "- Clean invalid bytes from error message before converting to JSON (requires Ruby 2.1+) [#1705]\n- Add queues list for each process to the Busy page. [davetoxa, #1897]\n- Fix for crash caused by empty config file. [jordan0day, #1901]\n- Add Rails Worker generator, `rails g sidekiq:worker User` will create `app/workers/user_worker.rb`. [seuros, #1909]\n- Fix Web UI rendering with huge job arguments [jhass, #1918]\n- Minor refactoring of Sidekiq::Client internals, for Sidekiq Pro. [#1919]", "3.2.2\n-----------", "- **This version of Sidekiq will no longer start on Ruby 1.9.** Sidekiq\n 3 does not support MRI 1.9 but we've allowed it to run before now.\n- Fix issue which could cause Sidekiq workers to disappear from the Busy\n tab while still being active [#1884]\n- Add \"Back to App\" button in Web UI. You can set the button link via\n `Sidekiq::Web.app_url = 'http://www.mysite.com'` [#1875, seuros]\n- Add process tag (`-g tag`) to the Busy page so you can differentiate processes at a glance. [seuros, #1878]\n- Add \"Kill\" button to move retries directly to the DJQ so they don't retry. [seuros, #1867]", "3.2.1\n-----------", "- Revert eager loading change for Rails 3.x apps, as it broke a few edge\n cases.", "3.2.0\n-----------", "- **Fix issue which caused duplicate job execution in Rails 3.x**\n This issue is caused by [improper exception handling in ActiveRecord](https://github.com/rails/rails/blob/3-2-stable/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb#L281) which changes Sidekiq's Shutdown exception into a database\n error, making Sidekiq think the job needs to be retried. **The fix requires Ruby 2.1**. [#1805]\n- Update how Sidekiq eager loads Rails application code [#1791, jonleighton]\n- Change logging timestamp to show milliseconds.\n- Reverse sorting of Dead tab so newer jobs are listed first [#1802]", "3.1.4\n-----------", "- Happy π release!\n- Self-tuning Scheduler polling, we use heartbeat info to better tune poll\\_interval [#1630]\n- Remove all table column width rules, hopefully get better column formatting [#1747]\n- Handle edge case where YAML can't be decoded in dev mode [#1761]\n- Fix lingering jobs in Busy page on Heroku [#1764]", "3.1.3\n-----------", "- Use ENV['DYNO'] on Heroku for hostname display, rather than an ugly UUID. [#1742]\n- Show per-process labels on the Busy page, for feature tagging [#1673]", "\n3.1.2\n-----------", "- Suitably chastised, @mperham reverts the Bundler change.", "\n3.1.1\n-----------", "- Sidekiq::CLI now runs `Bundler.require(:default, environment)` to boot all gems\n before loading any app code.\n- Sort queues by name in Web UI [#1734]", "\n3.1.0\n-----------", "- New **remote control** feature: you can remotely trigger Sidekiq to quiet\n or terminate via API, without signals. This is most useful on JRuby\n or Heroku which does not support the USR1 'quiet' signal. Now you can\n run a rake task like this at the start of your deploy to quiet your\n set of Sidekiq processes. [#1703]\n```ruby\nnamespace :sidekiq do\n task :quiet => :environment do\n Sidekiq::ProcessSet.new.each(&:quiet!)\n end\nend\n```\n- The Web UI can use the API to quiet or stop all processes via the Busy page.\n- The Web UI understands and hides the `Sidekiq::Extensions::Delay*`\n classes, instead showing `Class.method` as the Job. [#1718]\n- Polish the Dashboard graphs a bit, update Rickshaw [brandonhilkert, #1725]\n- The poll interval is now configurable in the Web UI [madebydna, #1713]\n- Delay extensions can be removed so they don't conflict with\n DelayedJob: put `Sidekiq.remove_delay!` in your initializer. [devaroop, #1674]", "\n3.0.2\n-----------", "- Revert gemfile requirement of Ruby 2.0. JRuby 1.7 calls itself Ruby\n 1.9.3 and broke with this requirement.", "3.0.1\n-----------", "- Revert pidfile behavior from 2.17.5: Sidekiq will no longer remove its own pidfile\n as this is a race condition when restarting. [#1470, #1677]\n- Show warning on the Queues page if a queue is paused [#1672]\n- Only activate the ActiveRecord middleware if ActiveRecord::Base is defined on boot. [#1666]\n- Add ability to disable jobs going to the DJQ with the `dead` option.\n```ruby\nsidekiq_options :dead => false, :retry => 5\n```\n- Minor fixes", "\n3.0.0\n-----------", "Please see [3.0-Upgrade.md](docs/3.0-Upgrade.md) for more comprehensive upgrade notes.", "- **Dead Job Queue** - jobs which run out of retries are now moved to a dead\n job queue. These jobs must be retried manually or they will expire\n after 6 months or 10,000 jobs. The Web UI contains a \"Dead\" tab\n exposing these jobs. Use `sidekiq_options :retry => false` if you\ndon't wish jobs to be retried or put in the DJQ. Use\n`sidekiq_options :retry => 0` if you don't want jobs to retry but go\nstraight to the DJQ.\n- **Process Lifecycle Events** - you can now register blocks to run at\n certain points during the Sidekiq process lifecycle: startup, quiet and\n shutdown.\n```ruby\nSidekiq.configure_server do |config|\n config.on(:startup) do\n # do something\n end\nend\n```\n- **Global Error Handlers** - blocks of code which handle errors that\n occur anywhere within Sidekiq, not just within middleware.\n```ruby\nSidekiq.configure_server do |config|\n config.error_handlers << proc {|ex,ctx| ... }\nend\n```\n- **Process Heartbeat** - each Sidekiq process will ping Redis every 5\n seconds to give a summary of the Sidekiq population at work.\n- The Workers tab is now renamed to Busy and contains a list of live\n Sidekiq processes and jobs in progress based on the heartbeat.\n- **Shardable Client** - Sidekiq::Client instances can use a custom\n Redis connection pool, allowing very large Sidekiq installations to scale by\n sharding: sending different jobs to different Redis instances.\n```ruby\nclient = Sidekiq::Client.new(ConnectionPool.new { Redis.new })\nclient.push(...)\n```\n```ruby\nSidekiq::Client.via(ConnectionPool.new { Redis.new }) do\n FooWorker.perform_async\n BarWorker.perform_async\nend\n```\n **Sharding support does require a breaking change to client-side\nmiddleware, see docs/3.0-Upgrade.md.**\n- New Chinese, Greek, Swedish and Czech translations for the Web UI.\n- Updated most languages translations for the new UI features.\n- **Remove official Capistrano integration** - this integration has been\n moved into the [capistrano-sidekiq](https://github.com/seuros/capistrano-sidekiq) gem.\n- **Remove official support for MRI 1.9** - Things still might work but\n I no longer actively test on it.\n- **Remove built-in support for Redis-to-Go**.\n Heroku users: `heroku config:set REDIS_PROVIDER=REDISTOGO_URL`\n- **Remove built-in error integration for Airbrake, Honeybadger, ExceptionNotifier and Exceptional**.\n Each error gem should provide its own Sidekiq integration. Update your error gem to the latest\n version to pick up Sidekiq support.\n- Upgrade to connection\\_pool 2.0 which now creates connections lazily.\n- Remove deprecated Sidekiq::Client.registered\\_\\* APIs\n- Remove deprecated support for the old Sidekiq::Worker#retries\\_exhausted method.\n- Removed 'sidekiq/yaml\\_patch', this was never documented or recommended.\n- Removed --profile option, #1592\n- Remove usage of the term 'Worker' in the UI for clarity. Users would call both threads and\n processes 'workers'. Instead, use \"Thread\", \"Process\" or \"Job\".", "2.17.7\n-----------", "- Auto-prune jobs older than one hour from the Workers page [#1508]\n- Add Sidekiq::Workers#prune which can perform the auto-pruning.\n- Fix issue where a job could be lost when an exception occurs updating\n Redis stats before the job executes [#1511]", "2.17.6\n-----------", "- Fix capistrano integration due to missing pidfile. [#1490]", "2.17.5\n-----------", "- Automatically use the config file found at `config/sidekiq.yml`, if not passed `-C`. [#1481]\n- Store 'retried\\_at' and 'failed\\_at' timestamps as Floats, not Strings. [#1473]\n- A `USR2` signal will now reopen _all_ logs, using IO#reopen. Thus, instead of creating a new Logger object,\n Sidekiq will now just update the existing Logger's file descriptor [#1163].\n- Remove pidfile when shutting down if started with `-P` [#1470]", "2.17.4\n-----------", "- Fix JID support in inline testing, #1454\n- Polish worker arguments display in UI, #1453\n- Marshal arguments fully to avoid worker mutation, #1452\n- Support reverse paging sorted sets, #1098", "\n2.17.3\n-----------", "- Synchronously terminates the poller and fetcher to fix a race condition in bulk requeue during shutdown [#1406]", "2.17.2\n-----------", "- Fix bug where strictly prioritized queues might be processed out of\n order [#1408]. A side effect of this change is that it breaks a queue\n declaration syntax that worked, although only because of a bug—it was\n never intended to work and never supported. If you were declaring your\n queues as a comma-separated list, e.g. `sidekiq -q critical,default,low`,\n you must now use the `-q` flag before each queue, e.g.\n `sidekiq -q critical -q default -q low`.", "2.17.1\n-----------", "- Expose `delay` extension as `sidekiq_delay` also. This allows you to\n run Delayed::Job and Sidekiq in the same process, selectively porting\n `delay` calls to `sidekiq_delay`. You just need to ensure that\n Sidekiq is required **before** Delayed::Job in your Gemfile. [#1393]\n- Bump redis client required version to 3.0.6\n- Minor CSS fixes for Web UI", "2.17.0\n-----------", "- Change `Sidekiq::Client#push_bulk` to return an array of pushed `jid`s. [#1315, barelyknown]\n- Web UI refactoring to use more API internally (yummy dogfood!)\n- Much faster Sidekiq::Job#delete performance for larger queue sizes\n- Further capistrano 3 fixes\n- Many misc minor fixes", "2.16.1\n-----------", "- Revert usage of `resolv-replace`. MRI's native DNS lookup releases the GIL.\n- Fix several Capistrano 3 issues\n- Escaping dynamic data like job args and error messages in Sidekiq Web UI. [#1299, lian]", "2.16.0\n-----------", "- Deprecate `Sidekiq::Client.registered_workers` and `Sidekiq::Client.registered_queues`\n- Refactor Sidekiq::Client to be instance-based [#1279]\n- Pass all Redis options to the Redis driver so Unix sockets\n can be fully configured. [#1270, salimane]\n- Allow sidekiq-web extensions to add locale paths so extensions\n can be localized. [#1261, ondrejbartas]\n- Capistrano 3 support [#1254, phallstrom]\n- Use Ruby's `resolv-replace` to enable pure Ruby DNS lookups.\n This ensures that any DNS resolution that takes place in worker\n threads won't lock up the entire VM on MRI. [#1258]", "2.15.2\n-----------", "- Iterating over Sidekiq::Queue and Sidekiq::SortedSet will now work as\n intended when jobs are deleted [#866, aackerman]\n- A few more minor Web UI fixes [#1247]", "2.15.1\n-----------", "- Fix several Web UI issues with the Bootstrap 3 upgrade.", "2.15.0\n-----------", "- The Core Sidekiq actors are now monitored. If any crash, the\n Sidekiq process logs the error and exits immediately. This is to\n help prevent \"stuck\" Sidekiq processes which are running but don't\n appear to be doing any work. [#1194]\n- Sidekiq's testing behavior is now dynamic. You can choose between\n `inline` and `fake` behavior in your tests. See\n[Testing](https://github.com/sidekiq/sidekiq/wiki/Testing) for detail. [#1193]\n- The Retries table has a new column for the error message.\n- The Web UI topbar now contains the status and live poll button.\n- Orphaned worker records are now auto-vacuumed when you visit the\n Workers page in the Web UI.\n- Sidekiq.default\\_worker\\_options allows you to configure default\n options for all Sidekiq worker types.", "```ruby\nSidekiq.default_worker_options = { 'queue' => 'default', 'backtrace' => true }\n```\n- Added two Sidekiq::Client class methods for compatibility with resque-scheduler:\n `enqueue_to_in` and `enqueue_in` [#1212]\n- Upgrade Web UI to Bootstrap 3.0. [#1211, jeffboek]", "2.14.1\n-----------", "- Fix misc Web UI issues due to ERB conversion.\n- Bump redis-namespace version due to security issue.", "2.14.0\n-----------", "- Removed slim gem dependency, Web UI now uses ERB [Locke23rus, #1120]\n- Fix more race conditions in Web UI actions\n- Don't reset Job enqueued\\_at when retrying\n- Timestamp tooltips in the Web UI should use UTC\n- Fix invalid usage of handle\\_exception causing issues in Airbrake\n [#1134]", "\n2.13.1\n-----------", "- Make Sidekiq::Middleware::Chain Enumerable\n- Make summary bar and graphs responsive [manishval, #1025]\n- Adds a job status page for scheduled jobs [jonhyman]\n- Handle race condition in retrying and deleting jobs in the Web UI\n- The Web UI relative times are now i18n. [MadRabbit, #1088]\n- Allow for default number of retry attempts to be set for\n `Sidekiq::Middleware::Server::RetryJobs` middleware. [czarneckid] [#1091]", "```ruby\nSidekiq.configure_server do |config|\n config.server_middleware do |chain|\n chain.add Sidekiq::Middleware::Server::RetryJobs, :max_retries => 10\n end\nend\n```", "\n2.13.0\n-----------", "- Adding button to move scheduled job to main queue [guiceolin, #1020]\n- fix i18n support resetting saved locale when job is retried [#1011]\n- log rotation via USR2 now closes the old logger [#1008]\n- Add ability to customize retry schedule, like so [jmazzi, #1027]", "```ruby\nclass MyWorker\n include Sidekiq::Worker\n sidekiq_retry_in { |count| count * 2 }\nend\n```\n- Redesign Worker#retries\\_exhausted callback to use same form as above [jmazzi, #1030]", "```ruby\nclass MyWorker\n include Sidekiq::Worker\n sidekiq_retries_exhausted do |msg|\n Rails.logger.error \"Failed to process #{msg['class']} with args: #{msg['args']}\"\n end\nend\n```", "2.12.4\n-----------", "- Fix error in previous release which crashed the Manager when a\n Processor died.", "2.12.3\n-----------", "- Revert back to Celluloid's TaskFiber for job processing which has proven to be more\n stable than TaskThread. [#985]\n- Avoid possible lockup during hard shutdown [#997]", "At this point, if you are experiencing stability issues with Sidekiq in\nRuby 1.9, please try Ruby 2.0. It seems to be more stable.", "2.12.2\n-----------", "- Relax slim version requirement to >= 1.1.0\n- Refactor historical stats to use TTL, not explicit cleanup. [grosser, #971]", "2.12.1\n-----------", "- Force Celluloid 0.14.1 as 0.14.0 has a serious bug. [#954]\n- Scheduled and Retry jobs now use Sidekiq::Client to push\n jobs onto the queue, so they use client middleware. [dimko, #948]\n- Record the timestamp when jobs are enqueued. Add\n Sidekiq::Job#enqueued\\_at to query the time. [mariovisic, #944]\n- Add Sidekiq::Queue#latency - calculates diff between now and\n enqueued\\_at for the oldest job in the queue.\n- Add testing method `perform_one` that dequeues and performs a single job.\n This is mainly to aid testing jobs that spawn other jobs. [fumin, #963]", "2.12.0\n-----------", "- Upgrade to Celluloid 0.14, remove the use of Celluloid's thread\n pool. This should halve the number of threads in each Sidekiq\n process, thus requiring less resources. [#919]\n- Abstract Celluloid usage to Sidekiq::Actor for testing purposes.\n- Better handling for Redis downtime when fetching jobs and shutting\n down, don't print exceptions every second and print success message\n when Redis is back.\n- Fix unclean shutdown leading to duplicate jobs [#897]\n- Add Korean locale [#890]\n- Upgrade test suite to Minitest 5\n- Remove usage of `multi_json` as `json` is now robust on all platforms.", "2.11.2\n-----------", "- Fix Web UI when used without Rails [#886]\n- Add Sidekiq::Stats#reset [#349]\n- Add Norwegian locale.\n- Updates for the JA locale.", "2.11.1\n-----------", "- Fix timeout warning.\n- Add Dutch web UI locale.", "2.11.0\n-----------", "- Upgrade to Celluloid 0.13. [#834]\n- Remove **timeout** support from `sidekiq_options`. Ruby's timeout\n is inherently unsafe in a multi-threaded application and was causing\n stability problems for many. See http://bit.ly/OtYpK\n- Add Japanese locale for Web UI [#868]\n- Fix a few issues with Web UI i18n.", "2.10.1\n-----------", "- Remove need for the i18n gem. (brandonhilkert)\n- Improve redis connection info logging on startup for debugging\npurposes [#858]\n- Revert sinatra/slim as runtime dependencies\n- Add `find_job` method to sidekiq/api", "\n2.10.0\n-----------", "- Refactor algorithm for putting scheduled jobs onto the queue [#843]\n- Fix scheduler thread dying due to incorrect error handling [#839]\n- Fix issue which left stale workers if Sidekiq wasn't shutdown while\nquiet. [#840]\n- I18n for web UI. Please submit translations of `web/locales/en.yml` for\nyour own language. [#811]\n- 'sinatra', 'slim' and 'i18n' are now gem dependencies for Sidekiq.", "\n2.9.0\n-----------", "- Update 'sidekiq/testing' to work with any Sidekiq::Client call. It\n also serializes the arguments as using Redis would. [#713]\n- Raise a Sidekiq::Shutdown error within workers which don't finish within the hard\n timeout. This is to prevent unwanted database transaction commits. [#377]\n- Lazy load Redis connection pool, you no longer need to specify\n anything in Passenger or Unicorn's after_fork callback [#794]\n- Add optional Worker#retries_exhausted hook after max retries failed. [jkassemi, #780]\n- Fix bug in pagination link to last page [pitr, #774]\n- Upstart scripts for multiple Sidekiq instances [dariocravero, #763]\n- Use select via pipes instead of poll to catch signals [mrnugget, #761]", "2.8.0\n-----------", "- I18n support! Sidekiq can optionally save and restore the Rails locale\n so it will be properly set when your jobs execute. Just include\n `require 'sidekiq/middleware/i18n'` in your sidekiq initializer. [#750]\n- Fix bug which could lose messages when using namespaces and the message\nneeds to be requeued in Redis. [#744]\n- Refactor Redis namespace support [#747]. The redis namespace can no longer be\n passed via the config file, the only supported way is via Ruby in your\n initializer:", "```ruby\nsidekiq_redis = { :url => 'redis://localhost:3679', :namespace => 'foo' }\nSidekiq.configure_server { |config| config.redis = sidekiq_redis }\nSidekiq.configure_client { |config| config.redis = sidekiq_redis }\n```", "A warning is printed out to the log if a namespace is found in your sidekiq.yml.", "\n2.7.5\n-----------", "- Capistrano no longer uses daemonization in order to work with JRuby [#719]\n- Refactor signal handling to work on Ruby 2.0 [#728, #730]\n- Fix dashboard refresh URL [#732]", "2.7.4\n-----------", "- Fixed daemonization, was broken by some internal refactoring in 2.7.3 [#727]", "2.7.3\n-----------", "- Real-time dashboard is now the default web page\n- Make config file optional for capistrano\n- Fix Retry All button in the Web UI", "2.7.2\n-----------", "- Remove gem signing infrastructure. It was causing Sidekiq to break\nwhen used via git in Bundler. This is why we can't have nice things. [#688]", "\n2.7.1\n-----------", "- Fix issue with hard shutdown [#680]", "\n2.7.0\n-----------", "- Add -d daemonize flag, capistrano recipe has been updated to use it [#662]\n- Support profiling via `ruby-prof` with -p. When Sidekiq is stopped\n via Ctrl-C, it will output `profile.html`. You must add `gem 'ruby-prof'` to your Gemfile for it to work.\n- Dynamically update Redis stats on dashboard [brandonhilkert]\n- Add Sidekiq::Workers API giving programmatic access to the current\n set of active workers.", "```\nworkers = Sidekiq::Workers.new\nworkers.size => 2\nworkers.each do |name, work|\n # name is a unique identifier per Processor instance\n # work is a Hash which looks like:\n # { 'queue' => name, 'run_at' => timestamp, 'payload' => msg }\nend\n```", "- Allow environment-specific sections within the config file which\noverride the global values [dtaniwaki, #630]", "```\n---\n:concurrency: 50\n:verbose: false\nstaging:\n :verbose: true\n :concurrency: 5\n```", "\n2.6.5\n-----------", "- Several reliability fixes for job requeueing upon termination [apinstein, #622, #624]\n- Fix typo in capistrano recipe\n- Add `retry_queue` option so retries can be given lower priority [ryanlower, #620]", "```ruby\nsidekiq_options queue: 'high', retry_queue: 'low'\n```", "2.6.4\n-----------", "- Fix crash upon empty queue [#612]", "2.6.3\n-----------", "- sidekiqctl exits with non-zero exit code upon error [jmazzi]\n- better argument validation in Sidekiq::Client [karlfreeman]", "2.6.2\n-----------", "- Add Dashboard beacon indicating when stats are updated. [brandonhilkert, #606]\n- Revert issue with capistrano restart. [#598]", "2.6.1\n-----------", "- Dashboard now live updates summary stats also. [brandonhilkert, #605]\n- Add middleware chain APIs `insert_before` and `insert_after` for fine\n tuning the order of middleware. [jackrg, #595]", "2.6.0\n-----------", "- Web UI much more mobile friendly now [brandonhilkert, #573]\n- Enable live polling for every section in Web UI [brandonhilkert, #567]\n- Add Stats API [brandonhilkert, #565]\n- Add Stats::History API [brandonhilkert, #570]\n- Add Dashboard to Web UI with live and historical stat graphs [brandonhilkert, #580]\n- Add option to log output to a file, reopen log file on USR2 signal [mrnugget, #581]", "2.5.4\n-----------", "- `Sidekiq::Client.push` now accepts the worker class as a string so the\n Sidekiq client does not have to load your worker classes at all. [#524]\n- `Sidekiq::Client.push_bulk` now works with inline testing.\n- **Really** fix status icon in Web UI this time.\n- Add \"Delete All\" and \"Retry All\" buttons to Retries in Web UI", "\n2.5.3\n-----------", "- Small Web UI fixes\n- Add `delay_until` so you can delay jobs until a specific timestamp:", "```ruby\nAuction.delay_until(@auction.ends_at).close(@auction.id)\n```", "This is identical to the existing Sidekiq::Worker method, `perform_at`.", "2.5.2\n-----------", "- Remove asset pipeline from Web UI for much faster, simpler runtime. [#499, #490, #481]\n- Add -g option so the procline better identifies a Sidekiq process, defaults to File.basename(Rails.root). [#486]", " sidekiq 2.5.1 myapp [0 of 25 busy]", "- Add splay to retry time so groups of failed jobs don't fire all at once. [#483]", "2.5.1\n-----------", "- Fix issues with core\\_ext", "2.5.0\n-----------", "- REDESIGNED WEB UI! [unity, cavneb]\n- Support Honeybadger for error delivery\n- Inline testing runs the client middleware before executing jobs [#465]\n- Web UI can now remove jobs from queue. [#466, dleung]\n- Web UI can now show the full message, not just 100 chars [#464, dleung]\n- Add APIs for manipulating the retry and job queues. See sidekiq/api. [#457]", "\n2.4.0\n-----------", "- ActionMailer.delay.method now only tries to deliver if method returns a valid message.\n- Logging now uses \"MSG-#{Job ID}\", not a random msg ID\n- Allow generic Redis provider as environment variable. [#443]\n- Add ability to customize sidekiq\\_options with delay calls [#450]", "```ruby\nFoo.delay(:retry => false).bar\nFoo.delay(:retry => 10).bar\nFoo.delay(:timeout => 10.seconds).bar\nFoo.delay_for(5.minutes, :timeout => 10.seconds).bar\n```", "2.3.3\n-----------", "- Remove option to disable Rails hooks. [#401]\n- Allow delay of any module class method", "2.3.2\n-----------", "- Fix retry. 2.3.1 accidentally disabled it.", "2.3.1\n-----------", "- Add Sidekiq::Client.push\\_bulk for bulk adding of jobs to Redis.\n My own simple test case shows pushing 10,000 jobs goes from 5 sec to 1.5 sec.\n- Add support for multiple processes per host to Capistrano recipe\n- Re-enable Celluloid::Actor#defer to fix stack overflow issues [#398]", "2.3.0\n-----------", "- Upgrade Celluloid to 0.12\n- Upgrade Twitter Bootstrap to 2.1.0\n- Rescue more Exceptions\n- Change Job ID to be Hex, rather than Base64, for HTTP safety\n- Use `Airbrake#notify_or_ignore`", "2.2.1\n-----------", "- Add support for custom tabs to Sidekiq::Web [#346]\n- Change capistrano recipe to run 'quiet' before deploy:update\\_code so\n it is run upon both 'deploy' and 'deploy:migrations'. [#352]\n- Rescue Exception rather than StandardError to catch and log any sort\n of Processor death.", "2.2.0\n-----------", "- Roll back Celluloid optimizations in 2.1.0 which caused instability.\n- Add extension to delay any arbitrary class method to Sidekiq.\n Previously this was limited to ActiveRecord classes.", "```ruby\nSomeClass.delay.class_method(1, 'mike', Date.today)\n```", "- Sidekiq::Client now generates and returns a random, 128-bit Job ID 'jid' which\n can be used to track the processing of a Job, e.g. for calling back to a webhook\n when a job is finished.", "2.1.1\n-----------", "- Handle networking errors causing the scheduler thread to die [#309]\n- Rework exception handling to log all Processor and actor death (#325, subelsky)\n- Clone arguments when calling worker so modifications are discarded. (#265, hakanensari)", "2.1.0\n-----------", "- Tune Celluloid to no longer run message processing within a Fiber.\n This gives us a full Thread stack and also lowers Sidekiq's memory\n usage.\n- Add pagination within the Web UI [#253]\n- Specify which Redis driver to use: *hiredis* or *ruby* (default)\n- Remove FailureJobs and UniqueJobs, which were optional middleware\n that I don't want to support in core. [#302]", "2.0.3\n-----------\n- Fix sidekiq-web's navbar on mobile devices and windows under 980px (ezkl)\n- Fix Capistrano task for first deploys [#259]\n- Worker subclasses now properly inherit sidekiq\\_options set in\n their superclass [#221]\n- Add random jitter to scheduler to spread polls across POLL\\_INTERVAL\n window. [#247]\n- Sidekiq has a new mailing list: sidekiq@librelist.org See README.", "2.0.2\n-----------", "- Fix \"Retry Now\" button on individual retry page. (ezkl)", "2.0.1\n-----------", "- Add \"Clear Workers\" button to UI. If you kill -9 Sidekiq, the workers\n set can fill up with stale entries.\n- Update sidekiq/testing to support new scheduled jobs API:", " ```ruby\n require 'sidekiq/testing'\n DirectWorker.perform_in(10.seconds, 1, 2)\n assert_equal 1, DirectWorker.jobs.size\n assert_in_delta 10.seconds.from_now.to_f, DirectWorker.jobs.last['at'], 0.01\n ```", "2.0.0\n-----------", "- **SCHEDULED JOBS**!", "You can now use `perform_at` and `perform_in` to schedule jobs\nto run at arbitrary points in the future, like so:", "```ruby\n SomeWorker.perform_in(5.days, 'bob', 13)\n SomeWorker.perform_at(5.days.from_now, 'bob', 13)\n```", "It also works with the delay extensions:", "```ruby\n UserMailer.delay_for(5.days).send_welcome_email(user.id)\n```", "The time is approximately when the job will be placed on the queue;\nit is not guaranteed to run at precisely at that moment in time.", "This functionality is meant for one-off, arbitrary jobs. I still\nrecommend `whenever` or `clockwork` if you want cron-like,\nrecurring jobs. See `examples/scheduling.rb`", "I want to specially thank @yabawock for his work on sidekiq-scheduler.\nHis extension for Sidekiq 1.x filled an obvious functional gap that I now think is\nuseful enough to implement in Sidekiq proper.", "- Fixed issues due to Redis 3.x API changes. Sidekiq now requires\n the Redis 3.x client.\n- Inline testing now round trips arguments through JSON to catch\n serialization issues (betelgeuse)", "1.2.1\n-----------", "- Sidekiq::Worker now has access to Sidekiq's standard logger\n- Fix issue with non-StandardErrors leading to Processor exhaustion\n- Fix issue with Fetcher slowing Sidekiq shutdown\n- Print backtraces for all threads upon TTIN signal [#183]\n- Overhaul retries Web UI with new index page and bulk operations [#184]", "1.2.0\n-----------", "- Full or partial error backtraces can optionally be stored as part of the retry\n for display in the web UI if you aren't using an error service. [#155]", "```ruby\nclass Worker\n include Sidekiq::Worker\n sidekiq_options :backtrace => [true || 10]\nend\n```\n- Add timeout option to kill a worker after N seconds (blackgold9)", "```ruby\nclass HangingWorker\n include Sidekiq::Worker\n sidekiq_options :timeout => 600\n def perform\n # will be killed if it takes longer than 10 minutes\n end\nend\n```", "- Fix delayed extensions not available in workers [#152]\n- In test environments add the `#drain` class method to workers. This method\n executes all previously queued jobs. (panthomakos)\n- Sidekiq workers can be run inline during tests, just `require 'sidekiq/testing/inline'` (panthomakos)\n- Queues can now be deleted from the Sidekiq web UI [#154]\n- Fix unnecessary shutdown delay due to Retry Poller [#174]", "1.1.4\n-----------", "- Add 24 hr expiry for basic keys set in Redis, to avoid any possible leaking.\n- Only register workers in Redis while working, to avoid lingering\n workers [#156]\n- Speed up shutdown significantly.", "1.1.3\n-----------", "- Better network error handling when fetching jobs from Redis.\n Sidekiq will retry once per second until it can re-establish\n a connection. (ryanlecompte)\n- capistrano recipe now uses `bundle_cmd` if set [#147]\n- handle multi\\_json API changes (sferik)", "1.1.2\n-----------", "- Fix double restart with cap deploy [#137]", "1.1.1\n-----------", "- Set procline for easy monitoring of Sidekiq status via \"ps aux\"\n- Fix race condition on shutdown [#134]\n- Fix hang with cap sidekiq:start [#131]", "1.1.0\n-----------", "- The Sidekiq license has switched from GPLv3 to LGPLv3!\n- Sidekiq::Client.push now returns whether the actual Redis\n operation succeeded or not. [#123]\n- Remove UniqueJobs from the default middleware chain. Its\n functionality, while useful, is unexpected for new Sidekiq\n users. You can re-enable it with the following config.\n Read #119 for more discussion.", "```ruby\nSidekiq.configure_client do |config|\n require 'sidekiq/middleware/client/unique_jobs'\n config.client_middleware do |chain|\n chain.add Sidekiq::Middleware::Client::UniqueJobs\n end\nend\nSidekiq.configure_server do |config|\n require 'sidekiq/middleware/server/unique_jobs'\n config.server_middleware do |chain|\n chain.add Sidekiq::Middleware::Server::UniqueJobs\n end\nend\n```", "1.0.0\n-----------", "Thanks to all Sidekiq users and contributors for helping me\nget to this big milestone!", "- Default concurrency on client-side to 5, not 25 so we don't\n create as many unused Redis connections, same as ActiveRecord's\n default pool size.\n- Ensure redis= is given a Hash or ConnectionPool.", "0.11.2\n-----------", "- Implement \"safe shutdown\". The messages for any workers that\n are still busy when we hit the TERM timeout will be requeued in\n Redis so the messages are not lost when the Sidekiq process exits.\n [#110]\n- Work around Celluloid's small 4kb stack limit [#115]\n- Add support for a custom Capistrano role to limit Sidekiq to\n a set of machines. [#113]", "0.11.1\n-----------", "- Fix fetch breaking retry when used with Redis namespaces. [#109]\n- Redis connection now just a plain ConnectionPool, not CP::Wrapper.\n- Capistrano initial deploy fix [#106]\n- Re-implemented weighted queues support (ryanlecompte)", "0.11.0\n-----------", "- Client-side API changes, added sidekiq\\_options for Sidekiq::Worker.\n As a side effect of this change, the client API works on Ruby 1.8.\n It's not officially supported but should work [#103]\n- NO POLL! Sidekiq no longer polls Redis, leading to lower network\n utilization and lower latency for message processing.\n- Add --version CLI option", "0.10.1\n-----------", "- Add details page for jobs in retry queue (jcoene)\n- Display relative timestamps in web interface (jcoene)\n- Capistrano fixes (hinrik, bensie)", "0.10.0\n-----------", "- Reworked capistrano recipe to make it more fault-tolerant [#94].\n- Automatic failure retry! Sidekiq will now save failed messages\n and retry them, with an exponential backoff, over about 20 days.\n Did a message fail to process? Just deploy a bug fix in the next\n few days and Sidekiq will retry the message eventually.", "0.9.1\n-----------", "- Fix missed deprecations, poor method name in web UI", "0.9.0\n-----------", "- Add -t option to configure the TERM shutdown timeout\n- TERM shutdown timeout is now configurable, defaults to 5 seconds.\n- USR1 signal now stops Sidekiq from accepting new work,\n capistrano sends USR1 at start of deploy and TERM at end of deploy\n giving workers the maximum amount of time to finish.\n- New Sidekiq::Web rack application available\n- Updated Sidekiq.redis API", "0.8.0\n-----------", "- Remove :namespace and :server CLI options (mperham)\n- Add ExceptionNotifier support (masterkain)\n- Add capistrano support (mperham)\n- Workers now log upon start and finish (mperham)\n- Messages for terminated workers are now automatically requeued (mperham)\n- Add support for Exceptional error reporting (bensie)", "0.7.0\n-----------", "- Example chef recipe and monitrc script (jc00ke)\n- Refactor global configuration into Sidekiq.configure\\_server and\n Sidekiq.configure\\_client blocks. (mperham)\n- Add optional middleware FailureJobs which saves failed jobs to a\n 'failed' queue (fbjork)\n- Upon shutdown, workers are now terminated after 5 seconds. This is to\n meet Heroku's hard limit of 10 seconds for a process to shutdown. (mperham)\n- Refactor middleware API for simplicity, see sidekiq/middleware/chain. (mperham)\n- Add `delay` extensions for ActionMailer and ActiveRecord. (mperham)\n- Added config file support. See test/config.yml for an example file. (jc00ke)\n- Added pidfile for tools like monit (jc00ke)", "0.6.0\n-----------", "- Resque-compatible processing stats in redis (mperham)\n- Simple client testing support in sidekiq/testing (mperham)\n- Plain old Ruby support via the -r cli flag (mperham)\n- Refactored middleware support, introducing ability to add client-side middleware (ryanlecompte)\n- Added middleware for ignoring duplicate jobs (ryanlecompte)\n- Added middleware for displaying jobs in resque-web dashboard (maxjustus)\n- Added redis namespacing support (maxjustus)", "0.5.1\n-----------", "- Initial release!" ]
[ 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [9, 5, 81], "buggy_code_start_loc": [5, 4, 71], "filenames": ["Changes.md", "lib/sidekiq/version.rb", "lib/sidekiq/web/application.rb"], "fixing_code_end_loc": [12, 5, 81], "fixing_code_start_loc": [5, 4, 71], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:contribsys:sidekiq:*:*:*:*:*:*:*:*", "matchCriteriaId": "5B32B98F-EEB2-4982-976A-BEC2ECE01909", "versionEndExcluding": "7.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0.4", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8."}], "evaluatorComment": null, "id": "CVE-2023-1892", "lastModified": "2023-06-09T18:07:41.737", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 8.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.6, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-21T05:15:07.057", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/e35e5653-c429-4fb8-94a3-cbc123ae4777"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, "type": "CWE-79"}
244
Determine whether the {function_name} code is vulnerable or not.
[ "# Sidekiq Changes", "[Sidekiq Changes](https://github.com/sidekiq/sidekiq/blob/main/Changes.md) | [Sidekiq Pro Changes](https://github.com/sidekiq/sidekiq/blob/main/Pro-Changes.md) | [Sidekiq Enterprise Changes](https://github.com/sidekiq/sidekiq/blob/main/Ent-Changes.md)\n", "7.0.8", "----------\n", "- **SECURITY** Sanitize `period` input parameter on Metrics pages.\n Specially crafted values can lead to XSS. This functionality\n was introduced in 7.0.4. Thank you to spercex @ huntr.dev [#5694]\n- Add job hash as 3rd parameter to the `sidekiq_retry_in` block.", "\n7.0.7\n----------", "- Fix redis-client API usage which could result in stuck Redis\nconnections [#5823]\n- Fix AS::Duration with `sidekiq_retry_in` [#5806]\n- Restore dumping config options on startup with `-v` [#5822]", "7.0.5,7.0.6\n----------", "- More context for debugging json unsafe errors [#5787]", "7.0.4\n----------", "- Performance and memory optimizations [#5768, fatkodima]\n- Add 1-8 hour period selector to Metrics pages [#5694]\n- Fix process display with `sidekiqmon` [#5733]", "7.0.3\n----------", "- Don't warn about memory policy on Redis Enterprise [#5712]\n- Don't allow Quiet/Stop on embedded Sidekiq instances [#5716]\n- Fix `size: X` for configuring the default Redis pool size [#5702]\n- Improve the display of queue weights on Busy page [#5642]\n- Freeze CurrentAttributes on a job once initially set [#5692]", "7.0.2\n----------", "- Improve compatibility with custom loggers [#5673]\n- Add queue weights on Busy page [#5640]\n- Add BID link on job_info page if job is part of a Batch [#5623]\n- Allow custom extensions to add rows/links within Job detail pages [#5624]\n```ruby\nSidekiq::Web.custom_job_info_rows << AddAccountLink.new", "class AddAccountLink\n include CGI::Util\n def add_pair(job)\n # yield a (name, value) pair\n # You can include HTML tags and CSS, Sidekiq does not do any\n # escaping so beware user data injection! Note how we use CGI's\n # `h` escape helper.\n aid = job[\"account_id\"]\n yield \"Account\", \"<a href='/accounts/#{h aid}'>#{h aid}</a>\" if aid\n end\nend\n```", "7.0.1\n----------", "- Allow an embedding process to reuse its own heartbeat thread\n- Update zh-cn localization", "7.0.0\n----------", "- Embedded mode!\n- Capsules!!\n- Job Execution metrics!!!\n- See `docs/7.0-Upgrade.md` for release notes", "6.5.8\n----------", "- Fail if using a bad version of scout_apm [#5616]\n- Add pagination to Busy page [#5556]\n- Speed up WorkSet#each [#5559]\n- Adjust CurrentAttributes to work with the String class name so we aren't referencing the Class within a Rails initializer [#5536]", "6.5.7\n----------", "- Updates for JA and ZH locales\n- Further optimizations for scheduled polling [#5513]", "6.5.6\n----------", "- Fix deprecation warnings with redis-rb 4.8.0 [#5484]\n- Lock redis-rb to < 5.0 as we are moving to redis-client in Sidekiq 7.0", "6.5.5\n----------", "- Fix require issue with job_retry.rb [#5462]\n- Improve Sidekiq::Web compatibility with Rack 3.x", "6.5.4\n----------", "- Fix invalid code on Ruby 2.5 [#5460]\n- Fix further metrics dependency issues [#5457]", "6.5.3\n----------", "- Don't require metrics code without explicit opt-in [#5456]", "6.5.2\n----------", "- [Job Metrics are under active development, help wanted!](https://github.com/sidekiq/sidekiq/wiki/Metrics#contributing) **BETA**\n- Add `Context` column on queue page which shows any CurrentAttributes [#5450]\n- `sidekiq_retry_in` may now return `:discard` or `:kill` to dynamically stop job retries [#5406]\n- Smarter sorting of processes in /busy Web UI [#5398]\n- Fix broken hamburger menu in mobile UI [#5428]\n- Require redis-rb 4.5.0. Note that Sidekiq will break if you use the\n [`Redis.exists_returns_integer = false`](https://github.com/redis/redis-rb/blob/master/CHANGELOG.md#450) flag. [#5394]", "6.5.1\n----------", "- Fix `push_bulk` breakage [#5387]", "6.5.0\n---------", "- Substantial refactoring of Sidekiq server internals, part of a larger effort\n to reduce Sidekiq's internal usage of global methods and data, see [docs/global_to_local.md](docs/global_to_local.md) and [docs/middleware.md](docs/middleware.md).\n- **Add beta support for the `redis-client` gem**. This will become the default Redis driver in Sidekiq 7.0. [#5298]\n Read more: https://github.com/sidekiq/sidekiq/wiki/Using-redis-client\n- **Add beta support for DB transaction-aware client** [#5291]\n Add this line to your initializer and any jobs created during a transaction\n will only be pushed to Redis **after the transaction commits**. You will need to add the\n `after_commit_everywhere` gem to your Gemfile.\n```ruby\nSidekiq.transactional_push!\n```\n This feature does not have a lot of production usage yet; please try it out and let us\n know if you have any issues. It will be fully supported in Sidekiq 7.0 or removed if it\n proves problematic.\n- Fix regression with middleware arguments [#5312]", "6.4.2\n---------", "- Strict argument checking now runs after client-side middleware [#5246]\n- Fix page events with live polling [#5184]\n- Many under-the-hood changes to remove all usage of the term \"worker\"\n from the Sidekiq codebase and APIs. This mostly involved RDoc and local\n variable names but a few constants and public APIs were changed. The old\n APIs will be removed in Sidekiq 7.0.\n```\nSidekiq::DEFAULT_WORKER_OPTIONS -> Sidekiq.default_job_options\nSidekiq.default_worker_options -> Sidekiq.default_job_options\nSidekiq::Queues[\"default\"].jobs_by_worker(HardJob) -> Sidekiq::Queues[\"default\"].jobs_by_class(HardJob)\n```", "6.4.1\n---------", "- Fix pipeline/multi deprecations in redis-rb 4.6\n- Fix sidekiq.yml YAML load errors on Ruby 3.1 [#5141]\n- Sharding support for `perform_bulk` [#5129]\n- Refactor job logger for SPEEEEEEED", "6.4.0\n---------", "- **SECURITY**: Validate input to avoid possible DoS in Web UI.\n- Add **strict argument checking** [#5071]\n Sidekiq will now log a warning if JSON-unsafe arguments are passed to `perform_async`.\n Add `Sidekiq.strict_args!(false)` to your initializer to disable this warning.\n This warning will switch to an exception in Sidekiq 7.0.\n- Note that Delayed Extensions will be removed in Sidekiq 7.0 [#5076]\n- Add `perform_{inline,sync}` in Sidekiq::Job to run a job synchronously [#5061, hasan-ally]\n```ruby\nSomeJob.perform_async(args...)\nSomeJob.perform_sync(args...)\nSomeJob.perform_inline(args...)\n```\n You can also dynamically redirect a job to run synchronously:\n```ruby\nSomeJob.set(\"sync\": true).perform_async(args...) # will run via perform_inline\n```\n- Replace Sidekiq::Worker `app/workers` generator with Sidekiq::Job `app/sidekiq` generator [#5055]\n```\nbin/rails generate sidekiq:job ProcessOrderJob\n```\n- Fix job retries losing CurrentAttributes [#5090]\n- Tweak shutdown to give long-running threads time to cleanup [#5095]", "6.3.1\n---------", "- Fix keyword arguments error with CurrentAttributes on Ruby 3.0 [#5048]", "6.3.0\n---------", "- **BREAK**: The Web UI has been refactored to remove jQuery. Any UI extensions\n which use jQuery will break.\n- **FEATURE**: Sidekiq.logger has been enhanced so any `Rails.logger`\n output in jobs now shows up in the Sidekiq console. Remove any logger\n hacks in your initializer and see if it Just Works™ now. [#5021]\n- **FEATURE**: Add `Sidekiq::Job` alias for `Sidekiq::Worker`, to better\n reflect industry standard terminology. You can now do this:\n```ruby\nclass MyJob\n include Sidekiq::Job\n sidekiq_options ...\n def perform(args)\n end\nend\n```\n- **FEATURE**: Support for serializing ActiveSupport::CurrentAttributes into each job. [#4982]\n```ruby\n# config/initializers/sidekiq.rb\nrequire \"sidekiq/middleware/current_attributes\"\nSidekiq::CurrentAttributes.persist(Myapp::Current) # Your AS::CurrentAttributes singleton\n```\n- **FEATURE**: Add `Sidekiq::Worker.perform_bulk` for enqueuing jobs in bulk,\n similar to `Sidekiq::Client.push_bulk` [#5042]\n```ruby\nMyJob.perform_bulk([[1], [2], [3]])\n```\n- Implement `queue_as`, `wait` and `wait_until` for ActiveJob compatibility [#5003]\n- Scheduler now uses Lua to reduce Redis load and network roundtrips [#5044]\n- Retry Redis operation if we get an `UNBLOCKED` Redis error [#4985]\n- Run existing signal traps, if any, before running Sidekiq's trap [#4991]\n- Fix fetch bug when using weighted queues which caused Sidekiq to stop\n processing queues randomly [#5031]", "6.2.2\n---------", "- Reduce retry jitter, add jitter to `sidekiq_retry_in` values [#4957]\n- Minimize scheduler load on Redis at scale [#4882]\n- Improve logging of delay jobs [#4904, BuonOno]\n- Minor CSS improvements for buttons and tables, design PRs always welcome!\n- Tweak Web UI `Cache-Control` header [#4966]\n- Rename internal API class `Sidekiq::Job` to `Sidekiq::JobRecord` [#4955]", "6.2.1\n---------", "- Update RTT warning logic to handle transient RTT spikes [#4851]\n- Fix very low priority CVE on unescaped queue name [#4852]\n- Add note about sessions and Rails apps in API mode", "6.2.0\n---------", "- Store Redis RTT and log if poor [#4824]\n- Add process/thread stats to Busy page [#4806]\n- Improve Web UI on mobile devices [#4840]\n- **Refactor Web UI session usage** [#4804]\n Numerous people have hit \"Forbidden\" errors and struggled with Sidekiq's\n Web UI session requirement. If you have code in your initializer for\n Web sessions, it's quite possible it will need to be removed. Here's\n an overview:\n```\nSidekiq::Web needs a valid Rack session for CSRF protection. If this is a Rails app,\nmake sure you mount Sidekiq::Web *inside* your routes in `config/routes.rb` so\nSidekiq can reuse the Rails session:", " Rails.application.routes.draw do\n mount Sidekiq::Web => \"/sidekiq\"\n ....\n end", "If this is a bare Rack app, use a session middleware before Sidekiq::Web:", " # first, use IRB to create a shared secret key for sessions and commit it\n require 'securerandom'; File.open(\".session.key\", \"w\") {|f| f.write(SecureRandom.hex(32)) }", " # now, update your Rack app to include the secret with a session cookie middleware\n use Rack::Session::Cookie, secret: File.read(\".session.key\"), same_site: true, max_age: 86400\n run Sidekiq::Web", "If this is a Rails app in API mode, you need to enable sessions.", " https://guides.rubyonrails.org/api_app.html#using-session-middlewares\n```", "6.1.3\n---------", "- Warn if Redis is configured to evict data under memory pressure [#4752]\n- Add process RSS on the Busy page [#4717]", "6.1.2\n---------", "- Improve readability in dark mode Web UI [#4674]\n- Fix Web UI crash with corrupt session [#4672]\n- Allow middleware to yield arguments [#4673, @eugeneius]\n- Migrate CI from CircleCI to GitHub Actions [#4677]", "6.1.1\n---------", "- Jobs are now sorted by age in the Busy Workers table. [#4641]\n- Fix \"check all\" JS logic in Web UI [#4619]", "6.1.0\n---------", "- Web UI - Dark Mode fixes [#4543, natematykiewicz]\n- Ensure `Rack::ContentLength` is loaded as middleware for correct Web UI responses [#4541]\n- Avoid exception dumping SSL store in Redis connection logging [#4532]\n- Better error messages in Sidekiq::Client [#4549]\n- Remove rack-protection, reimplement CSRF protection [#4588]\n- Require redis-rb 4.2 [#4591]\n- Update to jquery 1.12.4 [#4593]\n- Refactor internal fetch logic and API [#4602]", "6.0.7\n---------", "- Refactor systemd integration to work better with custom binaries [#4511]\n- Don't connect to Redis at process exit if not needed [#4502]\n- Remove Redis connection naming [#4479]\n- Fix Redis Sentinel password redaction [#4499]\n- Add Vietnamese locale (vi) [#4528]", "6.0.6\n---------", "- **Integrate with systemd's watchdog and notification features** [#4488]\n Set `Type=notify` in [sidekiq.service](https://github.com/sidekiq/sidekiq/blob/4b8a8bd3ae42f6e48ae1fdaf95ed7d7af18ed8bb/examples/systemd/sidekiq.service#L30-L39). The integration works automatically.\n- Use `setTimeout` rather than `setInterval` to avoid thundering herd [#4480]\n- Fix edge case where a job can be pushed without a queue.\n- Flush job stats at exit [#4498]\n- Check RAILS_ENV before RACK_ENV [#4493]\n- Add Lithuanian locale [#4476]", "6.0.5\n---------", "- Fix broken Web UI response when using NewRelic and Rack 2.1.2+. [#4440]\n- Update APIs to use `UNLINK`, not `DEL`. [#4449]\n- Fix Ruby 2.7 warnings [#4412]\n- Add support for `APP_ENV` [[95fa5d9]](https://github.com/sidekiq/sidekiq/commit/95fa5d90192148026e52ca2902f1b83c70858ce8)", "6.0.4\n---------", "- Fix ActiveJob's `sidekiq_options` integration [#4404]\n- Sidekiq Pro users will now see a Pause button next to each queue in\n the Web UI, allowing them to pause queues manually [#4374, shayonj]\n- Fix Sidekiq::Workers API unintentional change in 6.0.2 [#4387]", "\n6.0.3\n---------", "- Fix `Sidekiq::Client.push_bulk` API which was erroneously putting\n invalid `at` values in the job payloads [#4321]", "6.0.2\n---------", "- Fix Sidekiq Enterprise's rolling restart functionality, broken by refactoring in 6.0.0. [#4334]\n- More internal refactoring and performance tuning [fatkodima]", "6.0.1\n---------", "- **Performance tuning**, Sidekiq should be 10-15% faster now [#4303, 4299,\n 4269, fatkodima]\n- **Dark Mode support in Web UI** (further design polish welcome!) [#4227, mperham,\n fatkodima, silent-e]\n- **Job-specific log levels**, allowing you to turn on debugging for\n problematic workers. [fatkodima, #4287]\n```ruby\nMyWorker.set(log_level: :debug).perform_async(...)\n```\n- **Ad-hoc job tags**. You can tag your jobs with, e.g, subdomain, tenant, country,\n locale, application, version, user/client, \"alpha/beta/pro/ent\", types of jobs,\n teams/people responsible for jobs, additional metadata, etc.\n Tags are shown on different pages with job listings. Sidekiq Pro users\n can filter based on them [fatkodima, #4280]\n```ruby\nclass MyWorker\n include Sidekiq::Worker\n sidekiq_options tags: ['bank-ops', 'alpha']\n ...\nend\n```\n- Fetch scheduled jobs in batches before pushing into specific queues.\n This will decrease enqueueing time of scheduled jobs by a third. [fatkodima, #4273]\n```\nScheduledSet with 10,000 jobs\nBefore: 56.6 seconds\nAfter: 39.2 seconds\n```\n- Compress error backtraces before pushing into Redis, if you are\n storing error backtraces, this will halve the size of your RetrySet\n in Redis [fatkodima, #4272]\n```\nRetrySet with 100,000 jobs\nBefore: 261 MB\nAfter: 129 MB\n```\n- Support display of ActiveJob 6.0 payloads in the Web UI [#4263]\n- Add `SortedSet#scan` for pattern based scanning. For large sets this API will be **MUCH** faster\n than standard iteration using each. [fatkodima, #4262]\n```ruby\n Sidekiq::DeadSet.new.scan(\"UnreliableApi\") do |job|\n job.retry\n end\n```\n- Dramatically speed up SortedSet#find\\_job(jid) by using Redis's ZSCAN\n support, approx 10x faster. [fatkodima, #4259]\n```\nzscan 0.179366 0.047727 0.227093 ( 1.161376)\nenum 8.522311 0.419826 8.942137 ( 9.785079)\n```\n- Respect rails' generators `test_framework` option and gracefully handle extra `worker` suffix on generator [fatkodima, #4256]\n- Add ability to sort 'Enqueued' page on Web UI by position in the queue [fatkodima, #4248]\n- Support `Client.push_bulk` with different delays [fatkodima, #4243]\n```ruby\nSidekiq::Client.push_bulk(\"class\" => FooJob, \"args\" => [[1], [2]], \"at\" => [1.minute.from_now.to_f, 5.minutes.from_now.to_f])\n```\n- Easier way to test enqueuing specific ActionMailer and ActiveRecord delayed jobs. Instead of manually\n parsing embedded class, you can now test by fetching jobs for specific classes. [fatkodima, #4292]\n```ruby\nassert_equal 1, Sidekiq::Extensions::DelayedMailer.jobs_for(FooMailer).size\n```\n- Add `sidekiqmon` to gemspec executables [#4242]\n- Gracefully handle `Sidekiq.logger = nil` [#4240]\n- Inject Sidekiq::LogContext module if user-supplied logger does not include it [#4239]", "6.0\n---------", "This release has major breaking changes. Read and test carefully in production.", "- With Rails 6.0.2+, ActiveJobs can now use `sidekiq_options` directly to configure Sidekiq\n features/internals like the retry subsystem. [#4213, pirj]\n```ruby\nclass MyJob < ActiveJob::Base\n queue_as :myqueue\n sidekiq_options retry: 10, backtrace: 20\n def perform(...)\n end\nend\n```\n- Logging has been redesigned to allow for pluggable log formatters:\n```ruby\nSidekiq.configure_server do |config|\n config.log_formatter = Sidekiq::Logger::Formatters::JSON.new\nend\n```\nSee the [Logging wiki page](https://github.com/sidekiq/sidekiq/wiki/Logging) for more details.\n- **BREAKING CHANGE** Validate proper usage of the `REDIS_PROVIDER`\n variable. This variable is meant to hold the name of the environment\n variable which contains your Redis URL, so that you can switch Redis\n providers quickly and easily with a single variable change. It is not\n meant to hold the actual Redis URL itself. If you want to manually set\n the Redis URL (not recommended as it implies you have no failover),\n then you may set `REDIS_URL` directly. [#3969]\n- **BREAKING CHANGE** Increase default shutdown timeout from 8 seconds\n to 25 seconds. Both Heroku and ECS now use 30 second shutdown timeout\n by default and we want Sidekiq to take advantage of this time. If you\n have deployment scripts which depend on the old default timeout, use `-t 8` to\n get the old behavior. [#3968]\n- **BREAKING CHANGE** Remove the daemonization, logfile and pidfile\n arguments to Sidekiq. Use a proper process supervisor (e.g. systemd or\n foreman) to manage Sidekiq. See the Deployment wiki page for links to\n more resources.\n- Integrate the StandardRB code formatter to ensure consistent code\n styling. [#4114, gearnode]", "5.2.10\n---------", "- Backport fix for CVE-2022-23837.\n- Migrate to `exists?` for redis-rb.\n- Lock redis-rb to <4.6 to avoid deprecations.", "5.2.9\n---------", "- Release Rack lock due to a cascade of CVEs. [#4566]\n Pro-tip: don't lock Rack.", "5.2.8\n---------", "- Lock to Rack 2.0.x to prevent future incompatibilities\n- Fix invalid reference in `sidekiqctl`", "5.2.7\n---------", "- Fix stale `enqueued_at` when retrying [#4149]\n- Move build to [Circle CI](https://circleci.com/gh/mperham/sidekiq) [#4120]", "5.2.6\n---------", "- Fix edge case where a job failure during Redis outage could result in a lost job [#4141]\n- Better handling of malformed job arguments in payload [#4095]\n- Restore bootstap's dropdown css component [#4099, urkle]\n- Display human-friendly time diff for longer queue latencies [#4111, interlinked]\n- Allow `Sidekiq::Worker#set` to be chained", "5.2.5\n---------", "- Fix default usage of `config/sidekiq.yml` [#4077, Tensho]", "5.2.4\n---------", "- Add warnings for various deprecations and changes coming in Sidekiq 6.0.\n See the 6-0 branch. [#4056]\n- Various improvements to the Sidekiq test suite and coverage [#4026, #4039, Tensho]", "5.2.3\n---------", "- Warning message on invalid REDIS\\_PROVIDER [#3970]\n- Add `sidekiqctl status` command [#4003, dzunk]\n- Update elapsed time calculatons to use monotonic clock [#3999]\n- Fix a few issues with mobile Web UI styling [#3973, navied]\n- Jobs with `retry: false` now go through the global `death_handlers`,\n meaning you can take action on failed ephemeral jobs. [#3980, Benjamin-Dobell]\n- Fix race condition in defining Workers. [#3997, mattbooks]", "5.2.2\n---------", "- Raise error for duplicate queue names in config to avoid unexpected fetch algorithm change [#3911]\n- Fix concurrency bug on JRuby [#3958, mattbooks]\n- Add \"Kill All\" button to the retries page [#3938]", "5.2.1\n-----------", "- Fix concurrent modification error during heartbeat [#3921]", "5.2.0\n-----------", "- **Decrease default concurrency from 25 to 10** [#3892]\n- Verify connection pool sizing upon startup [#3917]\n- Smoother scheduling for large Sidekiq clusters [#3889]\n- Switch Sidekiq::Testing impl from alias\\_method to Module#prepend, for resiliency [#3852]\n- Update Sidekiq APIs to use SCAN for scalability [#3848, ffiller]\n- Remove concurrent-ruby gem dependency [#3830]\n- Optimize Web UI's bootstrap.css [#3914]", "5.1.3\n-----------", "- Fix version comparison so Ruby 2.2.10 works. [#3808, nateberkopec]", "5.1.2\n-----------", "- Add link to docs in Web UI footer\n- Fix crash on Ctrl-C in Windows [#3775, Bernica]\n- Remove `freeze` calls on String constants. This is superfluous with Ruby\n 2.3+ and `frozen_string_literal: true`. [#3759]\n- Fix use of AR middleware outside of Rails [#3787]\n- Sidekiq::Worker `sidekiq_retry_in` block can now return nil or 0 to use\n the default backoff delay [#3796, dsalahutdinov]", "5.1.1\n-----------", "- Fix Web UI incompatibility with Redis 3.x gem [#3749]", "5.1.0\n-----------", "- **NEW** Global death handlers - called when your job exhausts all\n retries and dies. Now you can take action when a job fails permanently. [#3721]\n- **NEW** Enable ActiveRecord query cache within jobs by default [#3718, sobrinho]\n This will prevent duplicate SELECTS; cache is cleared upon any UPDATE/INSERT/DELETE.\n See the issue for how to bypass the cache or disable it completely.\n- Scheduler timing is now more accurate, 15 -> 5 seconds [#3734]\n- Exceptions during the :startup event will now kill the process [#3717]\n- Make `Sidekiq::Client.via` reentrant [#3715]\n- Fix use of Sidekiq logger outside of the server process [#3714]\n- Tweak `constantize` to better match Rails class lookup. [#3701, caffeinated-tech]", "5.0.5\n-----------", "- Update gemspec to allow newer versions of the Redis gem [#3617]\n- Refactor Worker.set so it can be memoized [#3602]\n- Fix display of Redis URL in web footer, broken in 5.0.3 [#3560]\n- Update `Sidekiq::Job#display_args` to avoid mutation [#3621]", "5.0.4\n-----------", "- Fix \"slow startup\" performance regression from 5.0.2. [#3525]\n- Allow users to disable ID generation since some redis providers disable the CLIENT command. [#3521]", "5.0.3\n-----------", "- Fix overriding `class_attribute` core extension from ActiveSupport with Sidekiq one [PikachuEXE, #3499]\n- Allow job logger to be overridden [AlfonsoUceda, #3502]\n- Set a default Redis client identifier for debugging [#3516]\n- Fix \"Uninitialized constant\" errors on startup with the delayed extensions [#3509]", "5.0.2\n-----------", "- fix broken release, thanks @nateberkopec", "5.0.1\n-----------", "- Fix incorrect server identity when daemonizing [jwilm, #3496]\n- Work around error running Web UI against Redis Cluster [#3492]\n- Remove core extensions, Sidekiq is now monkeypatch-free! [#3474]\n- Reimplement Web UI's HTTP\\_ACCEPT\\_LANGUAGE parsing because the spec is utterly\n incomprehensible for various edge cases. [johanlunds, natematykiewicz, #3449]\n- Update `class_attribute` core extension to avoid warnings\n- Expose `job_hash_context` from `Sidekiq::Logging` to support log customization", "5.0.0\n-----------", "- **BREAKING CHANGE** Job dispatch was refactored for safer integration with\n Rails 5. The **Logging** and **RetryJobs** server middleware were removed and\n functionality integrated directly into Sidekiq::Processor. These aren't\n commonly used public APIs so this shouldn't impact most users.\n```\nSidekiq::Middleware::Server::RetryJobs -> Sidekiq::JobRetry\nSidekiq::Middleware::Server::Logging -> Sidekiq::JobLogger\n```\n- Quieting Sidekiq is now done via the TSTP signal, the USR1 signal is deprecated.\n- The `delay` extension APIs are no longer available by default, you\n must opt into them.\n- The Web UI is now BiDi and can render RTL languages like Arabic, Farsi and Hebrew.\n- Rails 3.2 and Ruby 2.0 and 2.1 are no longer supported.\n- The `SomeWorker.set(options)` API was re-written to avoid thread-local state. [#2152]\n- Sidekiq Enterprise's encrypted jobs now display \"[encrypted data]\" in the Web UI instead\n of random hex bytes.\n- Please see the [5.0 Upgrade notes](docs/5.0-Upgrade.md) for more detail.", "4.2.10\n-----------", "- Scheduled jobs can now be moved directly to the Dead queue via API [#3390]\n- Fix edge case leading to job duplication when using Sidekiq Pro's\n reliability feature [#3388]\n- Fix error class name display on retry page [#3348]\n- More robust latency calculation [#3340]", "4.2.9\n-----------", "- Rollback [#3303] which broke Heroku Redis users [#3311]\n- Add support for TSTP signal, for Sidekiq 5.0 forward compatibility. [#3302]", "4.2.8\n-----------", "- Fix rare edge case with Redis driver that can create duplicate jobs [#3303]\n- Fix Rails 5 loading issue [#3275]\n- Restore missing tooltips to timestamps in Web UI [#3310]\n- Work on **Sidekiq 5.0** is now active! [#3301]", "4.2.7\n-----------", "- Add new integration testing to verify code loading and job execution\n in development and production modes with Rails 4 and 5 [#3241]\n- Fix delayed extensions in development mode [#3227, DarthSim]\n- Use Worker's `retry` default if job payload does not have a retry\n attribute [#3234, mlarraz]", "4.2.6\n-----------", "- Run Rails Executor when in production [#3221, eugeneius]", "4.2.5\n-----------", "- Re-enable eager loading of all code when running non-development Rails 5. [#3203]\n- Better root URL handling for zany web servers [#3207]", "4.2.4\n-----------", "- Log errors coming from the Rails 5 reloader. [#3212, eugeneius]\n- Clone job data so middleware changes don't appear in Busy tab", "4.2.3\n-----------", "- Disable use of Rails 5's Reloader API in non-development modes, it has proven\n to be unstable under load [#3154]\n- Allow disabling of Sidekiq::Web's cookie session to handle the\n case where the app provides a session already [#3180, inkstak]\n```ruby\nSidekiq::Web.set :sessions, false\n```\n- Fix Web UI sharding support broken in 4.2.2. [#3169]\n- Fix timestamps not updating during UI polling [#3193, shaneog]\n- Relax rack-protection version to >= 1.5.0\n- Provide consistent interface to exception handlers, changing the structure of the context hash. [#3161]", "4.2.2\n-----------", "- Fix ever-increasing cookie size with nginx [#3146, cconstantine]\n- Fix so Web UI works without trailing slash [#3158, timdorr]", "4.2.1\n-----------", "- Ensure browser does not cache JSON/AJAX responses. [#3136]\n- Support old Sinatra syntax for setting config [#3139]", "4.2.0\n-----------", "- Enable development-mode code reloading. **With Rails 5.0+, you don't need\n to restart Sidekiq to pick up your Sidekiq::Worker changes anymore!** [#2457]\n- **Remove Sinatra dependency**. Sidekiq's Web UI now uses Rack directly.\n Thank you to Sidekiq's newest committer, **badosu**, for writing the code\n and doing a lot of testing to ensure compatibility with many different\n 3rd party plugins. If your Web UI works with 4.1.4 but fails with\n 4.2.0, please open an issue. [#3075]\n- Allow tuning of concurrency with the `RAILS_MAX_THREADS` env var. [#2985]\n This is the same var used by Puma so you can tune all of your systems\n the same way:\n```sh\nweb: RAILS_MAX_THREADS=5 bundle exec puma ...\nworker: RAILS_MAX_THREADS=10 bundle exec sidekiq ...\n```\nUsing `-c` or `config/sidekiq.yml` overrides this setting. I recommend\nadjusting your `config/database.yml` to use it too so connections are\nauto-scaled:\n```yaml\n pool: <%= ENV['RAILS_MAX_THREADS'] || 5 %>\n```", "4.1.4\n-----------", "- Unlock Sinatra so a Rails 5.0 compatible version may be used [#3048]\n- Fix race condition on startup with JRuby [#3043]", "\n4.1.3\n-----------", "- Please note the Redis 3.3.0 gem has a [memory leak](https://github.com/redis/redis-rb/issues/612),\n Redis 3.2.2 is recommended until that issue is fixed.\n- Sinatra 1.4.x is now a required dependency, avoiding cryptic errors\n and old bugs due to people not upgrading Sinatra for years. [#3042]\n- Fixed race condition in heartbeat which could rarely lead to lingering\n processes on the Busy tab. [#2982]\n```ruby\n# To clean up lingering processes, modify this as necessary to connect to your Redis.\n# After 60 seconds, lingering processes should disappear from the Busy page.", "require 'redis'\nr = Redis.new(url: \"redis://localhost:6379/0\")\n# uncomment if you need a namespace\n#require 'redis-namespace'\n#r = Redis::Namespace.new(\"foo\", r)\nr.smembers(\"processes\").each do |pro|\n r.expire(pro, 60)\n r.expire(\"#{pro}:workers\", 60)\nend\n```", "\n4.1.2\n-----------", "- Fix Redis data leak with worker data when a busy Sidekiq process\n crashes. You can find and expire leaked data in Redis with this\nscript:\n```bash\n$ redis-cli keys \"*:workers\" | while read LINE ; do TTL=`redis-cli expire \"$LINE\" 60`; echo \"$LINE\"; done;\n```\n Please note that `keys` can be dangerous to run on a large, busy Redis. Caveat runner.\n- Freeze all string literals with Ruby 2.3. [#2741]\n- Client middleware can now stop bulk job push. [#2887]", "4.1.1\n-----------", "- Much better behavior when Redis disappears and comes back. [#2866]\n- Update FR locale [dbachet]\n- Don't fill logfile in case of Redis downtime [#2860]\n- Allow definition of a global retries_exhausted handler. [#2807]\n```ruby\nSidekiq.configure_server do |config|\n config.default_retries_exhausted = -> (job, ex) do\n Sidekiq.logger.info \"#{job['class']} job is now dead\"\n end\nend\n```", "4.1.0\n-----------", "- Tag quiet processes in the Web UI [#2757, jcarlson]\n- Pass last exception to sidekiq\\_retries\\_exhausted block [#2787, Nowaker]\n```ruby\nclass MyWorker\n include Sidekiq::Worker\n sidekiq_retries_exhausted do |job, exception|\n end\nend\n```\n- Add native support for ActiveJob's `set(options)` method allowing\nyou to override worker options dynamically. This should make it\neven easier to switch between ActiveJob and Sidekiq's native APIs [#2780]\n```ruby\nclass MyWorker\n include Sidekiq::Worker\n sidekiq_options queue: 'default', retry: true", " def perform(*args)\n # do something\n end\nend", "MyWorker.set(queue: 'high', retry: false).perform_async(1)\n```", "4.0.2\n-----------", "- Better Japanese translations\n- Remove `json` gem dependency from gemspec. [#2743]\n- There's a new testing API based off the `Sidekiq::Queues` namespace. All\n assertions made against the Worker class still work as expected.\n [#2676, brandonhilkert]\n```ruby\nassert_equal 0, Sidekiq::Queues[\"default\"].size\nHardWorker.perform_async(\"log\")\nassert_equal 1, Sidekiq::Queues[\"default\"].size\nassert_equal \"log\", Sidekiq::Queues[\"default\"].first['args'][0]\nSidekiq::Queues.clear_all\n```", "4.0.1\n-----------", "- Yank new queue-based testing API [#2663]\n- Fix invalid constant reference in heartbeat", "4.0.0\n-----------", "- Sidekiq's internals have been completely overhauled for performance\n and to remove dependencies. This has resulted in major speedups, as\n [detailed on my blog](http://www.mikeperham.com/2015/10/14/optimizing-sidekiq/).\n- See the [4.0 upgrade notes](docs/4.0-Upgrade.md) for more detail.", "3.5.4\n-----------", "- Ensure exception message is a string [#2707]\n- Revert racy Process.kill usage in sidekiqctl", "3.5.3\n-----------", "- Adjust shutdown event to run in parallel with the rest of system shutdown. [#2635]", "3.5.2\n-----------", "- **Sidekiq 3 is now in maintenance mode**, only major bugs will be fixed.\n- The exception triggering a retry is now passed into `sidekiq_retry_in`,\n allowing you to retry more frequently for certain types of errors.\n [#2619, kreynolds]\n```ruby\n sidekiq_retry_in do |count, ex|\n case ex\n when RuntimeError\n 5 * count\n else\n 10 * count\n end\n end\n```", "3.5.1\n-----------", "- **FIX MEMORY LEAK** Under rare conditions, threads may leak [#2598, gazay]\n- Add Ukrainian locale [#2561, elrakita]\n- Disconnect and retry Redis operations if we see a READONLY error [#2550]\n- Add server middleware testing harness; see [wiki](https://github.com/sidekiq/sidekiq/wiki/Testing#testing-server-middleware) [#2534, ryansch]", "3.5.0\n-----------", "- Polished new banner! [#2522, firedev]\n- Upgrade to Celluloid 0.17. [#2420, digitalextremist]\n- Activate sessions in Sinatra for CSRF protection, requires Rails\n monkeypatch due to rails/rails#15843. [#2460, jc00ke]", "3.4.2\n-----------", "- Don't allow `Sidekiq::Worker` in ActiveJob::Base classes. [#2424]\n- Safer display of job data in Web UI [#2405]\n- Fix CSRF vulnerability in Web UI, thanks to Egor Homakov for\n reporting. [#2422] If you are running the Web UI as a standalone Rack app,\n ensure you have a [session middleware\nconfigured](https://github.com/sidekiq/sidekiq/wiki/Monitoring#standalone):\n```ruby\nuse Rack::Session::Cookie, :secret => \"some unique secret string here\"\n```", "3.4.1\n-----------", "- Lock to Celluloid 0.16", "\n3.4.0\n-----------", "- Set a `created_at` attribute when jobs are created, set `enqueued_at` only\n when they go into a queue. Fixes invalid latency calculations with scheduled jobs.\n [#2373, mrsimo]\n- Don't log timestamp on Heroku [#2343]\n- Run `shutdown` event handlers in reverse order of definition [#2374]\n- Rename and rework `poll_interval` to be simpler, more predictable [#2317, cainlevy]\n The new setting is `average_scheduled_poll_interval`. To configure\n Sidekiq to look for scheduled jobs every 5 seconds, just set it to 5.\n```ruby\nSidekiq.configure_server do |config|\n config.average_scheduled_poll_interval = 5\nend\n```", "3.3.4\n-----------", "- **Improved ActiveJob integration** - Web UI now shows ActiveJobs in a\n nicer format and job logging shows the actual class name, requires\n Rails 4.2.2+ [#2248, #2259]\n- Add Sidekiq::Process#dump\\_threads API to trigger TTIN output [#2247]\n- Web UI polling now uses Ajax to avoid page reload [#2266, davydovanton]\n- Several Web UI styling improvements [davydovanton]\n- Add Tamil, Hindi translations for Web UI [ferdinandrosario, tejasbubane]\n- Fix Web UI to work with country-specific locales [#2243]\n- Handle circular error causes [#2285, eugenk]", "3.3.3\n-----------", "- Fix crash on exit when Redis is down [#2235]\n- Fix duplicate logging on startup\n- Undeprecate delay extension for ActionMailer 4.2+ . [#2186]", "3.3.2\n-----------", "- Add Sidekiq::Stats#queues back\n- Allows configuration of dead job set size and timeout [#2173, jonhyman]\n- Refactor scheduler enqueuing so Sidekiq Pro can override it. [#2159]", "3.3.1\n-----------", "- Dumb down ActionMailer integration so it tries to deliver if possible [#2149]\n- Stringify Sidekiq.default\\_worker\\_options's keys [#2126]\n- Add random integer to process identity [#2113, michaeldiscala]\n- Log Sidekiq Pro's Batch ID if available [#2076]\n- Refactor Processor Redis usage to avoid redis/redis-rb#490 [#2094]\n- Move /dashboard/stats to /stats. Add /stats/queues. [moserke, #2099]\n- Add processes count to /stats [ismaelga, #2141]\n- Greatly improve speed of Sidekiq::Stats [ismaelga, #2142]\n- Add better usage text for `sidekiqctl`.\n- `Sidekiq::Logging.with_context` is now a stack so you can set your\n own job context for logging purposes [grosser, #2110]\n- Remove usage of Google Fonts in Web UI so it loads in China [#2144]", "3.3.0\n-----------", "- Upgrade to Celluloid 0.16 [#2056]\n- Fix typo for generator test file name [dlackty, #2016]\n- Add Sidekiq::Middleware::Chain#prepend [seuros, #2029]", "3.2.6\n-----------", "- Deprecate delay extension for ActionMailer 4.2+ . [seuros, #1933]\n- Poll interval tuning now accounts for dead processes [epchris, #1984]\n- Add non-production environment to Web UI page titles [JacobEvelyn, #2004]", "3.2.5\n-----------", "- Lock Celluloid to 0.15.2 due to bugs in 0.16.0. This prevents the\n \"hang on shutdown\" problem with Celluloid 0.16.0.", "3.2.4\n-----------", "- Fix issue preventing ActionMailer sends working in some cases with\n Rails 4. [pbhogan, #1923]", "3.2.3\n-----------", "- Clean invalid bytes from error message before converting to JSON (requires Ruby 2.1+) [#1705]\n- Add queues list for each process to the Busy page. [davetoxa, #1897]\n- Fix for crash caused by empty config file. [jordan0day, #1901]\n- Add Rails Worker generator, `rails g sidekiq:worker User` will create `app/workers/user_worker.rb`. [seuros, #1909]\n- Fix Web UI rendering with huge job arguments [jhass, #1918]\n- Minor refactoring of Sidekiq::Client internals, for Sidekiq Pro. [#1919]", "3.2.2\n-----------", "- **This version of Sidekiq will no longer start on Ruby 1.9.** Sidekiq\n 3 does not support MRI 1.9 but we've allowed it to run before now.\n- Fix issue which could cause Sidekiq workers to disappear from the Busy\n tab while still being active [#1884]\n- Add \"Back to App\" button in Web UI. You can set the button link via\n `Sidekiq::Web.app_url = 'http://www.mysite.com'` [#1875, seuros]\n- Add process tag (`-g tag`) to the Busy page so you can differentiate processes at a glance. [seuros, #1878]\n- Add \"Kill\" button to move retries directly to the DJQ so they don't retry. [seuros, #1867]", "3.2.1\n-----------", "- Revert eager loading change for Rails 3.x apps, as it broke a few edge\n cases.", "3.2.0\n-----------", "- **Fix issue which caused duplicate job execution in Rails 3.x**\n This issue is caused by [improper exception handling in ActiveRecord](https://github.com/rails/rails/blob/3-2-stable/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb#L281) which changes Sidekiq's Shutdown exception into a database\n error, making Sidekiq think the job needs to be retried. **The fix requires Ruby 2.1**. [#1805]\n- Update how Sidekiq eager loads Rails application code [#1791, jonleighton]\n- Change logging timestamp to show milliseconds.\n- Reverse sorting of Dead tab so newer jobs are listed first [#1802]", "3.1.4\n-----------", "- Happy π release!\n- Self-tuning Scheduler polling, we use heartbeat info to better tune poll\\_interval [#1630]\n- Remove all table column width rules, hopefully get better column formatting [#1747]\n- Handle edge case where YAML can't be decoded in dev mode [#1761]\n- Fix lingering jobs in Busy page on Heroku [#1764]", "3.1.3\n-----------", "- Use ENV['DYNO'] on Heroku for hostname display, rather than an ugly UUID. [#1742]\n- Show per-process labels on the Busy page, for feature tagging [#1673]", "\n3.1.2\n-----------", "- Suitably chastised, @mperham reverts the Bundler change.", "\n3.1.1\n-----------", "- Sidekiq::CLI now runs `Bundler.require(:default, environment)` to boot all gems\n before loading any app code.\n- Sort queues by name in Web UI [#1734]", "\n3.1.0\n-----------", "- New **remote control** feature: you can remotely trigger Sidekiq to quiet\n or terminate via API, without signals. This is most useful on JRuby\n or Heroku which does not support the USR1 'quiet' signal. Now you can\n run a rake task like this at the start of your deploy to quiet your\n set of Sidekiq processes. [#1703]\n```ruby\nnamespace :sidekiq do\n task :quiet => :environment do\n Sidekiq::ProcessSet.new.each(&:quiet!)\n end\nend\n```\n- The Web UI can use the API to quiet or stop all processes via the Busy page.\n- The Web UI understands and hides the `Sidekiq::Extensions::Delay*`\n classes, instead showing `Class.method` as the Job. [#1718]\n- Polish the Dashboard graphs a bit, update Rickshaw [brandonhilkert, #1725]\n- The poll interval is now configurable in the Web UI [madebydna, #1713]\n- Delay extensions can be removed so they don't conflict with\n DelayedJob: put `Sidekiq.remove_delay!` in your initializer. [devaroop, #1674]", "\n3.0.2\n-----------", "- Revert gemfile requirement of Ruby 2.0. JRuby 1.7 calls itself Ruby\n 1.9.3 and broke with this requirement.", "3.0.1\n-----------", "- Revert pidfile behavior from 2.17.5: Sidekiq will no longer remove its own pidfile\n as this is a race condition when restarting. [#1470, #1677]\n- Show warning on the Queues page if a queue is paused [#1672]\n- Only activate the ActiveRecord middleware if ActiveRecord::Base is defined on boot. [#1666]\n- Add ability to disable jobs going to the DJQ with the `dead` option.\n```ruby\nsidekiq_options :dead => false, :retry => 5\n```\n- Minor fixes", "\n3.0.0\n-----------", "Please see [3.0-Upgrade.md](docs/3.0-Upgrade.md) for more comprehensive upgrade notes.", "- **Dead Job Queue** - jobs which run out of retries are now moved to a dead\n job queue. These jobs must be retried manually or they will expire\n after 6 months or 10,000 jobs. The Web UI contains a \"Dead\" tab\n exposing these jobs. Use `sidekiq_options :retry => false` if you\ndon't wish jobs to be retried or put in the DJQ. Use\n`sidekiq_options :retry => 0` if you don't want jobs to retry but go\nstraight to the DJQ.\n- **Process Lifecycle Events** - you can now register blocks to run at\n certain points during the Sidekiq process lifecycle: startup, quiet and\n shutdown.\n```ruby\nSidekiq.configure_server do |config|\n config.on(:startup) do\n # do something\n end\nend\n```\n- **Global Error Handlers** - blocks of code which handle errors that\n occur anywhere within Sidekiq, not just within middleware.\n```ruby\nSidekiq.configure_server do |config|\n config.error_handlers << proc {|ex,ctx| ... }\nend\n```\n- **Process Heartbeat** - each Sidekiq process will ping Redis every 5\n seconds to give a summary of the Sidekiq population at work.\n- The Workers tab is now renamed to Busy and contains a list of live\n Sidekiq processes and jobs in progress based on the heartbeat.\n- **Shardable Client** - Sidekiq::Client instances can use a custom\n Redis connection pool, allowing very large Sidekiq installations to scale by\n sharding: sending different jobs to different Redis instances.\n```ruby\nclient = Sidekiq::Client.new(ConnectionPool.new { Redis.new })\nclient.push(...)\n```\n```ruby\nSidekiq::Client.via(ConnectionPool.new { Redis.new }) do\n FooWorker.perform_async\n BarWorker.perform_async\nend\n```\n **Sharding support does require a breaking change to client-side\nmiddleware, see docs/3.0-Upgrade.md.**\n- New Chinese, Greek, Swedish and Czech translations for the Web UI.\n- Updated most languages translations for the new UI features.\n- **Remove official Capistrano integration** - this integration has been\n moved into the [capistrano-sidekiq](https://github.com/seuros/capistrano-sidekiq) gem.\n- **Remove official support for MRI 1.9** - Things still might work but\n I no longer actively test on it.\n- **Remove built-in support for Redis-to-Go**.\n Heroku users: `heroku config:set REDIS_PROVIDER=REDISTOGO_URL`\n- **Remove built-in error integration for Airbrake, Honeybadger, ExceptionNotifier and Exceptional**.\n Each error gem should provide its own Sidekiq integration. Update your error gem to the latest\n version to pick up Sidekiq support.\n- Upgrade to connection\\_pool 2.0 which now creates connections lazily.\n- Remove deprecated Sidekiq::Client.registered\\_\\* APIs\n- Remove deprecated support for the old Sidekiq::Worker#retries\\_exhausted method.\n- Removed 'sidekiq/yaml\\_patch', this was never documented or recommended.\n- Removed --profile option, #1592\n- Remove usage of the term 'Worker' in the UI for clarity. Users would call both threads and\n processes 'workers'. Instead, use \"Thread\", \"Process\" or \"Job\".", "2.17.7\n-----------", "- Auto-prune jobs older than one hour from the Workers page [#1508]\n- Add Sidekiq::Workers#prune which can perform the auto-pruning.\n- Fix issue where a job could be lost when an exception occurs updating\n Redis stats before the job executes [#1511]", "2.17.6\n-----------", "- Fix capistrano integration due to missing pidfile. [#1490]", "2.17.5\n-----------", "- Automatically use the config file found at `config/sidekiq.yml`, if not passed `-C`. [#1481]\n- Store 'retried\\_at' and 'failed\\_at' timestamps as Floats, not Strings. [#1473]\n- A `USR2` signal will now reopen _all_ logs, using IO#reopen. Thus, instead of creating a new Logger object,\n Sidekiq will now just update the existing Logger's file descriptor [#1163].\n- Remove pidfile when shutting down if started with `-P` [#1470]", "2.17.4\n-----------", "- Fix JID support in inline testing, #1454\n- Polish worker arguments display in UI, #1453\n- Marshal arguments fully to avoid worker mutation, #1452\n- Support reverse paging sorted sets, #1098", "\n2.17.3\n-----------", "- Synchronously terminates the poller and fetcher to fix a race condition in bulk requeue during shutdown [#1406]", "2.17.2\n-----------", "- Fix bug where strictly prioritized queues might be processed out of\n order [#1408]. A side effect of this change is that it breaks a queue\n declaration syntax that worked, although only because of a bug—it was\n never intended to work and never supported. If you were declaring your\n queues as a comma-separated list, e.g. `sidekiq -q critical,default,low`,\n you must now use the `-q` flag before each queue, e.g.\n `sidekiq -q critical -q default -q low`.", "2.17.1\n-----------", "- Expose `delay` extension as `sidekiq_delay` also. This allows you to\n run Delayed::Job and Sidekiq in the same process, selectively porting\n `delay` calls to `sidekiq_delay`. You just need to ensure that\n Sidekiq is required **before** Delayed::Job in your Gemfile. [#1393]\n- Bump redis client required version to 3.0.6\n- Minor CSS fixes for Web UI", "2.17.0\n-----------", "- Change `Sidekiq::Client#push_bulk` to return an array of pushed `jid`s. [#1315, barelyknown]\n- Web UI refactoring to use more API internally (yummy dogfood!)\n- Much faster Sidekiq::Job#delete performance for larger queue sizes\n- Further capistrano 3 fixes\n- Many misc minor fixes", "2.16.1\n-----------", "- Revert usage of `resolv-replace`. MRI's native DNS lookup releases the GIL.\n- Fix several Capistrano 3 issues\n- Escaping dynamic data like job args and error messages in Sidekiq Web UI. [#1299, lian]", "2.16.0\n-----------", "- Deprecate `Sidekiq::Client.registered_workers` and `Sidekiq::Client.registered_queues`\n- Refactor Sidekiq::Client to be instance-based [#1279]\n- Pass all Redis options to the Redis driver so Unix sockets\n can be fully configured. [#1270, salimane]\n- Allow sidekiq-web extensions to add locale paths so extensions\n can be localized. [#1261, ondrejbartas]\n- Capistrano 3 support [#1254, phallstrom]\n- Use Ruby's `resolv-replace` to enable pure Ruby DNS lookups.\n This ensures that any DNS resolution that takes place in worker\n threads won't lock up the entire VM on MRI. [#1258]", "2.15.2\n-----------", "- Iterating over Sidekiq::Queue and Sidekiq::SortedSet will now work as\n intended when jobs are deleted [#866, aackerman]\n- A few more minor Web UI fixes [#1247]", "2.15.1\n-----------", "- Fix several Web UI issues with the Bootstrap 3 upgrade.", "2.15.0\n-----------", "- The Core Sidekiq actors are now monitored. If any crash, the\n Sidekiq process logs the error and exits immediately. This is to\n help prevent \"stuck\" Sidekiq processes which are running but don't\n appear to be doing any work. [#1194]\n- Sidekiq's testing behavior is now dynamic. You can choose between\n `inline` and `fake` behavior in your tests. See\n[Testing](https://github.com/sidekiq/sidekiq/wiki/Testing) for detail. [#1193]\n- The Retries table has a new column for the error message.\n- The Web UI topbar now contains the status and live poll button.\n- Orphaned worker records are now auto-vacuumed when you visit the\n Workers page in the Web UI.\n- Sidekiq.default\\_worker\\_options allows you to configure default\n options for all Sidekiq worker types.", "```ruby\nSidekiq.default_worker_options = { 'queue' => 'default', 'backtrace' => true }\n```\n- Added two Sidekiq::Client class methods for compatibility with resque-scheduler:\n `enqueue_to_in` and `enqueue_in` [#1212]\n- Upgrade Web UI to Bootstrap 3.0. [#1211, jeffboek]", "2.14.1\n-----------", "- Fix misc Web UI issues due to ERB conversion.\n- Bump redis-namespace version due to security issue.", "2.14.0\n-----------", "- Removed slim gem dependency, Web UI now uses ERB [Locke23rus, #1120]\n- Fix more race conditions in Web UI actions\n- Don't reset Job enqueued\\_at when retrying\n- Timestamp tooltips in the Web UI should use UTC\n- Fix invalid usage of handle\\_exception causing issues in Airbrake\n [#1134]", "\n2.13.1\n-----------", "- Make Sidekiq::Middleware::Chain Enumerable\n- Make summary bar and graphs responsive [manishval, #1025]\n- Adds a job status page for scheduled jobs [jonhyman]\n- Handle race condition in retrying and deleting jobs in the Web UI\n- The Web UI relative times are now i18n. [MadRabbit, #1088]\n- Allow for default number of retry attempts to be set for\n `Sidekiq::Middleware::Server::RetryJobs` middleware. [czarneckid] [#1091]", "```ruby\nSidekiq.configure_server do |config|\n config.server_middleware do |chain|\n chain.add Sidekiq::Middleware::Server::RetryJobs, :max_retries => 10\n end\nend\n```", "\n2.13.0\n-----------", "- Adding button to move scheduled job to main queue [guiceolin, #1020]\n- fix i18n support resetting saved locale when job is retried [#1011]\n- log rotation via USR2 now closes the old logger [#1008]\n- Add ability to customize retry schedule, like so [jmazzi, #1027]", "```ruby\nclass MyWorker\n include Sidekiq::Worker\n sidekiq_retry_in { |count| count * 2 }\nend\n```\n- Redesign Worker#retries\\_exhausted callback to use same form as above [jmazzi, #1030]", "```ruby\nclass MyWorker\n include Sidekiq::Worker\n sidekiq_retries_exhausted do |msg|\n Rails.logger.error \"Failed to process #{msg['class']} with args: #{msg['args']}\"\n end\nend\n```", "2.12.4\n-----------", "- Fix error in previous release which crashed the Manager when a\n Processor died.", "2.12.3\n-----------", "- Revert back to Celluloid's TaskFiber for job processing which has proven to be more\n stable than TaskThread. [#985]\n- Avoid possible lockup during hard shutdown [#997]", "At this point, if you are experiencing stability issues with Sidekiq in\nRuby 1.9, please try Ruby 2.0. It seems to be more stable.", "2.12.2\n-----------", "- Relax slim version requirement to >= 1.1.0\n- Refactor historical stats to use TTL, not explicit cleanup. [grosser, #971]", "2.12.1\n-----------", "- Force Celluloid 0.14.1 as 0.14.0 has a serious bug. [#954]\n- Scheduled and Retry jobs now use Sidekiq::Client to push\n jobs onto the queue, so they use client middleware. [dimko, #948]\n- Record the timestamp when jobs are enqueued. Add\n Sidekiq::Job#enqueued\\_at to query the time. [mariovisic, #944]\n- Add Sidekiq::Queue#latency - calculates diff between now and\n enqueued\\_at for the oldest job in the queue.\n- Add testing method `perform_one` that dequeues and performs a single job.\n This is mainly to aid testing jobs that spawn other jobs. [fumin, #963]", "2.12.0\n-----------", "- Upgrade to Celluloid 0.14, remove the use of Celluloid's thread\n pool. This should halve the number of threads in each Sidekiq\n process, thus requiring less resources. [#919]\n- Abstract Celluloid usage to Sidekiq::Actor for testing purposes.\n- Better handling for Redis downtime when fetching jobs and shutting\n down, don't print exceptions every second and print success message\n when Redis is back.\n- Fix unclean shutdown leading to duplicate jobs [#897]\n- Add Korean locale [#890]\n- Upgrade test suite to Minitest 5\n- Remove usage of `multi_json` as `json` is now robust on all platforms.", "2.11.2\n-----------", "- Fix Web UI when used without Rails [#886]\n- Add Sidekiq::Stats#reset [#349]\n- Add Norwegian locale.\n- Updates for the JA locale.", "2.11.1\n-----------", "- Fix timeout warning.\n- Add Dutch web UI locale.", "2.11.0\n-----------", "- Upgrade to Celluloid 0.13. [#834]\n- Remove **timeout** support from `sidekiq_options`. Ruby's timeout\n is inherently unsafe in a multi-threaded application and was causing\n stability problems for many. See http://bit.ly/OtYpK\n- Add Japanese locale for Web UI [#868]\n- Fix a few issues with Web UI i18n.", "2.10.1\n-----------", "- Remove need for the i18n gem. (brandonhilkert)\n- Improve redis connection info logging on startup for debugging\npurposes [#858]\n- Revert sinatra/slim as runtime dependencies\n- Add `find_job` method to sidekiq/api", "\n2.10.0\n-----------", "- Refactor algorithm for putting scheduled jobs onto the queue [#843]\n- Fix scheduler thread dying due to incorrect error handling [#839]\n- Fix issue which left stale workers if Sidekiq wasn't shutdown while\nquiet. [#840]\n- I18n for web UI. Please submit translations of `web/locales/en.yml` for\nyour own language. [#811]\n- 'sinatra', 'slim' and 'i18n' are now gem dependencies for Sidekiq.", "\n2.9.0\n-----------", "- Update 'sidekiq/testing' to work with any Sidekiq::Client call. It\n also serializes the arguments as using Redis would. [#713]\n- Raise a Sidekiq::Shutdown error within workers which don't finish within the hard\n timeout. This is to prevent unwanted database transaction commits. [#377]\n- Lazy load Redis connection pool, you no longer need to specify\n anything in Passenger or Unicorn's after_fork callback [#794]\n- Add optional Worker#retries_exhausted hook after max retries failed. [jkassemi, #780]\n- Fix bug in pagination link to last page [pitr, #774]\n- Upstart scripts for multiple Sidekiq instances [dariocravero, #763]\n- Use select via pipes instead of poll to catch signals [mrnugget, #761]", "2.8.0\n-----------", "- I18n support! Sidekiq can optionally save and restore the Rails locale\n so it will be properly set when your jobs execute. Just include\n `require 'sidekiq/middleware/i18n'` in your sidekiq initializer. [#750]\n- Fix bug which could lose messages when using namespaces and the message\nneeds to be requeued in Redis. [#744]\n- Refactor Redis namespace support [#747]. The redis namespace can no longer be\n passed via the config file, the only supported way is via Ruby in your\n initializer:", "```ruby\nsidekiq_redis = { :url => 'redis://localhost:3679', :namespace => 'foo' }\nSidekiq.configure_server { |config| config.redis = sidekiq_redis }\nSidekiq.configure_client { |config| config.redis = sidekiq_redis }\n```", "A warning is printed out to the log if a namespace is found in your sidekiq.yml.", "\n2.7.5\n-----------", "- Capistrano no longer uses daemonization in order to work with JRuby [#719]\n- Refactor signal handling to work on Ruby 2.0 [#728, #730]\n- Fix dashboard refresh URL [#732]", "2.7.4\n-----------", "- Fixed daemonization, was broken by some internal refactoring in 2.7.3 [#727]", "2.7.3\n-----------", "- Real-time dashboard is now the default web page\n- Make config file optional for capistrano\n- Fix Retry All button in the Web UI", "2.7.2\n-----------", "- Remove gem signing infrastructure. It was causing Sidekiq to break\nwhen used via git in Bundler. This is why we can't have nice things. [#688]", "\n2.7.1\n-----------", "- Fix issue with hard shutdown [#680]", "\n2.7.0\n-----------", "- Add -d daemonize flag, capistrano recipe has been updated to use it [#662]\n- Support profiling via `ruby-prof` with -p. When Sidekiq is stopped\n via Ctrl-C, it will output `profile.html`. You must add `gem 'ruby-prof'` to your Gemfile for it to work.\n- Dynamically update Redis stats on dashboard [brandonhilkert]\n- Add Sidekiq::Workers API giving programmatic access to the current\n set of active workers.", "```\nworkers = Sidekiq::Workers.new\nworkers.size => 2\nworkers.each do |name, work|\n # name is a unique identifier per Processor instance\n # work is a Hash which looks like:\n # { 'queue' => name, 'run_at' => timestamp, 'payload' => msg }\nend\n```", "- Allow environment-specific sections within the config file which\noverride the global values [dtaniwaki, #630]", "```\n---\n:concurrency: 50\n:verbose: false\nstaging:\n :verbose: true\n :concurrency: 5\n```", "\n2.6.5\n-----------", "- Several reliability fixes for job requeueing upon termination [apinstein, #622, #624]\n- Fix typo in capistrano recipe\n- Add `retry_queue` option so retries can be given lower priority [ryanlower, #620]", "```ruby\nsidekiq_options queue: 'high', retry_queue: 'low'\n```", "2.6.4\n-----------", "- Fix crash upon empty queue [#612]", "2.6.3\n-----------", "- sidekiqctl exits with non-zero exit code upon error [jmazzi]\n- better argument validation in Sidekiq::Client [karlfreeman]", "2.6.2\n-----------", "- Add Dashboard beacon indicating when stats are updated. [brandonhilkert, #606]\n- Revert issue with capistrano restart. [#598]", "2.6.1\n-----------", "- Dashboard now live updates summary stats also. [brandonhilkert, #605]\n- Add middleware chain APIs `insert_before` and `insert_after` for fine\n tuning the order of middleware. [jackrg, #595]", "2.6.0\n-----------", "- Web UI much more mobile friendly now [brandonhilkert, #573]\n- Enable live polling for every section in Web UI [brandonhilkert, #567]\n- Add Stats API [brandonhilkert, #565]\n- Add Stats::History API [brandonhilkert, #570]\n- Add Dashboard to Web UI with live and historical stat graphs [brandonhilkert, #580]\n- Add option to log output to a file, reopen log file on USR2 signal [mrnugget, #581]", "2.5.4\n-----------", "- `Sidekiq::Client.push` now accepts the worker class as a string so the\n Sidekiq client does not have to load your worker classes at all. [#524]\n- `Sidekiq::Client.push_bulk` now works with inline testing.\n- **Really** fix status icon in Web UI this time.\n- Add \"Delete All\" and \"Retry All\" buttons to Retries in Web UI", "\n2.5.3\n-----------", "- Small Web UI fixes\n- Add `delay_until` so you can delay jobs until a specific timestamp:", "```ruby\nAuction.delay_until(@auction.ends_at).close(@auction.id)\n```", "This is identical to the existing Sidekiq::Worker method, `perform_at`.", "2.5.2\n-----------", "- Remove asset pipeline from Web UI for much faster, simpler runtime. [#499, #490, #481]\n- Add -g option so the procline better identifies a Sidekiq process, defaults to File.basename(Rails.root). [#486]", " sidekiq 2.5.1 myapp [0 of 25 busy]", "- Add splay to retry time so groups of failed jobs don't fire all at once. [#483]", "2.5.1\n-----------", "- Fix issues with core\\_ext", "2.5.0\n-----------", "- REDESIGNED WEB UI! [unity, cavneb]\n- Support Honeybadger for error delivery\n- Inline testing runs the client middleware before executing jobs [#465]\n- Web UI can now remove jobs from queue. [#466, dleung]\n- Web UI can now show the full message, not just 100 chars [#464, dleung]\n- Add APIs for manipulating the retry and job queues. See sidekiq/api. [#457]", "\n2.4.0\n-----------", "- ActionMailer.delay.method now only tries to deliver if method returns a valid message.\n- Logging now uses \"MSG-#{Job ID}\", not a random msg ID\n- Allow generic Redis provider as environment variable. [#443]\n- Add ability to customize sidekiq\\_options with delay calls [#450]", "```ruby\nFoo.delay(:retry => false).bar\nFoo.delay(:retry => 10).bar\nFoo.delay(:timeout => 10.seconds).bar\nFoo.delay_for(5.minutes, :timeout => 10.seconds).bar\n```", "2.3.3\n-----------", "- Remove option to disable Rails hooks. [#401]\n- Allow delay of any module class method", "2.3.2\n-----------", "- Fix retry. 2.3.1 accidentally disabled it.", "2.3.1\n-----------", "- Add Sidekiq::Client.push\\_bulk for bulk adding of jobs to Redis.\n My own simple test case shows pushing 10,000 jobs goes from 5 sec to 1.5 sec.\n- Add support for multiple processes per host to Capistrano recipe\n- Re-enable Celluloid::Actor#defer to fix stack overflow issues [#398]", "2.3.0\n-----------", "- Upgrade Celluloid to 0.12\n- Upgrade Twitter Bootstrap to 2.1.0\n- Rescue more Exceptions\n- Change Job ID to be Hex, rather than Base64, for HTTP safety\n- Use `Airbrake#notify_or_ignore`", "2.2.1\n-----------", "- Add support for custom tabs to Sidekiq::Web [#346]\n- Change capistrano recipe to run 'quiet' before deploy:update\\_code so\n it is run upon both 'deploy' and 'deploy:migrations'. [#352]\n- Rescue Exception rather than StandardError to catch and log any sort\n of Processor death.", "2.2.0\n-----------", "- Roll back Celluloid optimizations in 2.1.0 which caused instability.\n- Add extension to delay any arbitrary class method to Sidekiq.\n Previously this was limited to ActiveRecord classes.", "```ruby\nSomeClass.delay.class_method(1, 'mike', Date.today)\n```", "- Sidekiq::Client now generates and returns a random, 128-bit Job ID 'jid' which\n can be used to track the processing of a Job, e.g. for calling back to a webhook\n when a job is finished.", "2.1.1\n-----------", "- Handle networking errors causing the scheduler thread to die [#309]\n- Rework exception handling to log all Processor and actor death (#325, subelsky)\n- Clone arguments when calling worker so modifications are discarded. (#265, hakanensari)", "2.1.0\n-----------", "- Tune Celluloid to no longer run message processing within a Fiber.\n This gives us a full Thread stack and also lowers Sidekiq's memory\n usage.\n- Add pagination within the Web UI [#253]\n- Specify which Redis driver to use: *hiredis* or *ruby* (default)\n- Remove FailureJobs and UniqueJobs, which were optional middleware\n that I don't want to support in core. [#302]", "2.0.3\n-----------\n- Fix sidekiq-web's navbar on mobile devices and windows under 980px (ezkl)\n- Fix Capistrano task for first deploys [#259]\n- Worker subclasses now properly inherit sidekiq\\_options set in\n their superclass [#221]\n- Add random jitter to scheduler to spread polls across POLL\\_INTERVAL\n window. [#247]\n- Sidekiq has a new mailing list: sidekiq@librelist.org See README.", "2.0.2\n-----------", "- Fix \"Retry Now\" button on individual retry page. (ezkl)", "2.0.1\n-----------", "- Add \"Clear Workers\" button to UI. If you kill -9 Sidekiq, the workers\n set can fill up with stale entries.\n- Update sidekiq/testing to support new scheduled jobs API:", " ```ruby\n require 'sidekiq/testing'\n DirectWorker.perform_in(10.seconds, 1, 2)\n assert_equal 1, DirectWorker.jobs.size\n assert_in_delta 10.seconds.from_now.to_f, DirectWorker.jobs.last['at'], 0.01\n ```", "2.0.0\n-----------", "- **SCHEDULED JOBS**!", "You can now use `perform_at` and `perform_in` to schedule jobs\nto run at arbitrary points in the future, like so:", "```ruby\n SomeWorker.perform_in(5.days, 'bob', 13)\n SomeWorker.perform_at(5.days.from_now, 'bob', 13)\n```", "It also works with the delay extensions:", "```ruby\n UserMailer.delay_for(5.days).send_welcome_email(user.id)\n```", "The time is approximately when the job will be placed on the queue;\nit is not guaranteed to run at precisely at that moment in time.", "This functionality is meant for one-off, arbitrary jobs. I still\nrecommend `whenever` or `clockwork` if you want cron-like,\nrecurring jobs. See `examples/scheduling.rb`", "I want to specially thank @yabawock for his work on sidekiq-scheduler.\nHis extension for Sidekiq 1.x filled an obvious functional gap that I now think is\nuseful enough to implement in Sidekiq proper.", "- Fixed issues due to Redis 3.x API changes. Sidekiq now requires\n the Redis 3.x client.\n- Inline testing now round trips arguments through JSON to catch\n serialization issues (betelgeuse)", "1.2.1\n-----------", "- Sidekiq::Worker now has access to Sidekiq's standard logger\n- Fix issue with non-StandardErrors leading to Processor exhaustion\n- Fix issue with Fetcher slowing Sidekiq shutdown\n- Print backtraces for all threads upon TTIN signal [#183]\n- Overhaul retries Web UI with new index page and bulk operations [#184]", "1.2.0\n-----------", "- Full or partial error backtraces can optionally be stored as part of the retry\n for display in the web UI if you aren't using an error service. [#155]", "```ruby\nclass Worker\n include Sidekiq::Worker\n sidekiq_options :backtrace => [true || 10]\nend\n```\n- Add timeout option to kill a worker after N seconds (blackgold9)", "```ruby\nclass HangingWorker\n include Sidekiq::Worker\n sidekiq_options :timeout => 600\n def perform\n # will be killed if it takes longer than 10 minutes\n end\nend\n```", "- Fix delayed extensions not available in workers [#152]\n- In test environments add the `#drain` class method to workers. This method\n executes all previously queued jobs. (panthomakos)\n- Sidekiq workers can be run inline during tests, just `require 'sidekiq/testing/inline'` (panthomakos)\n- Queues can now be deleted from the Sidekiq web UI [#154]\n- Fix unnecessary shutdown delay due to Retry Poller [#174]", "1.1.4\n-----------", "- Add 24 hr expiry for basic keys set in Redis, to avoid any possible leaking.\n- Only register workers in Redis while working, to avoid lingering\n workers [#156]\n- Speed up shutdown significantly.", "1.1.3\n-----------", "- Better network error handling when fetching jobs from Redis.\n Sidekiq will retry once per second until it can re-establish\n a connection. (ryanlecompte)\n- capistrano recipe now uses `bundle_cmd` if set [#147]\n- handle multi\\_json API changes (sferik)", "1.1.2\n-----------", "- Fix double restart with cap deploy [#137]", "1.1.1\n-----------", "- Set procline for easy monitoring of Sidekiq status via \"ps aux\"\n- Fix race condition on shutdown [#134]\n- Fix hang with cap sidekiq:start [#131]", "1.1.0\n-----------", "- The Sidekiq license has switched from GPLv3 to LGPLv3!\n- Sidekiq::Client.push now returns whether the actual Redis\n operation succeeded or not. [#123]\n- Remove UniqueJobs from the default middleware chain. Its\n functionality, while useful, is unexpected for new Sidekiq\n users. You can re-enable it with the following config.\n Read #119 for more discussion.", "```ruby\nSidekiq.configure_client do |config|\n require 'sidekiq/middleware/client/unique_jobs'\n config.client_middleware do |chain|\n chain.add Sidekiq::Middleware::Client::UniqueJobs\n end\nend\nSidekiq.configure_server do |config|\n require 'sidekiq/middleware/server/unique_jobs'\n config.server_middleware do |chain|\n chain.add Sidekiq::Middleware::Server::UniqueJobs\n end\nend\n```", "1.0.0\n-----------", "Thanks to all Sidekiq users and contributors for helping me\nget to this big milestone!", "- Default concurrency on client-side to 5, not 25 so we don't\n create as many unused Redis connections, same as ActiveRecord's\n default pool size.\n- Ensure redis= is given a Hash or ConnectionPool.", "0.11.2\n-----------", "- Implement \"safe shutdown\". The messages for any workers that\n are still busy when we hit the TERM timeout will be requeued in\n Redis so the messages are not lost when the Sidekiq process exits.\n [#110]\n- Work around Celluloid's small 4kb stack limit [#115]\n- Add support for a custom Capistrano role to limit Sidekiq to\n a set of machines. [#113]", "0.11.1\n-----------", "- Fix fetch breaking retry when used with Redis namespaces. [#109]\n- Redis connection now just a plain ConnectionPool, not CP::Wrapper.\n- Capistrano initial deploy fix [#106]\n- Re-implemented weighted queues support (ryanlecompte)", "0.11.0\n-----------", "- Client-side API changes, added sidekiq\\_options for Sidekiq::Worker.\n As a side effect of this change, the client API works on Ruby 1.8.\n It's not officially supported but should work [#103]\n- NO POLL! Sidekiq no longer polls Redis, leading to lower network\n utilization and lower latency for message processing.\n- Add --version CLI option", "0.10.1\n-----------", "- Add details page for jobs in retry queue (jcoene)\n- Display relative timestamps in web interface (jcoene)\n- Capistrano fixes (hinrik, bensie)", "0.10.0\n-----------", "- Reworked capistrano recipe to make it more fault-tolerant [#94].\n- Automatic failure retry! Sidekiq will now save failed messages\n and retry them, with an exponential backoff, over about 20 days.\n Did a message fail to process? Just deploy a bug fix in the next\n few days and Sidekiq will retry the message eventually.", "0.9.1\n-----------", "- Fix missed deprecations, poor method name in web UI", "0.9.0\n-----------", "- Add -t option to configure the TERM shutdown timeout\n- TERM shutdown timeout is now configurable, defaults to 5 seconds.\n- USR1 signal now stops Sidekiq from accepting new work,\n capistrano sends USR1 at start of deploy and TERM at end of deploy\n giving workers the maximum amount of time to finish.\n- New Sidekiq::Web rack application available\n- Updated Sidekiq.redis API", "0.8.0\n-----------", "- Remove :namespace and :server CLI options (mperham)\n- Add ExceptionNotifier support (masterkain)\n- Add capistrano support (mperham)\n- Workers now log upon start and finish (mperham)\n- Messages for terminated workers are now automatically requeued (mperham)\n- Add support for Exceptional error reporting (bensie)", "0.7.0\n-----------", "- Example chef recipe and monitrc script (jc00ke)\n- Refactor global configuration into Sidekiq.configure\\_server and\n Sidekiq.configure\\_client blocks. (mperham)\n- Add optional middleware FailureJobs which saves failed jobs to a\n 'failed' queue (fbjork)\n- Upon shutdown, workers are now terminated after 5 seconds. This is to\n meet Heroku's hard limit of 10 seconds for a process to shutdown. (mperham)\n- Refactor middleware API for simplicity, see sidekiq/middleware/chain. (mperham)\n- Add `delay` extensions for ActionMailer and ActiveRecord. (mperham)\n- Added config file support. See test/config.yml for an example file. (jc00ke)\n- Added pidfile for tools like monit (jc00ke)", "0.6.0\n-----------", "- Resque-compatible processing stats in redis (mperham)\n- Simple client testing support in sidekiq/testing (mperham)\n- Plain old Ruby support via the -r cli flag (mperham)\n- Refactored middleware support, introducing ability to add client-side middleware (ryanlecompte)\n- Added middleware for ignoring duplicate jobs (ryanlecompte)\n- Added middleware for displaying jobs in resque-web dashboard (maxjustus)\n- Added redis namespacing support (maxjustus)", "0.5.1\n-----------", "- Initial release!" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [9, 5, 81], "buggy_code_start_loc": [5, 4, 71], "filenames": ["Changes.md", "lib/sidekiq/version.rb", "lib/sidekiq/web/application.rb"], "fixing_code_end_loc": [12, 5, 81], "fixing_code_start_loc": [5, 4, 71], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:contribsys:sidekiq:*:*:*:*:*:*:*:*", "matchCriteriaId": "5B32B98F-EEB2-4982-976A-BEC2ECE01909", "versionEndExcluding": "7.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0.4", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8."}], "evaluatorComment": null, "id": "CVE-2023-1892", "lastModified": "2023-06-09T18:07:41.737", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 8.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.6, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-21T05:15:07.057", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/e35e5653-c429-4fb8-94a3-cbc123ae4777"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, "type": "CWE-79"}
244
Determine whether the {function_name} code is vulnerable or not.
[ "# frozen_string_literal: true", "module Sidekiq", " VERSION = \"7.0.7\"", " MAJOR = 7\nend" ]
[ 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 5, 81], "buggy_code_start_loc": [5, 4, 71], "filenames": ["Changes.md", "lib/sidekiq/version.rb", "lib/sidekiq/web/application.rb"], "fixing_code_end_loc": [12, 5, 81], "fixing_code_start_loc": [5, 4, 71], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:contribsys:sidekiq:*:*:*:*:*:*:*:*", "matchCriteriaId": "5B32B98F-EEB2-4982-976A-BEC2ECE01909", "versionEndExcluding": "7.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0.4", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8."}], "evaluatorComment": null, "id": "CVE-2023-1892", "lastModified": "2023-06-09T18:07:41.737", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 8.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.6, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-21T05:15:07.057", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/e35e5653-c429-4fb8-94a3-cbc123ae4777"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, "type": "CWE-79"}
244
Determine whether the {function_name} code is vulnerable or not.
[ "# frozen_string_literal: true", "module Sidekiq", " VERSION = \"7.0.8\"", " MAJOR = 7\nend" ]
[ 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 5, 81], "buggy_code_start_loc": [5, 4, 71], "filenames": ["Changes.md", "lib/sidekiq/version.rb", "lib/sidekiq/web/application.rb"], "fixing_code_end_loc": [12, 5, 81], "fixing_code_start_loc": [5, 4, 71], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:contribsys:sidekiq:*:*:*:*:*:*:*:*", "matchCriteriaId": "5B32B98F-EEB2-4982-976A-BEC2ECE01909", "versionEndExcluding": "7.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0.4", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8."}], "evaluatorComment": null, "id": "CVE-2023-1892", "lastModified": "2023-06-09T18:07:41.737", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 8.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.6, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-21T05:15:07.057", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/e35e5653-c429-4fb8-94a3-cbc123ae4777"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, "type": "CWE-79"}
244
Determine whether the {function_name} code is vulnerable or not.
[ "# frozen_string_literal: true", "module Sidekiq\n class WebApplication\n extend WebRouter", " REDIS_KEYS = %w[redis_version uptime_in_days connected_clients used_memory_human used_memory_peak_human]\n CSP_HEADER = [\n \"default-src 'self' https: http:\",\n \"child-src 'self'\",\n \"connect-src 'self' https: http: wss: ws:\",\n \"font-src 'self' https: http:\",\n \"frame-src 'self'\",\n \"img-src 'self' https: http: data:\",\n \"manifest-src 'self'\",\n \"media-src 'self'\",\n \"object-src 'none'\",\n \"script-src 'self' https: http: 'unsafe-inline'\",\n \"style-src 'self' https: http: 'unsafe-inline'\",\n \"worker-src 'self'\",\n \"base-uri 'self'\"\n ].join(\"; \").freeze\n METRICS_PERIODS = {\n \"1h\" => 60,\n \"2h\" => 120,\n \"4h\" => 240,\n \"8h\" => 480\n }", " def initialize(klass)\n @klass = klass\n end", " def settings\n @klass.settings\n end", " def self.settings\n Sidekiq::Web.settings\n end", " def self.tabs\n Sidekiq::Web.tabs\n end", " def self.set(key, val)\n # nothing, backwards compatibility\n end", " head \"/\" do\n # HEAD / is the cheapest heartbeat possible,\n # it hits Redis to ensure connectivity\n Sidekiq.redis { |c| c.llen(\"queue:default\") }\n \"\"\n end", " get \"/\" do\n @redis_info = redis_info.select { |k, v| REDIS_KEYS.include? k }\n days = (params[\"days\"] || 30).to_i\n return halt(401) if days < 1 || days > 180", " stats_history = Sidekiq::Stats::History.new(days)\n @processed_history = stats_history.processed\n @failed_history = stats_history.failed", " erb(:dashboard)\n end", " get \"/metrics\" do\n q = Sidekiq::Metrics::Query.new", " @period = params[:period]", " @periods = METRICS_PERIODS\n minutes = @periods.fetch(@period, @periods.values.first)\n @query_result = q.top_jobs(minutes: minutes)\n erb(:metrics)\n end", " get \"/metrics/:name\" do\n @name = route_params[:name]", " @period = params[:period]", " q = Sidekiq::Metrics::Query.new\n @periods = METRICS_PERIODS\n minutes = @periods.fetch(@period, @periods.values.first)\n @query_result = q.for_job(@name, minutes: minutes)\n erb(:metrics_for_job)\n end", " get \"/busy\" do\n @count = (params[\"count\"] || 100).to_i\n (@current_page, @total_size, @workset) = page_items(workset, params[\"page\"], @count)", " erb(:busy)\n end", " post \"/busy\" do\n if params[\"identity\"]\n pro = Sidekiq::ProcessSet[params[\"identity\"]]", " pro.quiet! if params[\"quiet\"]\n pro.stop! if params[\"stop\"]\n else\n processes.each do |pro|\n next if pro.embedded?", " pro.quiet! if params[\"quiet\"]\n pro.stop! if params[\"stop\"]\n end\n end", " redirect \"#{root_path}busy\"\n end", " get \"/queues\" do\n @queues = Sidekiq::Queue.all", " erb(:queues)\n end", " QUEUE_NAME = /\\A[a-z_:.\\-0-9]+\\z/i", " get \"/queues/:name\" do\n @name = route_params[:name]", " halt(404) if !@name || @name !~ QUEUE_NAME", " @count = (params[\"count\"] || 25).to_i\n @queue = Sidekiq::Queue.new(@name)\n (@current_page, @total_size, @jobs) = page(\"queue:#{@name}\", params[\"page\"], @count, reverse: params[\"direction\"] == \"asc\")\n @jobs = @jobs.map { |msg| Sidekiq::JobRecord.new(msg, @name) }", " erb(:queue)\n end", " post \"/queues/:name\" do\n queue = Sidekiq::Queue.new(route_params[:name])", " if Sidekiq.pro? && params[\"pause\"]\n queue.pause!\n elsif Sidekiq.pro? && params[\"unpause\"]\n queue.unpause!\n else\n queue.clear\n end", " redirect \"#{root_path}queues\"\n end", " post \"/queues/:name/delete\" do\n name = route_params[:name]\n Sidekiq::JobRecord.new(params[\"key_val\"], name).delete", " redirect_with_query(\"#{root_path}queues/#{CGI.escape(name)}\")\n end", " get \"/morgue\" do\n @count = (params[\"count\"] || 25).to_i\n (@current_page, @total_size, @dead) = page(\"dead\", params[\"page\"], @count, reverse: true)\n @dead = @dead.map { |msg, score| Sidekiq::SortedEntry.new(nil, score, msg) }", " erb(:morgue)\n end", " get \"/morgue/:key\" do\n key = route_params[:key]\n halt(404) unless key", " @dead = Sidekiq::DeadSet.new.fetch(*parse_params(key)).first", " if @dead.nil?\n redirect \"#{root_path}morgue\"\n else\n erb(:dead)\n end\n end", " post \"/morgue\" do\n redirect(request.path) unless params[\"key\"]", " params[\"key\"].each do |key|\n job = Sidekiq::DeadSet.new.fetch(*parse_params(key)).first\n retry_or_delete_or_kill job, params if job\n end", " redirect_with_query(\"#{root_path}morgue\")\n end", " post \"/morgue/all/delete\" do\n Sidekiq::DeadSet.new.clear", " redirect \"#{root_path}morgue\"\n end", " post \"/morgue/all/retry\" do\n Sidekiq::DeadSet.new.retry_all", " redirect \"#{root_path}morgue\"\n end", " post \"/morgue/:key\" do\n key = route_params[:key]\n halt(404) unless key", " job = Sidekiq::DeadSet.new.fetch(*parse_params(key)).first\n retry_or_delete_or_kill job, params if job", " redirect_with_query(\"#{root_path}morgue\")\n end", " get \"/retries\" do\n @count = (params[\"count\"] || 25).to_i\n (@current_page, @total_size, @retries) = page(\"retry\", params[\"page\"], @count)\n @retries = @retries.map { |msg, score| Sidekiq::SortedEntry.new(nil, score, msg) }", " erb(:retries)\n end", " get \"/retries/:key\" do\n @retry = Sidekiq::RetrySet.new.fetch(*parse_params(route_params[:key])).first", " if @retry.nil?\n redirect \"#{root_path}retries\"\n else\n erb(:retry)\n end\n end", " post \"/retries\" do\n redirect(request.path) unless params[\"key\"]", " params[\"key\"].each do |key|\n job = Sidekiq::RetrySet.new.fetch(*parse_params(key)).first\n retry_or_delete_or_kill job, params if job\n end", " redirect_with_query(\"#{root_path}retries\")\n end", " post \"/retries/all/delete\" do\n Sidekiq::RetrySet.new.clear", " redirect \"#{root_path}retries\"\n end", " post \"/retries/all/retry\" do\n Sidekiq::RetrySet.new.retry_all", " redirect \"#{root_path}retries\"\n end", " post \"/retries/all/kill\" do\n Sidekiq::RetrySet.new.kill_all", " redirect \"#{root_path}retries\"\n end", " post \"/retries/:key\" do\n job = Sidekiq::RetrySet.new.fetch(*parse_params(route_params[:key])).first", " retry_or_delete_or_kill job, params if job", " redirect_with_query(\"#{root_path}retries\")\n end", " get \"/scheduled\" do\n @count = (params[\"count\"] || 25).to_i\n (@current_page, @total_size, @scheduled) = page(\"schedule\", params[\"page\"], @count)\n @scheduled = @scheduled.map { |msg, score| Sidekiq::SortedEntry.new(nil, score, msg) }", " erb(:scheduled)\n end", " get \"/scheduled/:key\" do\n @job = Sidekiq::ScheduledSet.new.fetch(*parse_params(route_params[:key])).first", " if @job.nil?\n redirect \"#{root_path}scheduled\"\n else\n erb(:scheduled_job_info)\n end\n end", " post \"/scheduled\" do\n redirect(request.path) unless params[\"key\"]", " params[\"key\"].each do |key|\n job = Sidekiq::ScheduledSet.new.fetch(*parse_params(key)).first\n delete_or_add_queue job, params if job\n end", " redirect_with_query(\"#{root_path}scheduled\")\n end", " post \"/scheduled/:key\" do\n key = route_params[:key]\n halt(404) unless key", " job = Sidekiq::ScheduledSet.new.fetch(*parse_params(key)).first\n delete_or_add_queue job, params if job", " redirect_with_query(\"#{root_path}scheduled\")\n end", " get \"/dashboard/stats\" do\n redirect \"#{root_path}stats\"\n end", " get \"/stats\" do\n sidekiq_stats = Sidekiq::Stats.new\n redis_stats = redis_info.select { |k, v| REDIS_KEYS.include? k }\n json(\n sidekiq: {\n processed: sidekiq_stats.processed,\n failed: sidekiq_stats.failed,\n busy: sidekiq_stats.workers_size,\n processes: sidekiq_stats.processes_size,\n enqueued: sidekiq_stats.enqueued,\n scheduled: sidekiq_stats.scheduled_size,\n retries: sidekiq_stats.retry_size,\n dead: sidekiq_stats.dead_size,\n default_latency: sidekiq_stats.default_queue_latency\n },\n redis: redis_stats,\n server_utc_time: server_utc_time\n )\n end", " get \"/stats/queues\" do\n json Sidekiq::Stats.new.queues\n end", " def call(env)\n action = self.class.match(env)\n return [404, {\"content-type\" => \"text/plain\", \"x-cascade\" => \"pass\"}, [\"Not Found\"]] unless action", " app = @klass\n resp = catch(:halt) do\n self.class.run_befores(app, action)\n action.instance_exec env, &action.block\n ensure\n self.class.run_afters(app, action)\n end", " case resp\n when Array\n # redirects go here\n resp\n else\n # rendered content goes here\n headers = {\n \"content-type\" => \"text/html\",\n \"cache-control\" => \"private, no-store\",\n \"content-language\" => action.locale,\n \"content-security-policy\" => CSP_HEADER\n }\n # we'll let Rack calculate Content-Length for us.\n [200, headers, [resp]]\n end\n end", " def self.helpers(mod = nil, &block)\n if block\n WebAction.class_eval(&block)\n else\n WebAction.send(:include, mod)\n end\n end", " def self.before(path = nil, &block)\n befores << [path && Regexp.new(\"\\\\A#{path.gsub(\"*\", \".*\")}\\\\z\"), block]\n end", " def self.after(path = nil, &block)\n afters << [path && Regexp.new(\"\\\\A#{path.gsub(\"*\", \".*\")}\\\\z\"), block]\n end", " def self.run_befores(app, action)\n run_hooks(befores, app, action)\n end", " def self.run_afters(app, action)\n run_hooks(afters, app, action)\n end", " def self.run_hooks(hooks, app, action)\n hooks.select { |p, _| !p || p =~ action.env[WebRouter::PATH_INFO] }\n .each { |_, b| action.instance_exec(action.env, app, &b) }\n end", " def self.befores\n @befores ||= []\n end", " def self.afters\n @afters ||= []\n end\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 5, 81], "buggy_code_start_loc": [5, 4, 71], "filenames": ["Changes.md", "lib/sidekiq/version.rb", "lib/sidekiq/web/application.rb"], "fixing_code_end_loc": [12, 5, 81], "fixing_code_start_loc": [5, 4, 71], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:contribsys:sidekiq:*:*:*:*:*:*:*:*", "matchCriteriaId": "5B32B98F-EEB2-4982-976A-BEC2ECE01909", "versionEndExcluding": "7.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0.4", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8."}], "evaluatorComment": null, "id": "CVE-2023-1892", "lastModified": "2023-06-09T18:07:41.737", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 8.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.6, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-21T05:15:07.057", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/e35e5653-c429-4fb8-94a3-cbc123ae4777"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, "type": "CWE-79"}
244
Determine whether the {function_name} code is vulnerable or not.
[ "# frozen_string_literal: true", "module Sidekiq\n class WebApplication\n extend WebRouter", " REDIS_KEYS = %w[redis_version uptime_in_days connected_clients used_memory_human used_memory_peak_human]\n CSP_HEADER = [\n \"default-src 'self' https: http:\",\n \"child-src 'self'\",\n \"connect-src 'self' https: http: wss: ws:\",\n \"font-src 'self' https: http:\",\n \"frame-src 'self'\",\n \"img-src 'self' https: http: data:\",\n \"manifest-src 'self'\",\n \"media-src 'self'\",\n \"object-src 'none'\",\n \"script-src 'self' https: http: 'unsafe-inline'\",\n \"style-src 'self' https: http: 'unsafe-inline'\",\n \"worker-src 'self'\",\n \"base-uri 'self'\"\n ].join(\"; \").freeze\n METRICS_PERIODS = {\n \"1h\" => 60,\n \"2h\" => 120,\n \"4h\" => 240,\n \"8h\" => 480\n }", " def initialize(klass)\n @klass = klass\n end", " def settings\n @klass.settings\n end", " def self.settings\n Sidekiq::Web.settings\n end", " def self.tabs\n Sidekiq::Web.tabs\n end", " def self.set(key, val)\n # nothing, backwards compatibility\n end", " head \"/\" do\n # HEAD / is the cheapest heartbeat possible,\n # it hits Redis to ensure connectivity\n Sidekiq.redis { |c| c.llen(\"queue:default\") }\n \"\"\n end", " get \"/\" do\n @redis_info = redis_info.select { |k, v| REDIS_KEYS.include? k }\n days = (params[\"days\"] || 30).to_i\n return halt(401) if days < 1 || days > 180", " stats_history = Sidekiq::Stats::History.new(days)\n @processed_history = stats_history.processed\n @failed_history = stats_history.failed", " erb(:dashboard)\n end", " get \"/metrics\" do\n q = Sidekiq::Metrics::Query.new", " @period = h((params[:period] || \"\")[0..1])", " @periods = METRICS_PERIODS\n minutes = @periods.fetch(@period, @periods.values.first)\n @query_result = q.top_jobs(minutes: minutes)\n erb(:metrics)\n end", " get \"/metrics/:name\" do\n @name = route_params[:name]", " @period = h((params[:period] || \"\")[0..1])", " q = Sidekiq::Metrics::Query.new\n @periods = METRICS_PERIODS\n minutes = @periods.fetch(@period, @periods.values.first)\n @query_result = q.for_job(@name, minutes: minutes)\n erb(:metrics_for_job)\n end", " get \"/busy\" do\n @count = (params[\"count\"] || 100).to_i\n (@current_page, @total_size, @workset) = page_items(workset, params[\"page\"], @count)", " erb(:busy)\n end", " post \"/busy\" do\n if params[\"identity\"]\n pro = Sidekiq::ProcessSet[params[\"identity\"]]", " pro.quiet! if params[\"quiet\"]\n pro.stop! if params[\"stop\"]\n else\n processes.each do |pro|\n next if pro.embedded?", " pro.quiet! if params[\"quiet\"]\n pro.stop! if params[\"stop\"]\n end\n end", " redirect \"#{root_path}busy\"\n end", " get \"/queues\" do\n @queues = Sidekiq::Queue.all", " erb(:queues)\n end", " QUEUE_NAME = /\\A[a-z_:.\\-0-9]+\\z/i", " get \"/queues/:name\" do\n @name = route_params[:name]", " halt(404) if !@name || @name !~ QUEUE_NAME", " @count = (params[\"count\"] || 25).to_i\n @queue = Sidekiq::Queue.new(@name)\n (@current_page, @total_size, @jobs) = page(\"queue:#{@name}\", params[\"page\"], @count, reverse: params[\"direction\"] == \"asc\")\n @jobs = @jobs.map { |msg| Sidekiq::JobRecord.new(msg, @name) }", " erb(:queue)\n end", " post \"/queues/:name\" do\n queue = Sidekiq::Queue.new(route_params[:name])", " if Sidekiq.pro? && params[\"pause\"]\n queue.pause!\n elsif Sidekiq.pro? && params[\"unpause\"]\n queue.unpause!\n else\n queue.clear\n end", " redirect \"#{root_path}queues\"\n end", " post \"/queues/:name/delete\" do\n name = route_params[:name]\n Sidekiq::JobRecord.new(params[\"key_val\"], name).delete", " redirect_with_query(\"#{root_path}queues/#{CGI.escape(name)}\")\n end", " get \"/morgue\" do\n @count = (params[\"count\"] || 25).to_i\n (@current_page, @total_size, @dead) = page(\"dead\", params[\"page\"], @count, reverse: true)\n @dead = @dead.map { |msg, score| Sidekiq::SortedEntry.new(nil, score, msg) }", " erb(:morgue)\n end", " get \"/morgue/:key\" do\n key = route_params[:key]\n halt(404) unless key", " @dead = Sidekiq::DeadSet.new.fetch(*parse_params(key)).first", " if @dead.nil?\n redirect \"#{root_path}morgue\"\n else\n erb(:dead)\n end\n end", " post \"/morgue\" do\n redirect(request.path) unless params[\"key\"]", " params[\"key\"].each do |key|\n job = Sidekiq::DeadSet.new.fetch(*parse_params(key)).first\n retry_or_delete_or_kill job, params if job\n end", " redirect_with_query(\"#{root_path}morgue\")\n end", " post \"/morgue/all/delete\" do\n Sidekiq::DeadSet.new.clear", " redirect \"#{root_path}morgue\"\n end", " post \"/morgue/all/retry\" do\n Sidekiq::DeadSet.new.retry_all", " redirect \"#{root_path}morgue\"\n end", " post \"/morgue/:key\" do\n key = route_params[:key]\n halt(404) unless key", " job = Sidekiq::DeadSet.new.fetch(*parse_params(key)).first\n retry_or_delete_or_kill job, params if job", " redirect_with_query(\"#{root_path}morgue\")\n end", " get \"/retries\" do\n @count = (params[\"count\"] || 25).to_i\n (@current_page, @total_size, @retries) = page(\"retry\", params[\"page\"], @count)\n @retries = @retries.map { |msg, score| Sidekiq::SortedEntry.new(nil, score, msg) }", " erb(:retries)\n end", " get \"/retries/:key\" do\n @retry = Sidekiq::RetrySet.new.fetch(*parse_params(route_params[:key])).first", " if @retry.nil?\n redirect \"#{root_path}retries\"\n else\n erb(:retry)\n end\n end", " post \"/retries\" do\n redirect(request.path) unless params[\"key\"]", " params[\"key\"].each do |key|\n job = Sidekiq::RetrySet.new.fetch(*parse_params(key)).first\n retry_or_delete_or_kill job, params if job\n end", " redirect_with_query(\"#{root_path}retries\")\n end", " post \"/retries/all/delete\" do\n Sidekiq::RetrySet.new.clear", " redirect \"#{root_path}retries\"\n end", " post \"/retries/all/retry\" do\n Sidekiq::RetrySet.new.retry_all", " redirect \"#{root_path}retries\"\n end", " post \"/retries/all/kill\" do\n Sidekiq::RetrySet.new.kill_all", " redirect \"#{root_path}retries\"\n end", " post \"/retries/:key\" do\n job = Sidekiq::RetrySet.new.fetch(*parse_params(route_params[:key])).first", " retry_or_delete_or_kill job, params if job", " redirect_with_query(\"#{root_path}retries\")\n end", " get \"/scheduled\" do\n @count = (params[\"count\"] || 25).to_i\n (@current_page, @total_size, @scheduled) = page(\"schedule\", params[\"page\"], @count)\n @scheduled = @scheduled.map { |msg, score| Sidekiq::SortedEntry.new(nil, score, msg) }", " erb(:scheduled)\n end", " get \"/scheduled/:key\" do\n @job = Sidekiq::ScheduledSet.new.fetch(*parse_params(route_params[:key])).first", " if @job.nil?\n redirect \"#{root_path}scheduled\"\n else\n erb(:scheduled_job_info)\n end\n end", " post \"/scheduled\" do\n redirect(request.path) unless params[\"key\"]", " params[\"key\"].each do |key|\n job = Sidekiq::ScheduledSet.new.fetch(*parse_params(key)).first\n delete_or_add_queue job, params if job\n end", " redirect_with_query(\"#{root_path}scheduled\")\n end", " post \"/scheduled/:key\" do\n key = route_params[:key]\n halt(404) unless key", " job = Sidekiq::ScheduledSet.new.fetch(*parse_params(key)).first\n delete_or_add_queue job, params if job", " redirect_with_query(\"#{root_path}scheduled\")\n end", " get \"/dashboard/stats\" do\n redirect \"#{root_path}stats\"\n end", " get \"/stats\" do\n sidekiq_stats = Sidekiq::Stats.new\n redis_stats = redis_info.select { |k, v| REDIS_KEYS.include? k }\n json(\n sidekiq: {\n processed: sidekiq_stats.processed,\n failed: sidekiq_stats.failed,\n busy: sidekiq_stats.workers_size,\n processes: sidekiq_stats.processes_size,\n enqueued: sidekiq_stats.enqueued,\n scheduled: sidekiq_stats.scheduled_size,\n retries: sidekiq_stats.retry_size,\n dead: sidekiq_stats.dead_size,\n default_latency: sidekiq_stats.default_queue_latency\n },\n redis: redis_stats,\n server_utc_time: server_utc_time\n )\n end", " get \"/stats/queues\" do\n json Sidekiq::Stats.new.queues\n end", " def call(env)\n action = self.class.match(env)\n return [404, {\"content-type\" => \"text/plain\", \"x-cascade\" => \"pass\"}, [\"Not Found\"]] unless action", " app = @klass\n resp = catch(:halt) do\n self.class.run_befores(app, action)\n action.instance_exec env, &action.block\n ensure\n self.class.run_afters(app, action)\n end", " case resp\n when Array\n # redirects go here\n resp\n else\n # rendered content goes here\n headers = {\n \"content-type\" => \"text/html\",\n \"cache-control\" => \"private, no-store\",\n \"content-language\" => action.locale,\n \"content-security-policy\" => CSP_HEADER\n }\n # we'll let Rack calculate Content-Length for us.\n [200, headers, [resp]]\n end\n end", " def self.helpers(mod = nil, &block)\n if block\n WebAction.class_eval(&block)\n else\n WebAction.send(:include, mod)\n end\n end", " def self.before(path = nil, &block)\n befores << [path && Regexp.new(\"\\\\A#{path.gsub(\"*\", \".*\")}\\\\z\"), block]\n end", " def self.after(path = nil, &block)\n afters << [path && Regexp.new(\"\\\\A#{path.gsub(\"*\", \".*\")}\\\\z\"), block]\n end", " def self.run_befores(app, action)\n run_hooks(befores, app, action)\n end", " def self.run_afters(app, action)\n run_hooks(afters, app, action)\n end", " def self.run_hooks(hooks, app, action)\n hooks.select { |p, _| !p || p =~ action.env[WebRouter::PATH_INFO] }\n .each { |_, b| action.instance_exec(action.env, app, &b) }\n end", " def self.befores\n @befores ||= []\n end", " def self.afters\n @afters ||= []\n end\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [9, 5, 81], "buggy_code_start_loc": [5, 4, 71], "filenames": ["Changes.md", "lib/sidekiq/version.rb", "lib/sidekiq/web/application.rb"], "fixing_code_end_loc": [12, 5, 81], "fixing_code_start_loc": [5, 4, 71], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:contribsys:sidekiq:*:*:*:*:*:*:*:*", "matchCriteriaId": "5B32B98F-EEB2-4982-976A-BEC2ECE01909", "versionEndExcluding": "7.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0.4", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository sidekiq/sidekiq prior to 7.0.8."}], "evaluatorComment": null, "id": "CVE-2023-1892", "lastModified": "2023-06-09T18:07:41.737", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 8.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.6, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-21T05:15:07.057", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/e35e5653-c429-4fb8-94a3-cbc123ae4777"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/sidekiq/sidekiq/commit/458fdf74176a9881478c48dc5cf0269107b22214"}, "type": "CWE-79"}
244
Determine whether the {function_name} code is vulnerable or not.
[ "Project: jackson-databind", "------------------------------------------------------------------------\n=== Releases ===\n------------------------------------------------------------------------", "2.6.7.2 (not yet released)", "", "#1737: Block more JDK types from polymorphic deserialization", "", "\n2.6.7.1 (11-Jul-2017)", "#1383: Problem with `@JsonCreator` with 1-arg factory-method, implicit param names\n#1599: Backport the extra safety checks for polymorphic deserialization", "2.6.7 (05-Jun-2016)", "#1194: Incorrect signature for generic type via `JavaType.getGenericSignature\n#1228: @JsonAnySetter does not deserialize null to Deserializer's NullValue\n (contributed by Eric S)", "2.6.6 (05-Apr-2016)", "#1088: NPE possibility in SimpleMixinResolver\n (reported by Laird N)\n#1099: Fix custom comparator container node traversal\n (contributed by Daniel N)\n#1108: Jackson not continue to parse after DeserializationFeature.FAIL_ON_INVALID_SUBTYPE error\n (reported by jefferyyuan@github)\n#1112: Detailed error message from custom key deserializer is discarded\n (contributed by Benson M)\n#1120: String value omitted from weirdStringException\n (reported by Benson M)\n#1123: Serializing and Deserializing Locale.ROOT\n (reported by hookumsnivy@github)", "2.6.5 (19-Jan-2016)", "#1052: Don't generate a spurious NullNode after parsing an embedded object\n (reported by philipa@github)\n#1061: Problem with Object Id and Type Id as Wrapper Object (regression in 2.5.1)\n#1073: Add try-catch around `java.sql` type serializers\n (suggested by claudemt@github)\n#1078: ObjectMapper.copy() still does not preserve _registeredModuleTypes\n (reported by ajonkisz@github)", "2.6.4 (07-Dec-2015)", "#984: JsonStreamContexts are not build the same way for write.. and convert methods\n (reported by Antibrumm@github)\n#989: Deserialization from \"{}\" to java.lang.Object causes \"out of END_OBJECT token\" error\n (reported by Ievgen P)\n#1003: JsonTypeInfo.As.EXTERNAL_PROPERTY does not work with a Delegate\n (reported by alexwen@github)\n#1005: Synthetic constructors confusing Jackson data binding\n (reported by Jayson M)\n#1013: `@JsonUnwrapped` is not treated as assuming `@JsonProperty(\"\")`\n (reported by David B)\n#1036: Problem with case-insensitive deserialization\n (repoted by Dmitry R)\n- Fix a minor problem with `@JsonNaming` not recognizing default value", "2.6.3 (12-Oct-2015)", "#749: `EnumMap` serialization ignores `SerializationFeature.WRITE_ENUMS_USING_TO_STRING`\n (reported by scubasau@github)\n#938: Regression: `StackOverflowError` with recursive types that contain `Map.Entry`\n (reported by jloisel@github)\n#939: Regression: DateConversionError in 2.6.x \n (reported by Andreas P, anpieber@github)\n#940: Add missing `hashCode()` implementations for `JsonNode` types that did not have them\n (contributed by Sergio M)\n#941: Deserialization from \"{}\" to ObjectNode field causes \"out of END_OBJECT token\" error\n (reported by Sadayuki F)\n#942: Handle null type id for polymorphic values that use external type id\n (reported by Warren B, stormboy@github)\n#943: Incorrect serialization of enum map key\n (reported by Benson M)\n#944: Failure to use custom deserializer for key deserializer\n (contributed by Benson M)\n#949: Report the offending substring when number parsing fails\n (contributed by Jesse W)\n#965: BigDecimal values via @JsonTypeInfo/@JsonSubTypes get rounded\n (reported by gmjabs@github)", "2.6.2 (14-Sep-2015)", "#894: When using withFactory on ObjectMapper, the created Factory has a TypeParser\n which still has the original Factory\n (reported by lufe66@github)\n#899: Problem serializing `ObjectReader` (and possibly `ObjectMapper`)\n#913: ObjectMapper.copy does not preserve MappingJsonFactory features\n (reported, fixed by Daniel W)\n#922: ObjectMapper.copy() does not preserve _registeredModuleTypes\n#928: Problem deserializing External Type Id if type id comes before POJO", "2.6.1 (09-Aug-2015)", "#873: Add missing OSGi import\n#881: BeanDeserializerBase having issues with non-CreatorProperty properties.\n (reported by dharaburda@github)\n#884: ArrayIndexOutOfBoundException for `BeanPropertyMap` (with ObjectId)\n (reported by alterGauner@github)\n#889: Configuring an ObjectMapper's DateFormat changes time zone\n (reported by Andy W, wilkinsona@github)\n#890: Exception deserializing a byte[] when the target type comes from an annotation\n (reported by gmjabs@github)", "2.6.0 (19-Jul-2015)", "#77: Allow injection of 'transient' fields\n#95: Allow read-only properties with `@JsonIgnoreProperties(allowGetters=true)`\n#222: EXTERNAL_PROPERTY adds property multiple times and in multiple places\n (reported by Rob E, thatsnotright@github)\n#296: Serialization of transient fields with public getters (add\n MapperFeature.PROPAGATE_TRANSIENT_MARKER)\n (suggested by Michal L)\n#312: Support Type Id mappings where two ids map to same Class\n#348: ObjectMapper.valueToTree does not work with @JsonRawValue\n (reported by Chris P, pimlottc@github)\n#504: Add `DeserializationFeature.USE_LONG_FOR_INTS`\n (suggested by Jeff S)\n#624: Allow setting external `ClassLoader` to use, via `TypeFactory`\n#649: Make `BeanDeserializer` use new `parser.nextFieldName()` and `.hasTokenId()` methods\n#664: Add `DeserializationFeature.ACCEPT_FLOAT_AS_INT` to prevent coercion of floating point\n numbers int `int`/`long`/`Integer`/`Long`\n (requested by wenzis@github)\n#677: Specifying `Enum` value serialization using `@JsonProperty`\n (requested by Allen C, allenchen1154@github)\n#679: Add `isEmpty()` implementation for `JsonNode` serializers\n#688: Provide a means for an ObjectMapper to discover mixin annotation classes on demand\n (requested by Laird N)\n#689: Add `ObjectMapper.setDefaultPrettyPrinter(PrettyPrinter)`\n (requested by derknorton@github)\n#696: Copy constructor does not preserve `_injectableValues`\n (reported by Charles A)\n#698: Add support for referential types (ReferenceType)\n#700: Cannot Change Default Abstract Type Mapper from LinkedHashMap\n (reported by wealdtech@github)\n#725: Auto-detect multi-argument constructor with implicit names if it is the only visible creator\n#727: Improve `ObjectWriter.forType()` to avoid forcing base type for container types\n#734: Add basic error-recovery for `ObjectReader.readValues()`\n#737: Add support for writing raw values in TokenBuffer\n (suggested by Guillaume S, gsmet@github)\n#740: Ensure proper `null` (as empty) handling for `AtomicReference`\n#741: Pass `DeserializationContext' argument for `JsonDeserializer` methods \"getNullValue()\"\n and \"getEmptyValue()\"\n#743: Add `RawValue` helper type, for piping raw values through `TokenBuffer`\n#756: Disabling SerializationFeature.FAIL_ON_EMPTY_BEANS does not affect `canSerialize()`\n (reported by nickwongdev@github)\n#762: Add `ObjectWriter.withoutRootName()`, `ObjectReader.withoutRootName()`\n#765: `SimpleType.withStaticTyping()` impl incorrect\n#769: Fix `JacksonAnnotationIntrospector.findDeserializer` to return `Object` (as per\n `AnnotationIntrospector`); similarly for other `findXxx(De)Serializer(...)` methods\n#777: Allow missing build method if its name is empty (\"\")\n (suggested by galdosd@github)\n#781: Support handling of `@JsonProperty.required` for Creator methods\n#787: Add `ObjectMapper setFilterProvider(FilterProvider)` to allow chaining\n (suggested by rgoldberg@githin)\n#790: Add `JsonNode.equals(Comparator<JsonNode>, JsonNode)` to support\n configurable/external equality comparison\n#794: Add `SerializationFeature.WRITE_DATES_WITH_ZONE_ID` to allow inclusion/exclusion of\n timezone id for date/time values (as opposed to timezone offset)\n#795: Converter annotation not honored for abstract types\n (reported by myrosia@github)\n#797: `JsonNodeFactory` method `numberNode(long)` produces `IntNode` for small numbers\n#810: Force value coercion for `java.util.Properties`, so that values are `String`s\n#811: Add new option, `JsonInclude.Include.NON_ABSENT` (to support exclusion of\n JDK8/Guava Optionals)\n#812: Java 8 breaks Class-value annotation properties, wrt generics: need to work around\n#813: Add support for new property of `@JsonProperty.access` to support\n read-only/write-only use cases\n#820: Add new method for `ObjectReader`, to bind from JSON Pointer position\n (contributed by Jerry Y, islanderman@github)\n#824: Contextual `TimeZone` changes don't take effect wrt `java.util.Date`,\n `java.util.Calendar` serialization\n#826: Replaced synchronized HashMap with ConcurrentHashMap in TypeDeserializerBase._findDeserializer\n (contributed by Lars P)\n#827: Fix for polymorphic custom map key serializer\n (reported by mjr6140@gitgub)\n#828: Respect DeserializationFeatures.WRAP_EXCEPTIONS in CollectionDeserializer\n (contributed by Steve G, thezerobit@github)\n#840: Change semantics of `@JsonPropertyOrder(alphabetic)` to only count `true` value\n#848: Custom serializer not used if POJO has `@JsonValue`\n#849: Possible problem with `NON_EMPTY` exclusion, `int`s, `Strings`\n#868: Annotations are lost in the case of duplicate methods\n- Remove old cglib compatibility tests; cause problems in Eclipse\n- Add `withFilterId()` method in `JsonSerializer` (demote from `BeanSerializer`)", "2.5.5 (07-Dec-2015)", "#844: Using JsonCreator still causes invalid path references in JsonMappingException\n (reported by Ian B)\n#852: Accept scientific number notation for quoted numbers too\n#878: serializeWithType on BeanSerializer does not setCurrentValue\n (reported by Chi K, chikim79@github)", "2.5.4 (09-Jun-2015)", "#676: Deserialization of class with generic collection inside depends on\n how is was deserialized first time\n (reported by lunaticare@github)\n#771: Annotation bundles ignored when added to Mixin\n (reported by Andrew D)\n#774: NPE from SqlDateSerializer as _useTimestamp is not checked for being null\n (reported by mrowkow@github)\n#785: Add handlings for classes which are available in `Thread.currentThread().getContextClassLoader()`\n (contributed by Charles A)\n#792: Ensure Constructor Parameter annotations are linked with those of Field, Getter, or Setter\n#793: `ObjectMapper.readTree()` does not work with defaultTyping enabled\n (reported by gracefulgopher@github)\n#801: Using `@JsonCreator` cause generating invalid path reference in `JsonMappingException`\n (contributed by Kamil B)\n#815: Presence of PropertyNamingStrategy Makes Deserialization fail\n#816: Allow date-only ISO strings to have no time zone\n (contributed by Andrew G)\n- Fix handling of Enums wrt JSON Schema, when 'toString()' used for serialization", "2.5.3 (24-Apr-2015)", "#731: XmlAdapter result marshaling error in case of ValueType=Object\n (reported, debugged by Dmitry S)\n#742: Allow deserialization of `null` Object Id (missing already allowed)\n#744: Custom deserializer with parent object update failing\n (reported by migel@github)\n#745: EnumDeserializer.deserializerForCreator fails when used to deserialize a Map key\n (contributed by John M)\n#761: Builder deserializer: in-compatible type exception when return type is super type\n (contributed by Alexey G)\n#766: Fix Infinite recursion (StackOverflowError) when serializing a SOAP object\n (contributed by Alain G)", "2.5.2 (29-Mar-2015)", "#609: Problem resolving locally declared generic type\n (repoted by Hal H)\n#691: NullSerializer for MapProperty failing when using polymorphic handling\n (reported by Antibrumm@github)\n#703: Multiple calls to ObjectMapper#canSerialize(Object.class) returns different values\n (reported by flexfrank@github)\n#705: JsonAnyGetter doesn't work with JsonSerialize (except with keyUsing)\n (reported by natnan@github)\n#728: TypeFactory#_fromVariable returns unknownType() even though it has enough information\n to provide a more specific type\n (reported by jkochaniak@github)\n#733: MappingIterator should move past errors or not return hasNext() == true\n (reported by Lorrin N, lorrin@github)\n#738: @JsonTypeInfo non-deterministically ignored in 2.5.1 (concurrency issue)\n (reported by Dylan S, dylanscott@github)\n- Improvement to handling of custom `ValueInstantiator` for delegating mode; no more NPE\n if `getDelegateCreator()` returns null\n- Refactor `TypedKey` into separate util class", "2.5.1 (06-Feb-2015)", "#667: Problem with bogus conflict between single-arg-String vs `CharSequence` constructor\n#669: JSOG usage of @JsonTypeInfo and @JsonIdentityInfo(generator=JSOGGenerator.class) fails\n (reported by ericali78@github)\n#671: Adding `java.util.Currency` deserialization support for maps\n (contributed by Alexandre S-C)\n#674: Spring CGLIB proxies not handled as intended\n (reported by Zoltan F)\n#682: Class<?>-valued Map keys not serialized properly\n (reported by Ludevik@github)\n#684: FAIL_ON_NUMBERS_FOR_ENUMS does not fail when integer value is quoted\n (reported by kllp@github)\n#696: Copy constructor does not preserve `_injectableValues`\n (reported by Charles A)\n- Add a work-around in `ISO8601DateFormat` to allow omission of ':' from timezone\n- Bit more work to complete #633", "2.5.0 (01-Jan-2015)", "#47: Support `@JsonValue` for (Map) key serialization \n#113: Problem deserializing polymorphic types with @JsonCreator\n#165: Add `DeserializationContext.getContextualType()` to let deserializer\n known the expected type.\n#299: Add `DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS` to allow missing\n Object Ids (as global default)\n#408: External type id does not allow use of 'visible=true'\n#421: @JsonCreator not used in case of multiple creators with parameter names\n (reported by Lovro P, lpandzic@github)\n#427: Make array and Collection serializers call `JsonGenerator.writeStartArray(int)`\n#521: Keep bundle annotations, prevent problems with recursive annotation types\n (reported by tea-dragon@github)\n#527: Add support for `@JsonInclude(content=Include.NON_NULL)` (and others) for Maps\n#528: Add support for `JsonType.As.EXISTING_PROPERTY`\n (reported by heapifyman@github; implemented by fleebytes@github)\n#539: Problem with post-procesing of \"empty bean\" serializer; was not calling\n 'BeanSerializerModifier.modifySerializer()` for empty beans\n (reported by Fabien R, fabienrenaud@github)\n#540: Support deserializing `[]` as null or empty collection when the java type\n is a not an object, `DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT`\n (requested by Fabien R, fabienrenaud@github)\n#543: Problem resolving self-referential recursive types\n (reported by ahgittin@github)\n#550: Minor optimization: prune introspection of \"well-known\" JDK types\n#552: Improved handling for ISO-8601 (date) format\n (contributed by Jerome G, geronimo-iia@github)\n#559: Add `getDateFormat()`, `getPropertyNamingStrategy()` in `ObjectMapper`\n#560: @JsonCreator to deserialize BigInteger to Enum\n (requested by gisupp@github)\n#565: Add support for handling `Map.Entry`\n#566: Add support for case-insensitive deserialization (`MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES`)\n (contributed by Michael R)\n#571: Add support in ObjectMapper for custom `ObjectReader`, `ObjectWriter` (sub-classes)\n#572: Override default serialization of Enums\n (requested by herau@github)\n#576: Add fluent API for adding mixins\n (contributed by Adam S, adstro@github)\n#594: `@JsonValue` on enum not used when enum value is a Map key\n (reported by chrylis@github)\n#596: Add support for `@JsonProperty.defaultValue`, exposed via `BeanProperty.getMetadata().getDefaultValue()`\n#597: Improve error messaging for cases where JSON Creator returns null (which\n is illegal)\n (contributed by Aurelien L)\n#599: Add a simple mechanism for avoiding multiple registrations of the same module\n#607: Allow (re)config of `JsonParser.Feature`s via `ObjectReader`\n#608: Allow (re)config of `JsonGenerator.Feature`s via `ObjectWriter`\n#614: Add a mechanism for using `@JsonCreator.mode` for resolving possible ambiguity between\n delegating- and property-based creators\n#616: Add `SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS`\n#622: Support for non-scalar ObjectId Reference deserialiazation (like JSOG)\n#623: Add `StdNodeBasedDeserializer`\n#630: Add `KeyDeserializer` for `Class`\n#631: Update `current value` of `JsonParser`, `JsonGenerator` from standard serializers,\n deserializers\n (suggested by Antibrumm@github)\n#633: Allow returning null value from IdResolver to make type information optional\n (requested by Antibrumm@github)\n#634: Add `typeFromId(DatabindContext,String)` in `TypeIdDeserializer`\n#636: `ClassNotFoundException` for classes not (yet) needed during serialization\n (contributed by mspiegel@github)\n#638: Add annotation-based method(s) for injecting properties during serialization\n (using @JsonAppend, VirtualBeanPropertyWriter)\n#647: Deserialization fails when @JsonUnwrapped property contains an object with same property name\n (reported by Konstantin L)\n#653: Jackson doesn't follow JavaBean naming convention (added `MapperFeature.USE_STD_BEAN_NAMING`)\n#654: Add support for (re)configuring `JsonGenerator.setRootValueSeparator()` via `ObjectWriter`\n#655: Add `ObjectWriter.writeValues()` for writing value sequences\n#660: `@JsonCreator`-annotated factory method is ignored if constructor exists\n- Allow use of `Shape.ARRAY` for Enums, as an alias to 'use index'\n- Start using `JsonGenerator.writeStartArray(int)` to help data formats\n that benefit from knowing number of elements in arrays (and would otherwise\n need to buffer values to know length)\n- Added new overload for `JsonSerializer.isEmpty()`, to eventually solve #588\n- Improve error messaging (related to [jaxb-annotations#38]) to include known subtype ids.", "2.4.6 (23-Apr-2015)", "#735: (complete fix) @JsonDeserialize on Map with contentUsing custom deserializer overwrites default behavior\n (reported by blackfyre512@github) (regression due to #604)\n$744: Custom deserializer with parent object update fails", "2.4.5.1 (26-Mar-2015)", "Special one-off \"micro patch\" for:", "#706: Add support for `@JsonUnwrapped` via JSON Schema module\n#707: Error in getting string representation of an ObjectNode with a float number value\n (reported by @navidqar)\n#735: (partial) @JsonDeserialize on Map with contentUsing custom deserializer overwrites default behavior", "2.4.5 (13-Jan-2015)", "#635: Reduce cachability of `Map` deserializers, to avoid problems with per-property config changes\n (regression due to #604)\n#656: `defaultImpl` configuration is ignored for `WRAPPER_OBJECT`\n- Solve potential cyclic-resolution problem for `UntypedObjectDeserializer`", "2.4.4 (24-Nov-2014)", "(jackson-core)#158: Setter confusion on assignable types\n (reported by tsquared2763@github)\n#245: Calls to ObjectMapper.addMixInAnnotations() on an instance returned by ObjectMapper.copy()\n don't work\n (reported by Erik D)\n#580: delegate deserializers choke on a (single) abstract/polymorphic parameter\n (reported by Ian B, tea-dragon@github)\n#590: Binding invalid Currency gives nonsense at end of the message\n (reported by Jerbell@github)\n#592: Wrong `TokenBuffer` delegate deserialization using `@JsonCreator`\n (reported by Eugene L)\n#601: ClassCastException for a custom serializer for enum key in `EnumMap`\n (reported by Benson M)\n#604: `Map` deserializers not being cached, causing performance problems\n#610: Fix forward reference in hierarchies\n (contributed by zeito@github)\n#619: Off by one error in AnnotatedWithParams\n (reported by stevetodd@github)\n- Minor fix to `EnumSerializer` regarding detection \"serialize using index\"\n- Minor fix to number serializers, to call proper callback for schema generation", "2.4.3 (02-Oct-2014)", "#496: Wrong result with `new TextNode(\"false\").asBoolean(true)`\n (reported by Ivar R, ivarru@github)\n#511: DeserializationFeature.FAIL_ON_INVALID_SUBTYPE does not work\n (reported by sbelikov@github)\n#523: MapDeserializer and friends do not report the field/key name for mapping exceptions\n (reported by Ian B, tea-dragon@github)\n#524: @JsonIdentityReference(alwaysAsId = true) Custom resolver is reset to SimpleObjectIdResolver\n (reported by pkokorev@github)\n#541: @JsonProperty in @JsonCreator is conflicting with POJOs getters/attributes\n (reported by fabienrenaud@github)\n#543: Problem resolving self-referential generic types\n#570: Add Support for Parsing All Compliant ISO-8601 Date Formats\n (requested by pfconrey@github)\n- Fixed a problem with `acceptJsonFormatVisitor` with Collection/array types that\n are marked with `@JsonValue`; could cause NPE in JSON Schema generator module.", "2.4.2 (14-Aug-2014)", "#515: Mixin annotations lost when using a mixin class hierarchy with non-mixin interfaces\n (reported by 'stevebread@github')\n- Fixed a problem related to [jackson-dataformat-smile#19].", "2.4.1.2 (12-Jul-2014)", "Special one-off \"micro patch\" for:", "#503: Concurrency issue inside com.fasterxml.jackson.databind.util.LRUMap.get(Object)\n (reported by fjtc@github)", "2.4.1.1 (18-Jun-2014)", "Special one-off \"micro patch\" for:", "#491: Temporary work-around for issue #490 (full fix for 2.5 needs to be\n in `jackson-annotations`)\n#506: Index is never set for Collection and Array in InvalidFormatException.Reference\n (reported by Fabrice D, fabdouglas@github)\n- Fixed a problem related to [jackson-dataformat-smile#19].", "2.4.1 (17-Jun-2014)", "#479: NPE on trying to deserialize a `String[]` that contains null\n (reported by huxi@github)\n#482: Make date parsing error behavior consistent with JDK\n (suggested by Steve S, sanbeg@github)\n#489 (partial): TypeFactory cache prevents garbage collection of custom ClassLoader\n (reported by sftwrengnr@github)", "2.4.0 (02-Jun-2014)", "#81: Allow use of @JsonUnwrapped with typed (@JsonTypeInfo) classes, provided\n that (new) feature `SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS`\n is disabled\n (constributed by Ben F, UnquietCode@github)\n#88: Prevent use of type information for `JsonNode` via default typing\n (reported by electricmonk@github)\n#149: Allow use of \"stringified\" indexes for Enum values\n (requested by chenboxiang@github)\n#176: Allow use external Object Id resolver (to use with @JsonIdentityInfo etc)\n (implemented by Pascal G)\n#193: Conflicting property name definitions\n (reported by Stuart J, sgjohnston@github)\n#323: Serialization of the field with deserialization config\n (reported by metanet@github)\n#327: Should not consider explicitly differing renames a fail, as long as all are explicit\n#335: Allow use of `@JsonPropertyOrder(alphabetic=true)` for Map properties\n#352 Add `ObjectMapper.setConfig()` for overriding `SerializationConfig`/`DeserializationConfig`\n#353: Problems with polymorphic types, `JsonNode` (related to #88)\n (reported by cemo@github)\n#359: Converted object not using explicitly annotated serializer\n (reported by Florian S [fschopp@github])\n#369: Incorrect comparison for renaming in `POJOPropertyBuilder`\n#375: Add `readValue()`/`readPropertyValue()` methods in `DeserializationContext`\n#376: Add support for `@JsonFormat(shape=STRING)` for number serializers\n#381: Allow inlining/unwrapping of value from single-component JSON array\n (contributed by yinzara@github)\n#390: Change order in which managed/back references are resolved (now back-ref\n first, then forward)\n (requested by zAlbee@github)\n#407: Properly use null handlers for value types when serializer Collection\n and array types\n (contributed by Will P)\n#425: Add support for using `Void.class` as \"no class\", instead of `NoClass.class`\n#428: `PropertyNamingStrategy` will rename even explicit name from `@JsonProperty`\n (reported by turskip@github)\n#435: Performance bottleneck in TypeFactory._fromClass\n (reported by Sean D, sdonovanuk@github)\n#434: Ensure that DecimalNodes with mathematically equal values are equal\n (contributed by Francis G)\n#435: Performance bottleneck in TypeFactory._fromClass\n (reported by sdonovanuk@github)\n#438: Add support for accessing `@JsonProperty(index=N)` annotations\n#442: Make `@JsonUnwrapped` indicate property inclusion\n (suggested by Ben F)\n#447: ArrayNode#addAll should accept Collection<? extends JsonNode>\n (suggested by alias@github)\n#461: Add new standard naming strategy, `PropertyNamingStrategy.LowerCaseStrategy`\n#463: Add 'JsonNode.asText(String defaultValue)`\n (suggested by Chris C)\n#464: Include `JsonLocation` in more mapping exceptions\n (contributed by Andy C (q3aiml@github))\n#465: Make it easier to support serialization of custom subtypes of `Number`\n#467: Unwanted POJO's embedded in tree via serialization to tree\n (reported by Benson M)\n- Slightly improve `SqlDateSerializer` to support `@JsonFormat`\n- Improve handling of native type ids (YAML, CBOR) to use non-native type ids\n as fallback", "2.3.5 (13-Jan-2015)", "#496: Wrong result for TextNode(\"false\").asBoolean(true)\n (reported by Ivar R, ivarru@github)\n#543: Problems resolving self-referential generic types.\n#656: defaultImpl configuration is ignored for WRAPPER_OBJECT", "2.3.4 (17-Jul-2014)", "#459: BeanDeserializerBuilder copy constructor not copying `_injectables`\n#462: Annotation-provided Deserializers are not contextualized inside CreatorProperties\n (reported by aarondav@github)", "2.3.3 (10-Apr-2014)", "#420: Remove 'final' modifier from `BeanDeserializerBase.deserializeWithType`\n (requested by Ghoughpteighbteau@github)\n#422: Allow use of \"True\" and \"False\" as aliases for booleans when coercing from\n JSON String\n#423: Fix `CalendarSerializer` to work with custom format\n (reported by sergeymetallic@github)\n#433: `ObjectMapper`'s `.valueToTree()` wraps `JsonSerializable` objects into a POJONode\n (reported by Francis G)\n- Fix null-handling for `CollectionSerializer`", "2.3.2 (01-Mar-2014)", "#378: Fix a problem with custom enum deserializer construction\n (reported by BokoEnos@github)\n#379: Fix a problem with (re)naming of Creator properties; needed to make\n Paranamer module work with NamingStrategy.\n (reported by Chris P, cpilsworth@github)\n#398: Should deserialize empty (not null) URI from empty String\n (reported by pgieser@github)\n#406: @JsonTypeIdResolver not working with external type ids\n (reported by Martin T)\n#411: NumberDeserializers throws exception with NaN and +/- Infinity\n (reported by clarkbreyman@github)\n#412: ObjectMapper.writerWithType() does not change root name being used\n (repoted by jhalterman@github)\n- Added `BeanSerializerBase._serializeObjectId()` needed by modules that\n override standard BeanSerializer; specifically, XML module.", "2.3.1 (28-Dec-2013)", "#346: Fix problem deserializing `ObjectNode`, with @JsonCreator, empty\n JSON Object\n (reported by gaff78@github)\n#358: `IterableSerializer` ignoring annotated content serializer\n (reported by Florian S)\n#361: Reduce sync overhead for SerializerCache by using volatile, double-locking\n (contributed by stuartwdouglas@github)\n#362: UUID output as Base64 String with ObjectMapper.convertValue()\n (reported by jknack@github)\n#367: Make `TypeNameIdResolver` call `TypeResolver` for resolving base type\n (suggested by Ben F)\n#370: Fail to add Object Id for POJO with no properties\n (reported by jh3141@github)\n- Fix for [jackson-module-afterburner#38]: need to remove @JacksonStdImpl from\n `RawSerializer`, to avoid accidental removal of proper handling.", "2.3.0 (13-Nov-2013)", "#48: Add support for `InetSocketAddress`\n (contributed by Nick T)\n#152: Add support for traversing `JsonNode` with (new!) `JsonPointer` implementation\n (suggested by fge@github)\n#208: Accept \"fromString()\" as an implicit Creator (factory) method (alias for \"valueOf()\")\n (requested by David P)\n#215: Allow registering custom `CharacterEscapes` to use for serialization,\n via `ObjectWriter.with(CharacterEscapes)` (and `ObjectMapper.writer(CharacterEscapes)`)\n#227: Allow \"generic\" Enum serializers, deserializers, via `SimpleModule`\n#234: Incorrect type information for deeply nested Maps\n (reported by Andrei P)\n#237: Add `DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY` to optionally\n throw `JsonMappingException` on duplicate keys, tree model (`JsonNode`)\n#238: Allow existence of overlapping getter, is-getter (choose 'regular' getter)\n#239: Support `ByteBuffer`\n (suggested by mckamey@github)\n#240: Make sure `@JsonSerialize.include` does not accidentally override\n class inclusion settings\n (requested by thierryhenrio@github)\n#253: `DelegatingDeserializer` causes problems for Managed/BackReferences\n (reported by bfelaco@github)\n#257: Make `UntypedObjectDeserializer` support overides for `List`, `Map` etc\n#268: Add new variant of `ObjectMapper.canSerialize()` that can return `Throwable`\n that caused false to be returned (if any)\n#269: Add support for new `@JsonPropertyDescription` via `AnnotationIntrospector`\n as well as `BeanProperty.getMedata().getDescription()`\n#270: Add `SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID` to allow use of equality\n (instead of identity) for figuring out when to use Object Id\n (requested by beku8@github)\n#271: Support handling of `@JsonUnwrapped` for in-built JSON Schema generation\n#277: Make `TokenBuffer` support new native type and object ids\n#302: Add `setNamingStrategy` in `Module.SetupContext`\n (suggested by Miguel C)\n#305: Add support for accessing `TypeFactory` via `TypeIdResolverBase`\n (not yet via `TypeIdResolver` interface), other configuration\n#306: Allow use of `@JsonFilter` for properties, not just classes \n#307: Allow use of `@JsonFilter` for Maps in addition to POJOs\n#308: Improve serialization and deserialization speed of `java.util.UUID` by 4x\n (suggested by David P)\n#310: Improve `java.util.UUID` serialization with binary codecs, to use \"raw\" form.\n#311: Make sure that \"creator properties\" are alphabetically ordered too, if\n so requested.\n#315: Allow per-property definition of null serializer to use, using\n new `@JsonSerialize(nullsUsing=xxx)` annotation property\n#317: Fix `JsonNode` support for nulls bound to `ObjectNode`, `ArrayNode`\n (contributed by Seth P)\n#318: Problems with `ObjectMapper.updateValue()`, creator property-backed accessors\n#319: Add support for per-call (\"contextual\") attributes, with defaulting,\n to allow keeping track of state during (de)serialization\n#324: Make sure to throw `JsonMappingException` from `EnumDeserializer` creator,\n not `IllegalArgumentException`\n (reported by beverku@github)\n#326: Support `@JsonFilter` for \"any getter\" properties\n#334: Make `ArrayNode`, `ObjectNode` non-final again\n#337: `AnySetter` does not support polymorphic types\n (reported by askvortsov@github)\n#340: AtomicReference not working with polymorphic types\n#342: Add `DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES` to make `ObjectMapper`\n throw exception when encountering explicitly ignored properties\n (requested by Ruslan M)\n[JACKSON-890]: Support managed/back-references for polymorphic (abstract) types\n- Add 'BeanPropertyWriter.isUnwrapping()' for future needs (by Afterburner)\n- Add coercions from String \"null\" (as if null token was parsed) for primitives/Wrappers.\n- Add `JsonDeserializer.handledType()`", "2.2.4 (10-Jun-2014)", "#292: Problems with abstract `Map`s, `Collection`s, polymorphic deserialization\n#324: EnumDeserializer should throw JsonMappingException, not IllegalArgumentException\n#346: Problems deserializing `ObjectNode` from empty JSON Object, with @JsonCreator", "2.2.3 (22-Aug-2013)", "#234: Problems with serializing types for deeply nested generic Maps, default typing \n#251: SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN ignored with JsonNode\n serialization\n (reported by fge@github)\n#259: Fix a problem with JSON Schema generation for `@JsonValue`\n (reported by Lior L)\n#267: Handle negative, stringified timestamps\n (reported by Drecth@github)\n#281: Make `NullNode` use configured null-value serializer\n#287: Fix problems with converters, Maps with Object values\n (reported by antubis@github)\n#288: Fix problem with serialization converters assigned with annotations\n (reported by cemo@github)", "2.2.2 (26-May-2013)", "#216: Problems with Android, 1.6-only types\n#217: JsonProcessingExceptions not all wrapped as expected\n (reported by karldmoore@github)\n#220: ContainerNode missing 'createNumber(BigInteger)'\n (reported by Pascal G)\n#223: Duplicated nulls with @JsonFormat(shape=Shape.ARRAY)\n (reported by lukegh@github)\n#226: Field mapping fail on deserialization to common referenced object when\n @JsonUnwrapped is used\n (reported by ikvia@github)\n#232: Converting bound BigDecimal value to tree fails with WRITE_BIGDECIMAL_AS_PLAIN\n (reported by celkings@github)\n- Minor fix to handle primitive types for key deserializer lookups\n- Add convenience method `MappingIterator.getCurrentLocation()`\n (suggested by Tomdz@github)", "2.2.1 (03-May-2013)", "#214: Problem with LICENSE, NOTICE, Android packaging\n (reported by thierryd@github)", "2.2.0 (22-Apr-2013)", "Fixes:", "#23: Fixing typing of root-level collections\n#118: JsonTypeInfo.as.EXTERNAL_PROPERTY not working correctly\n with missing type id, scalar types\n#130: TimeZone not set for GregorianCalendar, even if configured\n#144: MissingNode.isValueNode() should return 'false'\n (reported by 'fge@github')\n#146: Creator properties were not being renamed as expected\n (contributed by Christoper C)\n#188: Problem with ObjectId serialization, 'alwaysAsId' references", "Improvements:", "#116: JavaType implements `java.lang.reflect.Type` (as does `TypeReference`)\n#147: Defer reporting of problems with missing creator parameters\n (contributed by Christoper C)\n#155: Make `ObjectNode` and `ArrayNode` final (other node types already were)\n (requested by fge@github)\n#161: Add deserializer for java.util.concurrent.ArrayBlockingQueue\n#173: Add 'JsonNode.traverse(ObjectCodec)' for convenience\n#181: Improve error reporting for missing '_valueDeserializer'\n#194: Add `FloatNode` type in tree model (JsonNode)\n (requested by msteiger@github)\n#199: Allow deserializing `Iterable` instances (as basic `Collection`s)\n (requested by electrum@github)\n#206: Make 'ObjectMapper.createDeserializationContext()' overridable\n (requested by noter@github)\n#207: Add explicit support for `short` datatypes, for tree model\n (contributed by msteiger@github)", "New features:", "#120: Extend BeanDeserializerModifier to work with non-POJO deserializers\n#121: Extend BeanSerializerModifier to work with non-POJO serializers\n#124: Add support for serialization converters (@JsonSerializer(converter=...))\n#124: Add support for deserialization converters (@JsonDeserializer(converter=...))\n#140: Add 'SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN' to allow forcing\n of non-scientific notation when serializing BigDecimals.\n (suggested by phedny@github)\n#148: Add 'DeserializationFeature.FAIL_ON_INVALID_SUBTYPE`, which allows mapping\n entries with missing or invalid type id into null references (instead of failing).\n Also allows use of '@JsonTypeInfo.defaultImpl = NoClass.class' as alternative.\n#159: Add more accessors in 'MappingIterator': getParser(), getParserSchema(),\n readAll()\n (suggested by Tom D)\n#190: Add 'MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS' (default: true) for\n pruning out final fields (to avoid using as mutators)\n (requested by Eric T)\n#195: Add 'MapperFeature.INFER_PROPERTY_MUTATORS' (default: enabled) for finer\n control of what mutators are auto-detected.\n (requested by Dain S)\n#198: Add SPI metadata, handling in ObjectMapper (findModules()), for\n automatic registration of auto-detected extension modules\n (suggested by 'beamerblvd@github')\n#203: Added new features to support advanced date/time handling:\n - SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS\n - DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS\n - DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE", "Other:", "#126: Update JDK baseline to 1.6\n* API under 'com.fasterxml.jackson.databind.jsonFormatVisitors' changed significantly\n based on experiences with external JSON Schema generator.\n* Version information accessed via code-generated access class, instead of reading\n VERSION.txt\n* Added 2 methods in Converter interface: getInputType(), getOutputType(),\n to allow programmatic overrides (needed by JAXB annotation module)", "2.1.4 (26-Feb-2013)", "* [JACKSON-887]: StackOverflow with parameterized sub-class field\n (reported by Alexander M)\n* [#130]: TimeZone not set for GregorianCalendar, when deserializing\n* [#157]: NPE when registering module twice\n* [#162]: JsonNodeFactory: work around an old bug with BigDecimal and zero\n (submitted by fge@github)\n* [#166]: Incorrect optimization for `ObjectMapper.convertValue(Class)`\n (reported by Eric T)\n* [#167]: Problems with @JsonValue, polymorphic types (regression from 1.x)\n (reported by Eric T)\n* [#170]: Problems deserializing `java.io.File` if creator auto-discovery disabled\n (reported by Eric T)\n* [#175]: NPE for JsonMappingException, if no path is specified\n (reported by bramp@github)", "2.1.3 (19-Jan-2013)", "* [Issue#141]: ACCEPT_EMPTY_STRING_AS_NULL_OBJECT not working for enums\n* [Issue#142]: Serialization of class containing EnumMap with polymorphic enum\n fails to generate class type data\n (reported by kidavis4@github)", "2.1.2 (04-Dec-2012)", "* [Issue#106]: NPE in ObjectArraySerializer.createContextual(...)\n* [Issue#117]: HandlerInstantiator defaulting not working\n (reported by Alexander B)\n* [Issue#118]: Problems with JsonTypeInfo.As.EXTERNAL_PROPERTY, scalar values\n (reported by Adva11@github)\n* [Issue#119]: Problems with @JsonValue, JsonTypeInfo.As.EXTERNAL_PROPERTY\n (reported by Adva11@github)\n* [Issue#122]: ObjectMapper.copy() was not copying underlying mix-in map\n (reported by rzlo@github)", "2.1.1 (11-Nov-2012)", "Fixes:", "* [JACKSON-875]: Enum values not found if Feature.USE_ANNOTATIONS disabled\n (reported by Laurent P)\n* [Issue#93]: ObjectNode.setAll() broken; would not add anything for\n empty ObjectNodes.\n (reported by Francis G)\n* Making things implement java.io.Serializable:\n - Issues: #94, #99, #100, #102\n (reported by Sean B)\n* [Issue#96]: Problem with JsonTypeInfo.As.EXTERNAL_PROPERTY, defaultImpl\n (reported by Adva11@github)", "2.1.0 (08-Oct-2012)", " New minor version for 2.x series. Major improvements in multiple areas,\n including:", " - Dataformat auto-detection\n - More `@JsonFormat.shape` variant to serialize Collections as\n JSON Objects, POJOs as JSON Arrays (csv-like).\n - Much more configuration accessible via ObjectReader, ObjectWriter\n - New mechanism for JSON Schema generation, other uses (in future)", "Fixes:", "* [JACKSON-830]/[Issue#19]: Change OSGi bundle name to be fully-qualified\n* ]JACKSON-847]: Make @JsonIdentityInfo work with property-based creator\n* [JACKSON-851]: State corruption with ObjectWriter, DefaultPrettyPrinter\n (reported by Duncan A)\n* [Issue#75]: Too aggressive KeySerializer caching\n* Minor fix wrt [Issue#11], coercion needed extra checks", "Improvements:", "* [JACKSON-758]: Remove 'IOException' from throws clauses of \"writeValueAsString\"\n and \"writeValueAsBytes\" of ObjectMapper/ObjectWriter\n (suggested by G-T Chen)\n* [JACKSON-839]: Allow \"upgrade\" of integer number types for\n UntypedObjectDeserializer, even with default typing enabled.\n* [JACKSON-850]: Allow use of zero-arg factory methods as \"default creator\"\n (suggested by Razvan D)\n* [Issue#9]: Implement 'required' JSON Schema attribute for bean properties\n* [Issue#20]: Add new exception type, InvalidFormatException (sub-type of\n JsonMappingException) to indicate data format problems\n (suggested by HolySamosa@github)\n* [Issue#30]: ObjectReader and ObjectWriter now try to pre-fetch root\n (de)serializer if possible; minor performance improvement (2% for small POJOs).\n* [Issue#33]: Simplified/clarified definition of 'ObjectReader.readValues()';\n minor change in behavior for JSON Array \"wrapped\" sequences\n* [Issue#60]: Add 'JsonNode.hasNonNull(...)' method(s)\n (suggested by Jeff S on mailing list) \n* [Issue#64]: Add new \"standard\" PropertyNamingStrategy, PascalCaseStrategy\n (PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE)\n (contributed by Sean B)\n* [Issue#65]: Add getters to `ObjectMapper`, DeserializationContext/-Factory.\n (contributed by Dmitry K)\n* [Issue#69]: Add `PropertyName` abstraction, new methods in AnnotationIntrospector\n* [Issue#80]: Make `DecimalNode` normalize input, to make \"1.0\" and \"1.00\"equal\n (reported by fge@github)", "New features:", "* [Issue#15]: Support data format auto-detection via ObjectReader (added\n 'withFormatDetection(...)' fluent factories)\n* [Issue#21]: Add 'ObjectNode.set(...)' method (and related) to improve\n chaining, semantic consistency of Tree Model API\n (suggested by fge@Github)\n* [Issue#22]: Add 'ObjectMapper.setAnnotationIntrospectors()' which allows\n defining different introspectors for serialization, deserialization\n* [Issue#24]: Allow serialization of Enums as JSON Objects\n (suggested by rveloso@github)\n* [Issue#28]: Add 'ObjectMapper.copy()', to create non-linked copy of\n mapper, with same configuration settings\n* [Issue#29]: Allow serializing, deserializing POJOs as JSON Arrays\n by using `@JsonFormat(shape=Shape.ARRAY)`\n* [Issue#40]: Allow serialization of Collections as JSON Objects\n (and deserialization from)\n (suggested by 'rveloso@github')\n* [Issue#42]: Allow specifying Base64 variant to use for Base64-encoded data\n using ObjectReader.with(Base64Variant), ObjectWriter.with(Base64Variant).\n (suggested by 'mpfau@github')\n* [Issue#45]: Add '@JsonNaming' annotation to define per-class PropertyNamingStrategy\n (suggested by Mark W)\n* [Pull#58]: Make 'MappingIterator' implement 'Closable'\n (contributed by Pascal G)\n* [Issue#72]: Add 'MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME' to use\n wrapper name annotations for renaming properties\n* [Issue#87]: Add 'StdDelegatingSerializer', 'StdDelegatingDeserializer' to\n simplify writing of two-step handlers\n* (issue #4 of jackson-annotations): Add `@JsonIdentityReference(alwaysAsId=true)`\n to force ALL references to an object written as Object Id, even the first one.\n* Added 'ObjectReader#withHandler' to allow for reconfiguring deserialization\n problem handler\n (suggested by 'electricmonk')", "Other changes:", "* New variant of AnnotationIntrospector.getFormat(), to support class\n annotations\n* It is now possible to serialize instances of plain old Object, iff\n 'FAIL_ON_EMPTY_BEANS' is disabled.\n* Trying to remove reference to \"JSON\" in datatype conversion errors\n (since databinding is format-agnostic)", "INCOMPATIBILITIES: (rats!)", "* Note that [Issue#33] (see above) is, technically speaking, backwards\n imcompatible change. It is estimated that it should NOT affect most\n users, as changes are to edge cases (and undocumented ones at that).\n However, it can potentially cause problems with upgrade.\n* Implementation of `JsonFormatVisitable` resulting in 2 new methods\n being added in `BeanPropertyFilter` interface -- this is unfortunate,\n but was required to support full traversability.", "2.0.4 (26-Jun-2012)", "* [Issue#6]: element count for PrettyPrinter, endObject wrong\n (reported by \"thebluemountain\")\n* [JACKSON-838]: Utf8StreamParser._reportInvalidToken() skips letters\n from reported token name\n (reported by Lóránt Pintér)\n* [JACKSON-841] Data is doubled in SegmentedStringWriter output\n (reported by Scott S)\n* [JACKSON-842] ArrayIndexOutOfBoundsException when skipping C-style comments\n (reported by Sebastien R)", "2.0.3: no version 2.0.3 released -- only used for extension modules", "2.0.2 [14-May-2012]", "Fixes:", "* [Issue#14]: Annotations were not included from parent classes of\n mix-in classes\n (reported by @guillaup)\n* [JACKSON-824]: Combination of JSON Views, ObjectMapper.readerForUpdating()\n was not working\n (reported by Nir S)\n(and all fixes from 1.9.7)", "Improvements:", "* [Issue#11]: Improve ObjectMapper.convertValue()/.treeToValue() to use\n cast if possible", "2.0.1 [23-Apr-2012]", "Fixes:", "* [JACKSON-827] Ensure core packages work on JDK 1.5\n (reported by Pascal g)\n* [JACKSON-829] Custom serializers not working for List<String> properties,\n @JsonSerialize(contentUsing)\n (reported by James R)", "Improvements:", "* [Issue#5]: Add support for maps with java.util.Locale keys to the set of\n StdKeyDeserializers\n (contributed by Ryan G)", "2.0.0 [25-Mar-2012]", "Fixes:", "* [JACKSON-368]: Problems with managed references, abstract types\n* [JACKSON-711]: Delegating @JsonCreator did not work with Injectable values\n* [JACKSON-798]: Problem with external type id, creators\n (reported by Casey L)\n(and all fixes up until and including 1.9.6)", "Improvements:", "* [JACKSON-546]: Indicate end-of-input with JsonMappingException instead\n of EOFException, when there is no parsing exception\n* [JACKSON-664]: Reduce overhead of type resolution by adding caching\n in TypeFactory\n* [JACKSON-690]: Pass DeserializationContext through ValueInstantiator\n* [JACKSON-695]: Add 'isEmpty(value)' in JsonSerializer to allow\n customizing handling of serialization of empty values\n* [JACKSON-710]: 'ObjectMapper.convertValue()' should ignore root value\n wrapping/unwrapping settings\n* [JACKSON-730] Split various features (JsonParser, JsonGenerator,\n SerializationConfig, DeserializationConfig) into per-factory\n features (MapperFeature, JsonFactory.Feature) an per\n instance features (existing ones)\n* [JACKSON-732]: Allow 'AnnotationIntrospector.findContentDeserializer()'\n (and similar) to return instance, not just Class<?> for instance\n (requested by James R)\n* [JACKSON-736]: Add (more) access to array, container and map serializers\n* [JACKSON-737]: Allow accessing of \"creator properties\" for BeanDeserializer\n* [JACKSON-748]: Add 'registerSubtypes' to 'Module.setupContext' (and SimpleModule)\n* [JACKSON-749]: Make @JsonValue work for Enum deserialization\n* [JACKSON-769]: ObjectNode/ArrayNode: change 'put', 'insert', 'add' to return\n 'this node' (unless already returning something)\n* [JACKSON-770]: Simplify method naming for JsonNode, drop unnecessary 'get' prefix\n from methods like 'getTextValue()' (becomes 'textValue()')\n* [JACKSON-777]: Rename 'SerializationConfig.Feature' as 'SerializationFeature',\n 'DeserializationConfig.Feature' as 'DeserializationFeature'\n* [JACKSON-780]: MissingNode, NullNode should return 'defaultValue' from 'asXxx' methods,\n (not 0 for numbers), as they are not numeric types\n* [JACKSON-787]: Allow use of @JsonIgnoreProperties for properties (fields, getters, setters)\n* [JACKSON-795]: @JsonValue was not working for Maps, Collections\n* [JACKSON-800]: Add 'Module.SetupContext#addDeserializationProblemHandler'\n (suggested by James R)", "New features:", "* [JACKSON-107]: Add support for Object Identity (to handled cycles, shared refs),\n with @JsonIdentityInfo\n* [JACKSON-435]: Allow per-property Date formatting using @JsonFormat.\n* [JACKSON-437]: Allow injecting of type id as POJO property, by setting\n new '@JsonTypeInfo.visible' property to true.\n* [JACKSON-469]: Support \"Builder pattern\" for deserialiation; that is, allow\n use of separate Builder object for data binding, creating actual value\n* [JACKSON-608]: Allow use of JSON Views for deserialization\n* [JACKSON-636]: Add 'SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS' to allow\n forced sorting of Maps during serialization\n (suggested by Joern H)\n* [JACKSON-669]: Allow prefix/suffix for @JsonUnwrapped properties\n (requested by Aner P)\n* [JACKSON-707]: Add 'JsonNode.deepCopy()', to create safe deep copies\n of ObjectNodes, ArrayNodes.\n* [JACKSON-714]: Add general-purpose @JsonFormat annotation\n* [JACKSON-718]: Added 'JsonNode.canConvertToInt()', 'JsonNode.canConvertToLong()'\n* [JACKSON-747]: Allow changing of 'SerializationFeature' for ObjectWriter,\n 'DeserializationFeature' for ObjectReader.\n* [JACKSON-752]: Add @JsonInclude (replacement of @JsonSerialize.include)\n* [JACKSON-754]: Add @JacksonAnnotationsInside for creating \"annotation\n bundles\" (also: AnnotationIntrospector.isAnnotationBundle())\n* [JACKSON-762]: Allow using @JsonTypeId to specify property to use as\n type id, instead of using separate type id resolver.\n* [JACKSON-764]: Allow specifying \"root name\" to use for root wrapping\n via ObjectReader, ObjectWriter.\n* [JACKSON-772]: Add 'JsonNode.withArray()' to use for traversing Array nodes.\n* [JACKSON-793]: Add support for configurable Locale, TimeZone to use\n (via SerializationConfig, DeserializationConfig)\n* [JACKSON-805]: Add 'SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED'\n to improve interoperability with BadgerFish/Jettison\n* [JACKSON-810]: Deserialization Feature: Allow unknown Enum values via\n 'DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL'\n (suggested by Raymond R)\n* [JACKSON-813]: Add '@JsonSerializableSchema.id' attribute, to indicate\n 'id' value to add to generated JSON Schemas.", "[entries for versions 1.x and earlier not retained; refer to earlier releases)" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [8, 69], "buggy_code_start_loc": [7, 69], "filenames": ["release-notes/VERSION", "src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializerFactory.java"], "fixing_code_end_loc": [12, 76], "fixing_code_start_loc": [8, 70], "message": "FasterXML jackson-databind 2.x before 2.9.7 might allow remote attackers to execute arbitrary code by leveraging failure to block the blaze-ds-opt and blaze-ds-core classes from polymorphic deserialization.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "A1BA8F04-46A7-4804-A997-59080034013F", "versionEndExcluding": "2.6.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.6.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "B99066EB-FF79-4D9D-9466-B04AD4D3A814", "versionEndExcluding": "2.7.9.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4D3858C-DAF3-4522-90EC-EFCD13BD121E", "versionEndExcluding": "2.8.11.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "4DA01839-5250-43A7-AFB7-871DC9B8AB32", "versionEndExcluding": "2.9.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.9.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"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}, {"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:banking_platform:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "35AD0C07-9688-4397-8D45-FBB88C0F0C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.0:*:*:*:*:*:*:*", "matchCriteriaId": "8972497F-6E24-45A9-9A18-EB0E842CB1D4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.1:*:*:*:*:*:*:*", "matchCriteriaId": "400509A8-D6F2-432C-A2F1-AD5B8778D0D9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.2:*:*:*:*:*:*:*", "matchCriteriaId": "132CE62A-FBFC-4001-81EC-35D81F73AF48", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:business_process_management_suite:12.1.3.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "B887E174-57AB-449D-AEE4-82DD1A3E5C84", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:business_process_management_suite:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "E869C417-C0E6-4FC3-B406-45598A1D1906", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:clusterware:12.1.0.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "6C9084DB-329E-403F-8D0A-5B9F53183714", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_billing_and_revenue_management:7.5:*:*:*:*:*:*:*", "matchCriteriaId": "E6039DC7-08F2-4DD9-B5B5-B6B22DD2409F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_billing_and_revenue_management:12.0:*:*:*:*:*:*:*", "matchCriteriaId": "7231AF76-3D46-41C4-83E9-6E9E12940BD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:11.2.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "C1E11A25-C7CE-49DF-99CA-352FD21B8230", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:12.1.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "4F3D40B7-925C-413D-AFF3-60BF330D5BC2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:12.2.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "5C614BA7-7103-4ED7-ADD0-56064FE256A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:18c:*:*:*:*:*:*:*", "matchCriteriaId": "6833701E-5510-4180-9523-9CFD318DEE6A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:19c:*:*:*:*:*:*:*", "matchCriteriaId": "B2204841-585F-40C7-A1D9-C34E612808CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "A9E97F04-00ED-48E9-AB40-7A02B3419641", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "FCCE5A11-39E7-4BBB-9E1A-BA4B754103BB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "A5AEC7F5-C353-4CF5-96CE-8C713A2B0C92", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "BB79BB43-E0AB-4F0D-A6EA-000485757EEC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "F238CB66-886D-47E8-8DC0-7FC2025771EB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "59B7B8AD-1210-4C40-8EF7-E2E8156630A1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "0DE4A291-4358-42A9-A68D-E59D9998A1CC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "0D19CF00-FE20-4690-AAB7-8E9DBC68A94F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "A030A498-3361-46F8-BB99-24A66CAE11CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "F6455EB1-C741-45E8-A53E-E7AD7A5D00EE", "versionEndExcluding": "11.2.0.3.23", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "BFD43191-E67F-4D1B-967B-3C7B20331945", "versionEndExcluding": "12.2.0.1.19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "12.2.0.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "062C588A-CBBA-470F-8D11-2F961922E927", "versionEndExcluding": "13.9.4.2.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "13.9.4.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jdeveloper:12.1.3.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "042C243F-EDFE-4A04-AB0B-26E73CC34837", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jdeveloper:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "228DA523-4D6D-48C5-BDB0-DB1A60F23F8B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A1E1023-2EB9-4334-9B74-CA71480F71C2", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "93A4E178-0082-45C5-BBC0-0A4E51C8B1DE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:15.2:*:*:*:*:*:*:*", "matchCriteriaId": "3F021C23-AB9B-4877-833F-D01359A98762", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:16.1:*:*:*:*:*:*:*", "matchCriteriaId": "2F8ED016-32A1-42EE-844E-3E6B2C116B74", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:16.2:*:*:*:*:*:*:*", "matchCriteriaId": "A046CC2C-445F-4336-8810-930570B4FEC6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "0745445C-EC43-4091-BA7C-5105AFCC6F1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:*:*:*:*:*:*:*:*", "matchCriteriaId": "08FA59A8-6A62-4B33-8952-D6E658F8DAC9", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:16.1:*:*:*:*:*:*:*", "matchCriteriaId": "D55A54FD-7DD1-49CD-BE81-0BE73990943C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:16.2:*:*:*:*:*:*:*", "matchCriteriaId": "82EB08C0-2D46-4635-88DF-E54F6452D3A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "202AD518-2E9B-4062-B063-9858AE1F9CE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_merchandising_system:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "792DF04A-2D1B-40B5-B960-3E7152732EB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_merchandising_system:16.0:*:*:*:*:*:*:*", "matchCriteriaId": "46525CA6-4226-4F6F-B899-D800D4DDE0B5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_workforce_management_software:1.60.9.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "9967AAFD-2199-4668-9105-207D4866B707", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:webcenter_portal:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "D6A4F71A-4269-40FC-8F61-1D1301F2B728", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "3A76E5BF-01E4-46E7-8E3B-5ACE75657360", "versionEndExcluding": "3.11.153", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.11", "vulnerable": true}, {"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "E9A6D103-9674-4B04-8397-86501F1D91CF", "versionEndExcluding": "4.6.26", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.6", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "D2452F48-6A8B-4274-B0CE-F1256F400170", "versionEndExcluding": "4.1.18", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.1", "vulnerable": true}], "negate": false, "operator": "OR"}, {"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": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"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}, {"criteria": "cpe:2.3:a:netapp:snapcenter:-:*:*:*:*:*:*:*", "matchCriteriaId": "BDFB1169-41A0-4A86-8E4F-FDA9730B1E94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:netapp:steelstore_cloud_integrated_storage:*:*:*:*:*:*:*:*", "matchCriteriaId": "09A8C9D2-9FFF-4312-95FB-87D79B3C0339", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "FasterXML jackson-databind 2.x before 2.9.7 might allow remote attackers to execute arbitrary code by leveraging failure to block the blaze-ds-opt and blaze-ds-core classes from polymorphic deserialization."}, {"lang": "es", "value": "Las versiones 2.x de FasterXML jackson-databind anteriores a la 2.9.7 podr\u00edan permitir a los atacantes remotos ejecutar c\u00f3digo arbitrario aprovechando un fallo para bloquear las clases blaze-ds-opt y blaze-ds-core de deserializaci\u00f3n polim\u00f3rfica."}], "evaluatorComment": null, "id": "CVE-2018-14719", "lastModified": "2021-05-21T15:22:43.047", "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": "2019-01-02T18:29:00.387", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHBA-2019:0959"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:0782"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:0877"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1782"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1797"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1822"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1823"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:2804"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:2858"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3002"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3140"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3149"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3892"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:4037"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson-databind/commit/87d29af25e82a249ea15858e2d4ecbf64091db44"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson-databind/issues/2097"}, {"source": "cve@mitre.org", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.9.7"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/519eb0fd45642dcecd9ff74cb3e71c20a4753f7d82e2f07864b5108f@%3Cdev.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/b0656d359c7d40ec9f39c8cc61bca66802ef9a2a12ee199f5b0c1442@%3Cdev.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/f9bc3e55f4e28d1dcd1a69aae6d53e609a758e34d2869b4d798e13cc@%3Cissues.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ff8dcfe29377088ab655fda9d585dccd5b1f07fabd94ae84fd60a7f8@%3Ccommits.pulsar.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf1bbc0ea4a9f014cf94df9a12a6477d24a27f52741dbc87f2fd52ff2@%3Cissues.geode.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/03/msg00005.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Mailing List", "Third Party Advisory"], "url": "https://seclists.org/bugtraq/2019/May/68"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20190530-0003/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2019/dsa-4452"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2020.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpuapr2019-5072813.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpujan2019-5072801.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpujul2019-5072835.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpuoct2019-5072832.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/FasterXML/jackson-databind/commit/87d29af25e82a249ea15858e2d4ecbf64091db44"}, "type": "CWE-502"}
245
Determine whether the {function_name} code is vulnerable or not.
[ "Project: jackson-databind", "------------------------------------------------------------------------\n=== Releases ===\n------------------------------------------------------------------------", "2.6.7.2 (not yet released)", "", "#1737: Block more JDK types from polymorphic deserialization", "#2097: Block more classes from polymorphic deserialization (CVE-2018-14718\n - CVE-2018-14721)", "\n2.6.7.1 (11-Jul-2017)", "#1383: Problem with `@JsonCreator` with 1-arg factory-method, implicit param names\n#1599: Backport the extra safety checks for polymorphic deserialization", "2.6.7 (05-Jun-2016)", "#1194: Incorrect signature for generic type via `JavaType.getGenericSignature\n#1228: @JsonAnySetter does not deserialize null to Deserializer's NullValue\n (contributed by Eric S)", "2.6.6 (05-Apr-2016)", "#1088: NPE possibility in SimpleMixinResolver\n (reported by Laird N)\n#1099: Fix custom comparator container node traversal\n (contributed by Daniel N)\n#1108: Jackson not continue to parse after DeserializationFeature.FAIL_ON_INVALID_SUBTYPE error\n (reported by jefferyyuan@github)\n#1112: Detailed error message from custom key deserializer is discarded\n (contributed by Benson M)\n#1120: String value omitted from weirdStringException\n (reported by Benson M)\n#1123: Serializing and Deserializing Locale.ROOT\n (reported by hookumsnivy@github)", "2.6.5 (19-Jan-2016)", "#1052: Don't generate a spurious NullNode after parsing an embedded object\n (reported by philipa@github)\n#1061: Problem with Object Id and Type Id as Wrapper Object (regression in 2.5.1)\n#1073: Add try-catch around `java.sql` type serializers\n (suggested by claudemt@github)\n#1078: ObjectMapper.copy() still does not preserve _registeredModuleTypes\n (reported by ajonkisz@github)", "2.6.4 (07-Dec-2015)", "#984: JsonStreamContexts are not build the same way for write.. and convert methods\n (reported by Antibrumm@github)\n#989: Deserialization from \"{}\" to java.lang.Object causes \"out of END_OBJECT token\" error\n (reported by Ievgen P)\n#1003: JsonTypeInfo.As.EXTERNAL_PROPERTY does not work with a Delegate\n (reported by alexwen@github)\n#1005: Synthetic constructors confusing Jackson data binding\n (reported by Jayson M)\n#1013: `@JsonUnwrapped` is not treated as assuming `@JsonProperty(\"\")`\n (reported by David B)\n#1036: Problem with case-insensitive deserialization\n (repoted by Dmitry R)\n- Fix a minor problem with `@JsonNaming` not recognizing default value", "2.6.3 (12-Oct-2015)", "#749: `EnumMap` serialization ignores `SerializationFeature.WRITE_ENUMS_USING_TO_STRING`\n (reported by scubasau@github)\n#938: Regression: `StackOverflowError` with recursive types that contain `Map.Entry`\n (reported by jloisel@github)\n#939: Regression: DateConversionError in 2.6.x \n (reported by Andreas P, anpieber@github)\n#940: Add missing `hashCode()` implementations for `JsonNode` types that did not have them\n (contributed by Sergio M)\n#941: Deserialization from \"{}\" to ObjectNode field causes \"out of END_OBJECT token\" error\n (reported by Sadayuki F)\n#942: Handle null type id for polymorphic values that use external type id\n (reported by Warren B, stormboy@github)\n#943: Incorrect serialization of enum map key\n (reported by Benson M)\n#944: Failure to use custom deserializer for key deserializer\n (contributed by Benson M)\n#949: Report the offending substring when number parsing fails\n (contributed by Jesse W)\n#965: BigDecimal values via @JsonTypeInfo/@JsonSubTypes get rounded\n (reported by gmjabs@github)", "2.6.2 (14-Sep-2015)", "#894: When using withFactory on ObjectMapper, the created Factory has a TypeParser\n which still has the original Factory\n (reported by lufe66@github)\n#899: Problem serializing `ObjectReader` (and possibly `ObjectMapper`)\n#913: ObjectMapper.copy does not preserve MappingJsonFactory features\n (reported, fixed by Daniel W)\n#922: ObjectMapper.copy() does not preserve _registeredModuleTypes\n#928: Problem deserializing External Type Id if type id comes before POJO", "2.6.1 (09-Aug-2015)", "#873: Add missing OSGi import\n#881: BeanDeserializerBase having issues with non-CreatorProperty properties.\n (reported by dharaburda@github)\n#884: ArrayIndexOutOfBoundException for `BeanPropertyMap` (with ObjectId)\n (reported by alterGauner@github)\n#889: Configuring an ObjectMapper's DateFormat changes time zone\n (reported by Andy W, wilkinsona@github)\n#890: Exception deserializing a byte[] when the target type comes from an annotation\n (reported by gmjabs@github)", "2.6.0 (19-Jul-2015)", "#77: Allow injection of 'transient' fields\n#95: Allow read-only properties with `@JsonIgnoreProperties(allowGetters=true)`\n#222: EXTERNAL_PROPERTY adds property multiple times and in multiple places\n (reported by Rob E, thatsnotright@github)\n#296: Serialization of transient fields with public getters (add\n MapperFeature.PROPAGATE_TRANSIENT_MARKER)\n (suggested by Michal L)\n#312: Support Type Id mappings where two ids map to same Class\n#348: ObjectMapper.valueToTree does not work with @JsonRawValue\n (reported by Chris P, pimlottc@github)\n#504: Add `DeserializationFeature.USE_LONG_FOR_INTS`\n (suggested by Jeff S)\n#624: Allow setting external `ClassLoader` to use, via `TypeFactory`\n#649: Make `BeanDeserializer` use new `parser.nextFieldName()` and `.hasTokenId()` methods\n#664: Add `DeserializationFeature.ACCEPT_FLOAT_AS_INT` to prevent coercion of floating point\n numbers int `int`/`long`/`Integer`/`Long`\n (requested by wenzis@github)\n#677: Specifying `Enum` value serialization using `@JsonProperty`\n (requested by Allen C, allenchen1154@github)\n#679: Add `isEmpty()` implementation for `JsonNode` serializers\n#688: Provide a means for an ObjectMapper to discover mixin annotation classes on demand\n (requested by Laird N)\n#689: Add `ObjectMapper.setDefaultPrettyPrinter(PrettyPrinter)`\n (requested by derknorton@github)\n#696: Copy constructor does not preserve `_injectableValues`\n (reported by Charles A)\n#698: Add support for referential types (ReferenceType)\n#700: Cannot Change Default Abstract Type Mapper from LinkedHashMap\n (reported by wealdtech@github)\n#725: Auto-detect multi-argument constructor with implicit names if it is the only visible creator\n#727: Improve `ObjectWriter.forType()` to avoid forcing base type for container types\n#734: Add basic error-recovery for `ObjectReader.readValues()`\n#737: Add support for writing raw values in TokenBuffer\n (suggested by Guillaume S, gsmet@github)\n#740: Ensure proper `null` (as empty) handling for `AtomicReference`\n#741: Pass `DeserializationContext' argument for `JsonDeserializer` methods \"getNullValue()\"\n and \"getEmptyValue()\"\n#743: Add `RawValue` helper type, for piping raw values through `TokenBuffer`\n#756: Disabling SerializationFeature.FAIL_ON_EMPTY_BEANS does not affect `canSerialize()`\n (reported by nickwongdev@github)\n#762: Add `ObjectWriter.withoutRootName()`, `ObjectReader.withoutRootName()`\n#765: `SimpleType.withStaticTyping()` impl incorrect\n#769: Fix `JacksonAnnotationIntrospector.findDeserializer` to return `Object` (as per\n `AnnotationIntrospector`); similarly for other `findXxx(De)Serializer(...)` methods\n#777: Allow missing build method if its name is empty (\"\")\n (suggested by galdosd@github)\n#781: Support handling of `@JsonProperty.required` for Creator methods\n#787: Add `ObjectMapper setFilterProvider(FilterProvider)` to allow chaining\n (suggested by rgoldberg@githin)\n#790: Add `JsonNode.equals(Comparator<JsonNode>, JsonNode)` to support\n configurable/external equality comparison\n#794: Add `SerializationFeature.WRITE_DATES_WITH_ZONE_ID` to allow inclusion/exclusion of\n timezone id for date/time values (as opposed to timezone offset)\n#795: Converter annotation not honored for abstract types\n (reported by myrosia@github)\n#797: `JsonNodeFactory` method `numberNode(long)` produces `IntNode` for small numbers\n#810: Force value coercion for `java.util.Properties`, so that values are `String`s\n#811: Add new option, `JsonInclude.Include.NON_ABSENT` (to support exclusion of\n JDK8/Guava Optionals)\n#812: Java 8 breaks Class-value annotation properties, wrt generics: need to work around\n#813: Add support for new property of `@JsonProperty.access` to support\n read-only/write-only use cases\n#820: Add new method for `ObjectReader`, to bind from JSON Pointer position\n (contributed by Jerry Y, islanderman@github)\n#824: Contextual `TimeZone` changes don't take effect wrt `java.util.Date`,\n `java.util.Calendar` serialization\n#826: Replaced synchronized HashMap with ConcurrentHashMap in TypeDeserializerBase._findDeserializer\n (contributed by Lars P)\n#827: Fix for polymorphic custom map key serializer\n (reported by mjr6140@gitgub)\n#828: Respect DeserializationFeatures.WRAP_EXCEPTIONS in CollectionDeserializer\n (contributed by Steve G, thezerobit@github)\n#840: Change semantics of `@JsonPropertyOrder(alphabetic)` to only count `true` value\n#848: Custom serializer not used if POJO has `@JsonValue`\n#849: Possible problem with `NON_EMPTY` exclusion, `int`s, `Strings`\n#868: Annotations are lost in the case of duplicate methods\n- Remove old cglib compatibility tests; cause problems in Eclipse\n- Add `withFilterId()` method in `JsonSerializer` (demote from `BeanSerializer`)", "2.5.5 (07-Dec-2015)", "#844: Using JsonCreator still causes invalid path references in JsonMappingException\n (reported by Ian B)\n#852: Accept scientific number notation for quoted numbers too\n#878: serializeWithType on BeanSerializer does not setCurrentValue\n (reported by Chi K, chikim79@github)", "2.5.4 (09-Jun-2015)", "#676: Deserialization of class with generic collection inside depends on\n how is was deserialized first time\n (reported by lunaticare@github)\n#771: Annotation bundles ignored when added to Mixin\n (reported by Andrew D)\n#774: NPE from SqlDateSerializer as _useTimestamp is not checked for being null\n (reported by mrowkow@github)\n#785: Add handlings for classes which are available in `Thread.currentThread().getContextClassLoader()`\n (contributed by Charles A)\n#792: Ensure Constructor Parameter annotations are linked with those of Field, Getter, or Setter\n#793: `ObjectMapper.readTree()` does not work with defaultTyping enabled\n (reported by gracefulgopher@github)\n#801: Using `@JsonCreator` cause generating invalid path reference in `JsonMappingException`\n (contributed by Kamil B)\n#815: Presence of PropertyNamingStrategy Makes Deserialization fail\n#816: Allow date-only ISO strings to have no time zone\n (contributed by Andrew G)\n- Fix handling of Enums wrt JSON Schema, when 'toString()' used for serialization", "2.5.3 (24-Apr-2015)", "#731: XmlAdapter result marshaling error in case of ValueType=Object\n (reported, debugged by Dmitry S)\n#742: Allow deserialization of `null` Object Id (missing already allowed)\n#744: Custom deserializer with parent object update failing\n (reported by migel@github)\n#745: EnumDeserializer.deserializerForCreator fails when used to deserialize a Map key\n (contributed by John M)\n#761: Builder deserializer: in-compatible type exception when return type is super type\n (contributed by Alexey G)\n#766: Fix Infinite recursion (StackOverflowError) when serializing a SOAP object\n (contributed by Alain G)", "2.5.2 (29-Mar-2015)", "#609: Problem resolving locally declared generic type\n (repoted by Hal H)\n#691: NullSerializer for MapProperty failing when using polymorphic handling\n (reported by Antibrumm@github)\n#703: Multiple calls to ObjectMapper#canSerialize(Object.class) returns different values\n (reported by flexfrank@github)\n#705: JsonAnyGetter doesn't work with JsonSerialize (except with keyUsing)\n (reported by natnan@github)\n#728: TypeFactory#_fromVariable returns unknownType() even though it has enough information\n to provide a more specific type\n (reported by jkochaniak@github)\n#733: MappingIterator should move past errors or not return hasNext() == true\n (reported by Lorrin N, lorrin@github)\n#738: @JsonTypeInfo non-deterministically ignored in 2.5.1 (concurrency issue)\n (reported by Dylan S, dylanscott@github)\n- Improvement to handling of custom `ValueInstantiator` for delegating mode; no more NPE\n if `getDelegateCreator()` returns null\n- Refactor `TypedKey` into separate util class", "2.5.1 (06-Feb-2015)", "#667: Problem with bogus conflict between single-arg-String vs `CharSequence` constructor\n#669: JSOG usage of @JsonTypeInfo and @JsonIdentityInfo(generator=JSOGGenerator.class) fails\n (reported by ericali78@github)\n#671: Adding `java.util.Currency` deserialization support for maps\n (contributed by Alexandre S-C)\n#674: Spring CGLIB proxies not handled as intended\n (reported by Zoltan F)\n#682: Class<?>-valued Map keys not serialized properly\n (reported by Ludevik@github)\n#684: FAIL_ON_NUMBERS_FOR_ENUMS does not fail when integer value is quoted\n (reported by kllp@github)\n#696: Copy constructor does not preserve `_injectableValues`\n (reported by Charles A)\n- Add a work-around in `ISO8601DateFormat` to allow omission of ':' from timezone\n- Bit more work to complete #633", "2.5.0 (01-Jan-2015)", "#47: Support `@JsonValue` for (Map) key serialization \n#113: Problem deserializing polymorphic types with @JsonCreator\n#165: Add `DeserializationContext.getContextualType()` to let deserializer\n known the expected type.\n#299: Add `DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS` to allow missing\n Object Ids (as global default)\n#408: External type id does not allow use of 'visible=true'\n#421: @JsonCreator not used in case of multiple creators with parameter names\n (reported by Lovro P, lpandzic@github)\n#427: Make array and Collection serializers call `JsonGenerator.writeStartArray(int)`\n#521: Keep bundle annotations, prevent problems with recursive annotation types\n (reported by tea-dragon@github)\n#527: Add support for `@JsonInclude(content=Include.NON_NULL)` (and others) for Maps\n#528: Add support for `JsonType.As.EXISTING_PROPERTY`\n (reported by heapifyman@github; implemented by fleebytes@github)\n#539: Problem with post-procesing of \"empty bean\" serializer; was not calling\n 'BeanSerializerModifier.modifySerializer()` for empty beans\n (reported by Fabien R, fabienrenaud@github)\n#540: Support deserializing `[]` as null or empty collection when the java type\n is a not an object, `DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT`\n (requested by Fabien R, fabienrenaud@github)\n#543: Problem resolving self-referential recursive types\n (reported by ahgittin@github)\n#550: Minor optimization: prune introspection of \"well-known\" JDK types\n#552: Improved handling for ISO-8601 (date) format\n (contributed by Jerome G, geronimo-iia@github)\n#559: Add `getDateFormat()`, `getPropertyNamingStrategy()` in `ObjectMapper`\n#560: @JsonCreator to deserialize BigInteger to Enum\n (requested by gisupp@github)\n#565: Add support for handling `Map.Entry`\n#566: Add support for case-insensitive deserialization (`MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES`)\n (contributed by Michael R)\n#571: Add support in ObjectMapper for custom `ObjectReader`, `ObjectWriter` (sub-classes)\n#572: Override default serialization of Enums\n (requested by herau@github)\n#576: Add fluent API for adding mixins\n (contributed by Adam S, adstro@github)\n#594: `@JsonValue` on enum not used when enum value is a Map key\n (reported by chrylis@github)\n#596: Add support for `@JsonProperty.defaultValue`, exposed via `BeanProperty.getMetadata().getDefaultValue()`\n#597: Improve error messaging for cases where JSON Creator returns null (which\n is illegal)\n (contributed by Aurelien L)\n#599: Add a simple mechanism for avoiding multiple registrations of the same module\n#607: Allow (re)config of `JsonParser.Feature`s via `ObjectReader`\n#608: Allow (re)config of `JsonGenerator.Feature`s via `ObjectWriter`\n#614: Add a mechanism for using `@JsonCreator.mode` for resolving possible ambiguity between\n delegating- and property-based creators\n#616: Add `SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS`\n#622: Support for non-scalar ObjectId Reference deserialiazation (like JSOG)\n#623: Add `StdNodeBasedDeserializer`\n#630: Add `KeyDeserializer` for `Class`\n#631: Update `current value` of `JsonParser`, `JsonGenerator` from standard serializers,\n deserializers\n (suggested by Antibrumm@github)\n#633: Allow returning null value from IdResolver to make type information optional\n (requested by Antibrumm@github)\n#634: Add `typeFromId(DatabindContext,String)` in `TypeIdDeserializer`\n#636: `ClassNotFoundException` for classes not (yet) needed during serialization\n (contributed by mspiegel@github)\n#638: Add annotation-based method(s) for injecting properties during serialization\n (using @JsonAppend, VirtualBeanPropertyWriter)\n#647: Deserialization fails when @JsonUnwrapped property contains an object with same property name\n (reported by Konstantin L)\n#653: Jackson doesn't follow JavaBean naming convention (added `MapperFeature.USE_STD_BEAN_NAMING`)\n#654: Add support for (re)configuring `JsonGenerator.setRootValueSeparator()` via `ObjectWriter`\n#655: Add `ObjectWriter.writeValues()` for writing value sequences\n#660: `@JsonCreator`-annotated factory method is ignored if constructor exists\n- Allow use of `Shape.ARRAY` for Enums, as an alias to 'use index'\n- Start using `JsonGenerator.writeStartArray(int)` to help data formats\n that benefit from knowing number of elements in arrays (and would otherwise\n need to buffer values to know length)\n- Added new overload for `JsonSerializer.isEmpty()`, to eventually solve #588\n- Improve error messaging (related to [jaxb-annotations#38]) to include known subtype ids.", "2.4.6 (23-Apr-2015)", "#735: (complete fix) @JsonDeserialize on Map with contentUsing custom deserializer overwrites default behavior\n (reported by blackfyre512@github) (regression due to #604)\n$744: Custom deserializer with parent object update fails", "2.4.5.1 (26-Mar-2015)", "Special one-off \"micro patch\" for:", "#706: Add support for `@JsonUnwrapped` via JSON Schema module\n#707: Error in getting string representation of an ObjectNode with a float number value\n (reported by @navidqar)\n#735: (partial) @JsonDeserialize on Map with contentUsing custom deserializer overwrites default behavior", "2.4.5 (13-Jan-2015)", "#635: Reduce cachability of `Map` deserializers, to avoid problems with per-property config changes\n (regression due to #604)\n#656: `defaultImpl` configuration is ignored for `WRAPPER_OBJECT`\n- Solve potential cyclic-resolution problem for `UntypedObjectDeserializer`", "2.4.4 (24-Nov-2014)", "(jackson-core)#158: Setter confusion on assignable types\n (reported by tsquared2763@github)\n#245: Calls to ObjectMapper.addMixInAnnotations() on an instance returned by ObjectMapper.copy()\n don't work\n (reported by Erik D)\n#580: delegate deserializers choke on a (single) abstract/polymorphic parameter\n (reported by Ian B, tea-dragon@github)\n#590: Binding invalid Currency gives nonsense at end of the message\n (reported by Jerbell@github)\n#592: Wrong `TokenBuffer` delegate deserialization using `@JsonCreator`\n (reported by Eugene L)\n#601: ClassCastException for a custom serializer for enum key in `EnumMap`\n (reported by Benson M)\n#604: `Map` deserializers not being cached, causing performance problems\n#610: Fix forward reference in hierarchies\n (contributed by zeito@github)\n#619: Off by one error in AnnotatedWithParams\n (reported by stevetodd@github)\n- Minor fix to `EnumSerializer` regarding detection \"serialize using index\"\n- Minor fix to number serializers, to call proper callback for schema generation", "2.4.3 (02-Oct-2014)", "#496: Wrong result with `new TextNode(\"false\").asBoolean(true)`\n (reported by Ivar R, ivarru@github)\n#511: DeserializationFeature.FAIL_ON_INVALID_SUBTYPE does not work\n (reported by sbelikov@github)\n#523: MapDeserializer and friends do not report the field/key name for mapping exceptions\n (reported by Ian B, tea-dragon@github)\n#524: @JsonIdentityReference(alwaysAsId = true) Custom resolver is reset to SimpleObjectIdResolver\n (reported by pkokorev@github)\n#541: @JsonProperty in @JsonCreator is conflicting with POJOs getters/attributes\n (reported by fabienrenaud@github)\n#543: Problem resolving self-referential generic types\n#570: Add Support for Parsing All Compliant ISO-8601 Date Formats\n (requested by pfconrey@github)\n- Fixed a problem with `acceptJsonFormatVisitor` with Collection/array types that\n are marked with `@JsonValue`; could cause NPE in JSON Schema generator module.", "2.4.2 (14-Aug-2014)", "#515: Mixin annotations lost when using a mixin class hierarchy with non-mixin interfaces\n (reported by 'stevebread@github')\n- Fixed a problem related to [jackson-dataformat-smile#19].", "2.4.1.2 (12-Jul-2014)", "Special one-off \"micro patch\" for:", "#503: Concurrency issue inside com.fasterxml.jackson.databind.util.LRUMap.get(Object)\n (reported by fjtc@github)", "2.4.1.1 (18-Jun-2014)", "Special one-off \"micro patch\" for:", "#491: Temporary work-around for issue #490 (full fix for 2.5 needs to be\n in `jackson-annotations`)\n#506: Index is never set for Collection and Array in InvalidFormatException.Reference\n (reported by Fabrice D, fabdouglas@github)\n- Fixed a problem related to [jackson-dataformat-smile#19].", "2.4.1 (17-Jun-2014)", "#479: NPE on trying to deserialize a `String[]` that contains null\n (reported by huxi@github)\n#482: Make date parsing error behavior consistent with JDK\n (suggested by Steve S, sanbeg@github)\n#489 (partial): TypeFactory cache prevents garbage collection of custom ClassLoader\n (reported by sftwrengnr@github)", "2.4.0 (02-Jun-2014)", "#81: Allow use of @JsonUnwrapped with typed (@JsonTypeInfo) classes, provided\n that (new) feature `SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS`\n is disabled\n (constributed by Ben F, UnquietCode@github)\n#88: Prevent use of type information for `JsonNode` via default typing\n (reported by electricmonk@github)\n#149: Allow use of \"stringified\" indexes for Enum values\n (requested by chenboxiang@github)\n#176: Allow use external Object Id resolver (to use with @JsonIdentityInfo etc)\n (implemented by Pascal G)\n#193: Conflicting property name definitions\n (reported by Stuart J, sgjohnston@github)\n#323: Serialization of the field with deserialization config\n (reported by metanet@github)\n#327: Should not consider explicitly differing renames a fail, as long as all are explicit\n#335: Allow use of `@JsonPropertyOrder(alphabetic=true)` for Map properties\n#352 Add `ObjectMapper.setConfig()` for overriding `SerializationConfig`/`DeserializationConfig`\n#353: Problems with polymorphic types, `JsonNode` (related to #88)\n (reported by cemo@github)\n#359: Converted object not using explicitly annotated serializer\n (reported by Florian S [fschopp@github])\n#369: Incorrect comparison for renaming in `POJOPropertyBuilder`\n#375: Add `readValue()`/`readPropertyValue()` methods in `DeserializationContext`\n#376: Add support for `@JsonFormat(shape=STRING)` for number serializers\n#381: Allow inlining/unwrapping of value from single-component JSON array\n (contributed by yinzara@github)\n#390: Change order in which managed/back references are resolved (now back-ref\n first, then forward)\n (requested by zAlbee@github)\n#407: Properly use null handlers for value types when serializer Collection\n and array types\n (contributed by Will P)\n#425: Add support for using `Void.class` as \"no class\", instead of `NoClass.class`\n#428: `PropertyNamingStrategy` will rename even explicit name from `@JsonProperty`\n (reported by turskip@github)\n#435: Performance bottleneck in TypeFactory._fromClass\n (reported by Sean D, sdonovanuk@github)\n#434: Ensure that DecimalNodes with mathematically equal values are equal\n (contributed by Francis G)\n#435: Performance bottleneck in TypeFactory._fromClass\n (reported by sdonovanuk@github)\n#438: Add support for accessing `@JsonProperty(index=N)` annotations\n#442: Make `@JsonUnwrapped` indicate property inclusion\n (suggested by Ben F)\n#447: ArrayNode#addAll should accept Collection<? extends JsonNode>\n (suggested by alias@github)\n#461: Add new standard naming strategy, `PropertyNamingStrategy.LowerCaseStrategy`\n#463: Add 'JsonNode.asText(String defaultValue)`\n (suggested by Chris C)\n#464: Include `JsonLocation` in more mapping exceptions\n (contributed by Andy C (q3aiml@github))\n#465: Make it easier to support serialization of custom subtypes of `Number`\n#467: Unwanted POJO's embedded in tree via serialization to tree\n (reported by Benson M)\n- Slightly improve `SqlDateSerializer` to support `@JsonFormat`\n- Improve handling of native type ids (YAML, CBOR) to use non-native type ids\n as fallback", "2.3.5 (13-Jan-2015)", "#496: Wrong result for TextNode(\"false\").asBoolean(true)\n (reported by Ivar R, ivarru@github)\n#543: Problems resolving self-referential generic types.\n#656: defaultImpl configuration is ignored for WRAPPER_OBJECT", "2.3.4 (17-Jul-2014)", "#459: BeanDeserializerBuilder copy constructor not copying `_injectables`\n#462: Annotation-provided Deserializers are not contextualized inside CreatorProperties\n (reported by aarondav@github)", "2.3.3 (10-Apr-2014)", "#420: Remove 'final' modifier from `BeanDeserializerBase.deserializeWithType`\n (requested by Ghoughpteighbteau@github)\n#422: Allow use of \"True\" and \"False\" as aliases for booleans when coercing from\n JSON String\n#423: Fix `CalendarSerializer` to work with custom format\n (reported by sergeymetallic@github)\n#433: `ObjectMapper`'s `.valueToTree()` wraps `JsonSerializable` objects into a POJONode\n (reported by Francis G)\n- Fix null-handling for `CollectionSerializer`", "2.3.2 (01-Mar-2014)", "#378: Fix a problem with custom enum deserializer construction\n (reported by BokoEnos@github)\n#379: Fix a problem with (re)naming of Creator properties; needed to make\n Paranamer module work with NamingStrategy.\n (reported by Chris P, cpilsworth@github)\n#398: Should deserialize empty (not null) URI from empty String\n (reported by pgieser@github)\n#406: @JsonTypeIdResolver not working with external type ids\n (reported by Martin T)\n#411: NumberDeserializers throws exception with NaN and +/- Infinity\n (reported by clarkbreyman@github)\n#412: ObjectMapper.writerWithType() does not change root name being used\n (repoted by jhalterman@github)\n- Added `BeanSerializerBase._serializeObjectId()` needed by modules that\n override standard BeanSerializer; specifically, XML module.", "2.3.1 (28-Dec-2013)", "#346: Fix problem deserializing `ObjectNode`, with @JsonCreator, empty\n JSON Object\n (reported by gaff78@github)\n#358: `IterableSerializer` ignoring annotated content serializer\n (reported by Florian S)\n#361: Reduce sync overhead for SerializerCache by using volatile, double-locking\n (contributed by stuartwdouglas@github)\n#362: UUID output as Base64 String with ObjectMapper.convertValue()\n (reported by jknack@github)\n#367: Make `TypeNameIdResolver` call `TypeResolver` for resolving base type\n (suggested by Ben F)\n#370: Fail to add Object Id for POJO with no properties\n (reported by jh3141@github)\n- Fix for [jackson-module-afterburner#38]: need to remove @JacksonStdImpl from\n `RawSerializer`, to avoid accidental removal of proper handling.", "2.3.0 (13-Nov-2013)", "#48: Add support for `InetSocketAddress`\n (contributed by Nick T)\n#152: Add support for traversing `JsonNode` with (new!) `JsonPointer` implementation\n (suggested by fge@github)\n#208: Accept \"fromString()\" as an implicit Creator (factory) method (alias for \"valueOf()\")\n (requested by David P)\n#215: Allow registering custom `CharacterEscapes` to use for serialization,\n via `ObjectWriter.with(CharacterEscapes)` (and `ObjectMapper.writer(CharacterEscapes)`)\n#227: Allow \"generic\" Enum serializers, deserializers, via `SimpleModule`\n#234: Incorrect type information for deeply nested Maps\n (reported by Andrei P)\n#237: Add `DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY` to optionally\n throw `JsonMappingException` on duplicate keys, tree model (`JsonNode`)\n#238: Allow existence of overlapping getter, is-getter (choose 'regular' getter)\n#239: Support `ByteBuffer`\n (suggested by mckamey@github)\n#240: Make sure `@JsonSerialize.include` does not accidentally override\n class inclusion settings\n (requested by thierryhenrio@github)\n#253: `DelegatingDeserializer` causes problems for Managed/BackReferences\n (reported by bfelaco@github)\n#257: Make `UntypedObjectDeserializer` support overides for `List`, `Map` etc\n#268: Add new variant of `ObjectMapper.canSerialize()` that can return `Throwable`\n that caused false to be returned (if any)\n#269: Add support for new `@JsonPropertyDescription` via `AnnotationIntrospector`\n as well as `BeanProperty.getMedata().getDescription()`\n#270: Add `SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID` to allow use of equality\n (instead of identity) for figuring out when to use Object Id\n (requested by beku8@github)\n#271: Support handling of `@JsonUnwrapped` for in-built JSON Schema generation\n#277: Make `TokenBuffer` support new native type and object ids\n#302: Add `setNamingStrategy` in `Module.SetupContext`\n (suggested by Miguel C)\n#305: Add support for accessing `TypeFactory` via `TypeIdResolverBase`\n (not yet via `TypeIdResolver` interface), other configuration\n#306: Allow use of `@JsonFilter` for properties, not just classes \n#307: Allow use of `@JsonFilter` for Maps in addition to POJOs\n#308: Improve serialization and deserialization speed of `java.util.UUID` by 4x\n (suggested by David P)\n#310: Improve `java.util.UUID` serialization with binary codecs, to use \"raw\" form.\n#311: Make sure that \"creator properties\" are alphabetically ordered too, if\n so requested.\n#315: Allow per-property definition of null serializer to use, using\n new `@JsonSerialize(nullsUsing=xxx)` annotation property\n#317: Fix `JsonNode` support for nulls bound to `ObjectNode`, `ArrayNode`\n (contributed by Seth P)\n#318: Problems with `ObjectMapper.updateValue()`, creator property-backed accessors\n#319: Add support for per-call (\"contextual\") attributes, with defaulting,\n to allow keeping track of state during (de)serialization\n#324: Make sure to throw `JsonMappingException` from `EnumDeserializer` creator,\n not `IllegalArgumentException`\n (reported by beverku@github)\n#326: Support `@JsonFilter` for \"any getter\" properties\n#334: Make `ArrayNode`, `ObjectNode` non-final again\n#337: `AnySetter` does not support polymorphic types\n (reported by askvortsov@github)\n#340: AtomicReference not working with polymorphic types\n#342: Add `DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES` to make `ObjectMapper`\n throw exception when encountering explicitly ignored properties\n (requested by Ruslan M)\n[JACKSON-890]: Support managed/back-references for polymorphic (abstract) types\n- Add 'BeanPropertyWriter.isUnwrapping()' for future needs (by Afterburner)\n- Add coercions from String \"null\" (as if null token was parsed) for primitives/Wrappers.\n- Add `JsonDeserializer.handledType()`", "2.2.4 (10-Jun-2014)", "#292: Problems with abstract `Map`s, `Collection`s, polymorphic deserialization\n#324: EnumDeserializer should throw JsonMappingException, not IllegalArgumentException\n#346: Problems deserializing `ObjectNode` from empty JSON Object, with @JsonCreator", "2.2.3 (22-Aug-2013)", "#234: Problems with serializing types for deeply nested generic Maps, default typing \n#251: SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN ignored with JsonNode\n serialization\n (reported by fge@github)\n#259: Fix a problem with JSON Schema generation for `@JsonValue`\n (reported by Lior L)\n#267: Handle negative, stringified timestamps\n (reported by Drecth@github)\n#281: Make `NullNode` use configured null-value serializer\n#287: Fix problems with converters, Maps with Object values\n (reported by antubis@github)\n#288: Fix problem with serialization converters assigned with annotations\n (reported by cemo@github)", "2.2.2 (26-May-2013)", "#216: Problems with Android, 1.6-only types\n#217: JsonProcessingExceptions not all wrapped as expected\n (reported by karldmoore@github)\n#220: ContainerNode missing 'createNumber(BigInteger)'\n (reported by Pascal G)\n#223: Duplicated nulls with @JsonFormat(shape=Shape.ARRAY)\n (reported by lukegh@github)\n#226: Field mapping fail on deserialization to common referenced object when\n @JsonUnwrapped is used\n (reported by ikvia@github)\n#232: Converting bound BigDecimal value to tree fails with WRITE_BIGDECIMAL_AS_PLAIN\n (reported by celkings@github)\n- Minor fix to handle primitive types for key deserializer lookups\n- Add convenience method `MappingIterator.getCurrentLocation()`\n (suggested by Tomdz@github)", "2.2.1 (03-May-2013)", "#214: Problem with LICENSE, NOTICE, Android packaging\n (reported by thierryd@github)", "2.2.0 (22-Apr-2013)", "Fixes:", "#23: Fixing typing of root-level collections\n#118: JsonTypeInfo.as.EXTERNAL_PROPERTY not working correctly\n with missing type id, scalar types\n#130: TimeZone not set for GregorianCalendar, even if configured\n#144: MissingNode.isValueNode() should return 'false'\n (reported by 'fge@github')\n#146: Creator properties were not being renamed as expected\n (contributed by Christoper C)\n#188: Problem with ObjectId serialization, 'alwaysAsId' references", "Improvements:", "#116: JavaType implements `java.lang.reflect.Type` (as does `TypeReference`)\n#147: Defer reporting of problems with missing creator parameters\n (contributed by Christoper C)\n#155: Make `ObjectNode` and `ArrayNode` final (other node types already were)\n (requested by fge@github)\n#161: Add deserializer for java.util.concurrent.ArrayBlockingQueue\n#173: Add 'JsonNode.traverse(ObjectCodec)' for convenience\n#181: Improve error reporting for missing '_valueDeserializer'\n#194: Add `FloatNode` type in tree model (JsonNode)\n (requested by msteiger@github)\n#199: Allow deserializing `Iterable` instances (as basic `Collection`s)\n (requested by electrum@github)\n#206: Make 'ObjectMapper.createDeserializationContext()' overridable\n (requested by noter@github)\n#207: Add explicit support for `short` datatypes, for tree model\n (contributed by msteiger@github)", "New features:", "#120: Extend BeanDeserializerModifier to work with non-POJO deserializers\n#121: Extend BeanSerializerModifier to work with non-POJO serializers\n#124: Add support for serialization converters (@JsonSerializer(converter=...))\n#124: Add support for deserialization converters (@JsonDeserializer(converter=...))\n#140: Add 'SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN' to allow forcing\n of non-scientific notation when serializing BigDecimals.\n (suggested by phedny@github)\n#148: Add 'DeserializationFeature.FAIL_ON_INVALID_SUBTYPE`, which allows mapping\n entries with missing or invalid type id into null references (instead of failing).\n Also allows use of '@JsonTypeInfo.defaultImpl = NoClass.class' as alternative.\n#159: Add more accessors in 'MappingIterator': getParser(), getParserSchema(),\n readAll()\n (suggested by Tom D)\n#190: Add 'MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS' (default: true) for\n pruning out final fields (to avoid using as mutators)\n (requested by Eric T)\n#195: Add 'MapperFeature.INFER_PROPERTY_MUTATORS' (default: enabled) for finer\n control of what mutators are auto-detected.\n (requested by Dain S)\n#198: Add SPI metadata, handling in ObjectMapper (findModules()), for\n automatic registration of auto-detected extension modules\n (suggested by 'beamerblvd@github')\n#203: Added new features to support advanced date/time handling:\n - SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS\n - DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS\n - DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE", "Other:", "#126: Update JDK baseline to 1.6\n* API under 'com.fasterxml.jackson.databind.jsonFormatVisitors' changed significantly\n based on experiences with external JSON Schema generator.\n* Version information accessed via code-generated access class, instead of reading\n VERSION.txt\n* Added 2 methods in Converter interface: getInputType(), getOutputType(),\n to allow programmatic overrides (needed by JAXB annotation module)", "2.1.4 (26-Feb-2013)", "* [JACKSON-887]: StackOverflow with parameterized sub-class field\n (reported by Alexander M)\n* [#130]: TimeZone not set for GregorianCalendar, when deserializing\n* [#157]: NPE when registering module twice\n* [#162]: JsonNodeFactory: work around an old bug with BigDecimal and zero\n (submitted by fge@github)\n* [#166]: Incorrect optimization for `ObjectMapper.convertValue(Class)`\n (reported by Eric T)\n* [#167]: Problems with @JsonValue, polymorphic types (regression from 1.x)\n (reported by Eric T)\n* [#170]: Problems deserializing `java.io.File` if creator auto-discovery disabled\n (reported by Eric T)\n* [#175]: NPE for JsonMappingException, if no path is specified\n (reported by bramp@github)", "2.1.3 (19-Jan-2013)", "* [Issue#141]: ACCEPT_EMPTY_STRING_AS_NULL_OBJECT not working for enums\n* [Issue#142]: Serialization of class containing EnumMap with polymorphic enum\n fails to generate class type data\n (reported by kidavis4@github)", "2.1.2 (04-Dec-2012)", "* [Issue#106]: NPE in ObjectArraySerializer.createContextual(...)\n* [Issue#117]: HandlerInstantiator defaulting not working\n (reported by Alexander B)\n* [Issue#118]: Problems with JsonTypeInfo.As.EXTERNAL_PROPERTY, scalar values\n (reported by Adva11@github)\n* [Issue#119]: Problems with @JsonValue, JsonTypeInfo.As.EXTERNAL_PROPERTY\n (reported by Adva11@github)\n* [Issue#122]: ObjectMapper.copy() was not copying underlying mix-in map\n (reported by rzlo@github)", "2.1.1 (11-Nov-2012)", "Fixes:", "* [JACKSON-875]: Enum values not found if Feature.USE_ANNOTATIONS disabled\n (reported by Laurent P)\n* [Issue#93]: ObjectNode.setAll() broken; would not add anything for\n empty ObjectNodes.\n (reported by Francis G)\n* Making things implement java.io.Serializable:\n - Issues: #94, #99, #100, #102\n (reported by Sean B)\n* [Issue#96]: Problem with JsonTypeInfo.As.EXTERNAL_PROPERTY, defaultImpl\n (reported by Adva11@github)", "2.1.0 (08-Oct-2012)", " New minor version for 2.x series. Major improvements in multiple areas,\n including:", " - Dataformat auto-detection\n - More `@JsonFormat.shape` variant to serialize Collections as\n JSON Objects, POJOs as JSON Arrays (csv-like).\n - Much more configuration accessible via ObjectReader, ObjectWriter\n - New mechanism for JSON Schema generation, other uses (in future)", "Fixes:", "* [JACKSON-830]/[Issue#19]: Change OSGi bundle name to be fully-qualified\n* ]JACKSON-847]: Make @JsonIdentityInfo work with property-based creator\n* [JACKSON-851]: State corruption with ObjectWriter, DefaultPrettyPrinter\n (reported by Duncan A)\n* [Issue#75]: Too aggressive KeySerializer caching\n* Minor fix wrt [Issue#11], coercion needed extra checks", "Improvements:", "* [JACKSON-758]: Remove 'IOException' from throws clauses of \"writeValueAsString\"\n and \"writeValueAsBytes\" of ObjectMapper/ObjectWriter\n (suggested by G-T Chen)\n* [JACKSON-839]: Allow \"upgrade\" of integer number types for\n UntypedObjectDeserializer, even with default typing enabled.\n* [JACKSON-850]: Allow use of zero-arg factory methods as \"default creator\"\n (suggested by Razvan D)\n* [Issue#9]: Implement 'required' JSON Schema attribute for bean properties\n* [Issue#20]: Add new exception type, InvalidFormatException (sub-type of\n JsonMappingException) to indicate data format problems\n (suggested by HolySamosa@github)\n* [Issue#30]: ObjectReader and ObjectWriter now try to pre-fetch root\n (de)serializer if possible; minor performance improvement (2% for small POJOs).\n* [Issue#33]: Simplified/clarified definition of 'ObjectReader.readValues()';\n minor change in behavior for JSON Array \"wrapped\" sequences\n* [Issue#60]: Add 'JsonNode.hasNonNull(...)' method(s)\n (suggested by Jeff S on mailing list) \n* [Issue#64]: Add new \"standard\" PropertyNamingStrategy, PascalCaseStrategy\n (PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE)\n (contributed by Sean B)\n* [Issue#65]: Add getters to `ObjectMapper`, DeserializationContext/-Factory.\n (contributed by Dmitry K)\n* [Issue#69]: Add `PropertyName` abstraction, new methods in AnnotationIntrospector\n* [Issue#80]: Make `DecimalNode` normalize input, to make \"1.0\" and \"1.00\"equal\n (reported by fge@github)", "New features:", "* [Issue#15]: Support data format auto-detection via ObjectReader (added\n 'withFormatDetection(...)' fluent factories)\n* [Issue#21]: Add 'ObjectNode.set(...)' method (and related) to improve\n chaining, semantic consistency of Tree Model API\n (suggested by fge@Github)\n* [Issue#22]: Add 'ObjectMapper.setAnnotationIntrospectors()' which allows\n defining different introspectors for serialization, deserialization\n* [Issue#24]: Allow serialization of Enums as JSON Objects\n (suggested by rveloso@github)\n* [Issue#28]: Add 'ObjectMapper.copy()', to create non-linked copy of\n mapper, with same configuration settings\n* [Issue#29]: Allow serializing, deserializing POJOs as JSON Arrays\n by using `@JsonFormat(shape=Shape.ARRAY)`\n* [Issue#40]: Allow serialization of Collections as JSON Objects\n (and deserialization from)\n (suggested by 'rveloso@github')\n* [Issue#42]: Allow specifying Base64 variant to use for Base64-encoded data\n using ObjectReader.with(Base64Variant), ObjectWriter.with(Base64Variant).\n (suggested by 'mpfau@github')\n* [Issue#45]: Add '@JsonNaming' annotation to define per-class PropertyNamingStrategy\n (suggested by Mark W)\n* [Pull#58]: Make 'MappingIterator' implement 'Closable'\n (contributed by Pascal G)\n* [Issue#72]: Add 'MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME' to use\n wrapper name annotations for renaming properties\n* [Issue#87]: Add 'StdDelegatingSerializer', 'StdDelegatingDeserializer' to\n simplify writing of two-step handlers\n* (issue #4 of jackson-annotations): Add `@JsonIdentityReference(alwaysAsId=true)`\n to force ALL references to an object written as Object Id, even the first one.\n* Added 'ObjectReader#withHandler' to allow for reconfiguring deserialization\n problem handler\n (suggested by 'electricmonk')", "Other changes:", "* New variant of AnnotationIntrospector.getFormat(), to support class\n annotations\n* It is now possible to serialize instances of plain old Object, iff\n 'FAIL_ON_EMPTY_BEANS' is disabled.\n* Trying to remove reference to \"JSON\" in datatype conversion errors\n (since databinding is format-agnostic)", "INCOMPATIBILITIES: (rats!)", "* Note that [Issue#33] (see above) is, technically speaking, backwards\n imcompatible change. It is estimated that it should NOT affect most\n users, as changes are to edge cases (and undocumented ones at that).\n However, it can potentially cause problems with upgrade.\n* Implementation of `JsonFormatVisitable` resulting in 2 new methods\n being added in `BeanPropertyFilter` interface -- this is unfortunate,\n but was required to support full traversability.", "2.0.4 (26-Jun-2012)", "* [Issue#6]: element count for PrettyPrinter, endObject wrong\n (reported by \"thebluemountain\")\n* [JACKSON-838]: Utf8StreamParser._reportInvalidToken() skips letters\n from reported token name\n (reported by Lóránt Pintér)\n* [JACKSON-841] Data is doubled in SegmentedStringWriter output\n (reported by Scott S)\n* [JACKSON-842] ArrayIndexOutOfBoundsException when skipping C-style comments\n (reported by Sebastien R)", "2.0.3: no version 2.0.3 released -- only used for extension modules", "2.0.2 [14-May-2012]", "Fixes:", "* [Issue#14]: Annotations were not included from parent classes of\n mix-in classes\n (reported by @guillaup)\n* [JACKSON-824]: Combination of JSON Views, ObjectMapper.readerForUpdating()\n was not working\n (reported by Nir S)\n(and all fixes from 1.9.7)", "Improvements:", "* [Issue#11]: Improve ObjectMapper.convertValue()/.treeToValue() to use\n cast if possible", "2.0.1 [23-Apr-2012]", "Fixes:", "* [JACKSON-827] Ensure core packages work on JDK 1.5\n (reported by Pascal g)\n* [JACKSON-829] Custom serializers not working for List<String> properties,\n @JsonSerialize(contentUsing)\n (reported by James R)", "Improvements:", "* [Issue#5]: Add support for maps with java.util.Locale keys to the set of\n StdKeyDeserializers\n (contributed by Ryan G)", "2.0.0 [25-Mar-2012]", "Fixes:", "* [JACKSON-368]: Problems with managed references, abstract types\n* [JACKSON-711]: Delegating @JsonCreator did not work with Injectable values\n* [JACKSON-798]: Problem with external type id, creators\n (reported by Casey L)\n(and all fixes up until and including 1.9.6)", "Improvements:", "* [JACKSON-546]: Indicate end-of-input with JsonMappingException instead\n of EOFException, when there is no parsing exception\n* [JACKSON-664]: Reduce overhead of type resolution by adding caching\n in TypeFactory\n* [JACKSON-690]: Pass DeserializationContext through ValueInstantiator\n* [JACKSON-695]: Add 'isEmpty(value)' in JsonSerializer to allow\n customizing handling of serialization of empty values\n* [JACKSON-710]: 'ObjectMapper.convertValue()' should ignore root value\n wrapping/unwrapping settings\n* [JACKSON-730] Split various features (JsonParser, JsonGenerator,\n SerializationConfig, DeserializationConfig) into per-factory\n features (MapperFeature, JsonFactory.Feature) an per\n instance features (existing ones)\n* [JACKSON-732]: Allow 'AnnotationIntrospector.findContentDeserializer()'\n (and similar) to return instance, not just Class<?> for instance\n (requested by James R)\n* [JACKSON-736]: Add (more) access to array, container and map serializers\n* [JACKSON-737]: Allow accessing of \"creator properties\" for BeanDeserializer\n* [JACKSON-748]: Add 'registerSubtypes' to 'Module.setupContext' (and SimpleModule)\n* [JACKSON-749]: Make @JsonValue work for Enum deserialization\n* [JACKSON-769]: ObjectNode/ArrayNode: change 'put', 'insert', 'add' to return\n 'this node' (unless already returning something)\n* [JACKSON-770]: Simplify method naming for JsonNode, drop unnecessary 'get' prefix\n from methods like 'getTextValue()' (becomes 'textValue()')\n* [JACKSON-777]: Rename 'SerializationConfig.Feature' as 'SerializationFeature',\n 'DeserializationConfig.Feature' as 'DeserializationFeature'\n* [JACKSON-780]: MissingNode, NullNode should return 'defaultValue' from 'asXxx' methods,\n (not 0 for numbers), as they are not numeric types\n* [JACKSON-787]: Allow use of @JsonIgnoreProperties for properties (fields, getters, setters)\n* [JACKSON-795]: @JsonValue was not working for Maps, Collections\n* [JACKSON-800]: Add 'Module.SetupContext#addDeserializationProblemHandler'\n (suggested by James R)", "New features:", "* [JACKSON-107]: Add support for Object Identity (to handled cycles, shared refs),\n with @JsonIdentityInfo\n* [JACKSON-435]: Allow per-property Date formatting using @JsonFormat.\n* [JACKSON-437]: Allow injecting of type id as POJO property, by setting\n new '@JsonTypeInfo.visible' property to true.\n* [JACKSON-469]: Support \"Builder pattern\" for deserialiation; that is, allow\n use of separate Builder object for data binding, creating actual value\n* [JACKSON-608]: Allow use of JSON Views for deserialization\n* [JACKSON-636]: Add 'SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS' to allow\n forced sorting of Maps during serialization\n (suggested by Joern H)\n* [JACKSON-669]: Allow prefix/suffix for @JsonUnwrapped properties\n (requested by Aner P)\n* [JACKSON-707]: Add 'JsonNode.deepCopy()', to create safe deep copies\n of ObjectNodes, ArrayNodes.\n* [JACKSON-714]: Add general-purpose @JsonFormat annotation\n* [JACKSON-718]: Added 'JsonNode.canConvertToInt()', 'JsonNode.canConvertToLong()'\n* [JACKSON-747]: Allow changing of 'SerializationFeature' for ObjectWriter,\n 'DeserializationFeature' for ObjectReader.\n* [JACKSON-752]: Add @JsonInclude (replacement of @JsonSerialize.include)\n* [JACKSON-754]: Add @JacksonAnnotationsInside for creating \"annotation\n bundles\" (also: AnnotationIntrospector.isAnnotationBundle())\n* [JACKSON-762]: Allow using @JsonTypeId to specify property to use as\n type id, instead of using separate type id resolver.\n* [JACKSON-764]: Allow specifying \"root name\" to use for root wrapping\n via ObjectReader, ObjectWriter.\n* [JACKSON-772]: Add 'JsonNode.withArray()' to use for traversing Array nodes.\n* [JACKSON-793]: Add support for configurable Locale, TimeZone to use\n (via SerializationConfig, DeserializationConfig)\n* [JACKSON-805]: Add 'SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED'\n to improve interoperability with BadgerFish/Jettison\n* [JACKSON-810]: Deserialization Feature: Allow unknown Enum values via\n 'DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL'\n (suggested by Raymond R)\n* [JACKSON-813]: Add '@JsonSerializableSchema.id' attribute, to indicate\n 'id' value to add to generated JSON Schemas.", "[entries for versions 1.x and earlier not retained; refer to earlier releases)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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": [8, 69], "buggy_code_start_loc": [7, 69], "filenames": ["release-notes/VERSION", "src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializerFactory.java"], "fixing_code_end_loc": [12, 76], "fixing_code_start_loc": [8, 70], "message": "FasterXML jackson-databind 2.x before 2.9.7 might allow remote attackers to execute arbitrary code by leveraging failure to block the blaze-ds-opt and blaze-ds-core classes from polymorphic deserialization.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "A1BA8F04-46A7-4804-A997-59080034013F", "versionEndExcluding": "2.6.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.6.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "B99066EB-FF79-4D9D-9466-B04AD4D3A814", "versionEndExcluding": "2.7.9.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4D3858C-DAF3-4522-90EC-EFCD13BD121E", "versionEndExcluding": "2.8.11.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "4DA01839-5250-43A7-AFB7-871DC9B8AB32", "versionEndExcluding": "2.9.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.9.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"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}, {"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:banking_platform:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "35AD0C07-9688-4397-8D45-FBB88C0F0C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.0:*:*:*:*:*:*:*", "matchCriteriaId": "8972497F-6E24-45A9-9A18-EB0E842CB1D4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.1:*:*:*:*:*:*:*", "matchCriteriaId": "400509A8-D6F2-432C-A2F1-AD5B8778D0D9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.2:*:*:*:*:*:*:*", "matchCriteriaId": "132CE62A-FBFC-4001-81EC-35D81F73AF48", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:business_process_management_suite:12.1.3.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "B887E174-57AB-449D-AEE4-82DD1A3E5C84", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:business_process_management_suite:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "E869C417-C0E6-4FC3-B406-45598A1D1906", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:clusterware:12.1.0.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "6C9084DB-329E-403F-8D0A-5B9F53183714", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_billing_and_revenue_management:7.5:*:*:*:*:*:*:*", "matchCriteriaId": "E6039DC7-08F2-4DD9-B5B5-B6B22DD2409F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_billing_and_revenue_management:12.0:*:*:*:*:*:*:*", "matchCriteriaId": "7231AF76-3D46-41C4-83E9-6E9E12940BD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:11.2.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "C1E11A25-C7CE-49DF-99CA-352FD21B8230", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:12.1.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "4F3D40B7-925C-413D-AFF3-60BF330D5BC2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:12.2.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "5C614BA7-7103-4ED7-ADD0-56064FE256A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:18c:*:*:*:*:*:*:*", "matchCriteriaId": "6833701E-5510-4180-9523-9CFD318DEE6A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:19c:*:*:*:*:*:*:*", "matchCriteriaId": "B2204841-585F-40C7-A1D9-C34E612808CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "A9E97F04-00ED-48E9-AB40-7A02B3419641", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "FCCE5A11-39E7-4BBB-9E1A-BA4B754103BB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "A5AEC7F5-C353-4CF5-96CE-8C713A2B0C92", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "BB79BB43-E0AB-4F0D-A6EA-000485757EEC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "F238CB66-886D-47E8-8DC0-7FC2025771EB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "59B7B8AD-1210-4C40-8EF7-E2E8156630A1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "0DE4A291-4358-42A9-A68D-E59D9998A1CC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "0D19CF00-FE20-4690-AAB7-8E9DBC68A94F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "A030A498-3361-46F8-BB99-24A66CAE11CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "F6455EB1-C741-45E8-A53E-E7AD7A5D00EE", "versionEndExcluding": "11.2.0.3.23", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "BFD43191-E67F-4D1B-967B-3C7B20331945", "versionEndExcluding": "12.2.0.1.19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "12.2.0.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "062C588A-CBBA-470F-8D11-2F961922E927", "versionEndExcluding": "13.9.4.2.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "13.9.4.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jdeveloper:12.1.3.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "042C243F-EDFE-4A04-AB0B-26E73CC34837", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jdeveloper:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "228DA523-4D6D-48C5-BDB0-DB1A60F23F8B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A1E1023-2EB9-4334-9B74-CA71480F71C2", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "93A4E178-0082-45C5-BBC0-0A4E51C8B1DE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:15.2:*:*:*:*:*:*:*", "matchCriteriaId": "3F021C23-AB9B-4877-833F-D01359A98762", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:16.1:*:*:*:*:*:*:*", "matchCriteriaId": "2F8ED016-32A1-42EE-844E-3E6B2C116B74", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:16.2:*:*:*:*:*:*:*", "matchCriteriaId": "A046CC2C-445F-4336-8810-930570B4FEC6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "0745445C-EC43-4091-BA7C-5105AFCC6F1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:*:*:*:*:*:*:*:*", "matchCriteriaId": "08FA59A8-6A62-4B33-8952-D6E658F8DAC9", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:16.1:*:*:*:*:*:*:*", "matchCriteriaId": "D55A54FD-7DD1-49CD-BE81-0BE73990943C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:16.2:*:*:*:*:*:*:*", "matchCriteriaId": "82EB08C0-2D46-4635-88DF-E54F6452D3A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "202AD518-2E9B-4062-B063-9858AE1F9CE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_merchandising_system:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "792DF04A-2D1B-40B5-B960-3E7152732EB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_merchandising_system:16.0:*:*:*:*:*:*:*", "matchCriteriaId": "46525CA6-4226-4F6F-B899-D800D4DDE0B5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_workforce_management_software:1.60.9.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "9967AAFD-2199-4668-9105-207D4866B707", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:webcenter_portal:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "D6A4F71A-4269-40FC-8F61-1D1301F2B728", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "3A76E5BF-01E4-46E7-8E3B-5ACE75657360", "versionEndExcluding": "3.11.153", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.11", "vulnerable": true}, {"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "E9A6D103-9674-4B04-8397-86501F1D91CF", "versionEndExcluding": "4.6.26", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.6", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "D2452F48-6A8B-4274-B0CE-F1256F400170", "versionEndExcluding": "4.1.18", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.1", "vulnerable": true}], "negate": false, "operator": "OR"}, {"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": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"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}, {"criteria": "cpe:2.3:a:netapp:snapcenter:-:*:*:*:*:*:*:*", "matchCriteriaId": "BDFB1169-41A0-4A86-8E4F-FDA9730B1E94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:netapp:steelstore_cloud_integrated_storage:*:*:*:*:*:*:*:*", "matchCriteriaId": "09A8C9D2-9FFF-4312-95FB-87D79B3C0339", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "FasterXML jackson-databind 2.x before 2.9.7 might allow remote attackers to execute arbitrary code by leveraging failure to block the blaze-ds-opt and blaze-ds-core classes from polymorphic deserialization."}, {"lang": "es", "value": "Las versiones 2.x de FasterXML jackson-databind anteriores a la 2.9.7 podr\u00edan permitir a los atacantes remotos ejecutar c\u00f3digo arbitrario aprovechando un fallo para bloquear las clases blaze-ds-opt y blaze-ds-core de deserializaci\u00f3n polim\u00f3rfica."}], "evaluatorComment": null, "id": "CVE-2018-14719", "lastModified": "2021-05-21T15:22:43.047", "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": "2019-01-02T18:29:00.387", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHBA-2019:0959"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:0782"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:0877"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1782"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1797"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1822"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1823"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:2804"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:2858"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3002"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3140"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3149"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3892"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:4037"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson-databind/commit/87d29af25e82a249ea15858e2d4ecbf64091db44"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson-databind/issues/2097"}, {"source": "cve@mitre.org", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.9.7"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/519eb0fd45642dcecd9ff74cb3e71c20a4753f7d82e2f07864b5108f@%3Cdev.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/b0656d359c7d40ec9f39c8cc61bca66802ef9a2a12ee199f5b0c1442@%3Cdev.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/f9bc3e55f4e28d1dcd1a69aae6d53e609a758e34d2869b4d798e13cc@%3Cissues.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ff8dcfe29377088ab655fda9d585dccd5b1f07fabd94ae84fd60a7f8@%3Ccommits.pulsar.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf1bbc0ea4a9f014cf94df9a12a6477d24a27f52741dbc87f2fd52ff2@%3Cissues.geode.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/03/msg00005.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Mailing List", "Third Party Advisory"], "url": "https://seclists.org/bugtraq/2019/May/68"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20190530-0003/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2019/dsa-4452"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2020.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpuapr2019-5072813.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpujan2019-5072801.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpujul2019-5072835.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpuoct2019-5072832.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/FasterXML/jackson-databind/commit/87d29af25e82a249ea15858e2d4ecbf64091db44"}, "type": "CWE-502"}
245
Determine whether the {function_name} code is vulnerable or not.
[ "package com.fasterxml.jackson.databind.deser;", "import java.lang.reflect.Type;\nimport java.util.*;", "import com.fasterxml.jackson.annotation.ObjectIdGenerator;\nimport com.fasterxml.jackson.annotation.ObjectIdGenerators;\nimport com.fasterxml.jackson.annotation.ObjectIdResolver;\nimport com.fasterxml.jackson.databind.*;\nimport com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;\nimport com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig;\nimport com.fasterxml.jackson.databind.deser.impl.*;\nimport com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer;\nimport com.fasterxml.jackson.databind.introspect.*;\nimport com.fasterxml.jackson.databind.jsontype.TypeDeserializer;\nimport com.fasterxml.jackson.databind.util.ArrayBuilders;\nimport com.fasterxml.jackson.databind.util.ClassUtil;\nimport com.fasterxml.jackson.databind.util.SimpleBeanPropertyDefinition;", "/**\n * Concrete deserializer factory class that adds full Bean deserializer\n * construction logic using class introspection.\n * Note that factories specifically do not implement any form of caching:\n * aside from configuration they are stateless; caching is implemented\n * by other components.\n *<p>\n * Instances of this class are fully immutable as all configuration is\n * done by using \"fluent factories\" (methods that construct new factory\n * instances with different configuration, instead of modifying instance).\n */\npublic class BeanDeserializerFactory\n extends BasicDeserializerFactory\n implements java.io.Serializable // since 2.1\n{\n private static final long serialVersionUID = 1;", " /**\n * Signature of <b>Throwable.initCause</b> method.\n */\n private final static Class<?>[] INIT_CAUSE_PARAMS = new Class<?>[] { Throwable.class };", " private final static Class<?>[] NO_VIEWS = new Class<?>[0];", " /**\n * Set of well-known \"nasty classes\", deserialization of which is considered dangerous\n * and should (and is) prevented by default.\n */\n private final static Set<String> DEFAULT_NO_DESER_CLASS_NAMES;\n static {\n Set<String> s = new HashSet<String>();\n // Courtesy of [https://github.com/kantega/notsoserial]:\n // (and wrt [databind#1599])\n s.add(\"org.apache.commons.collections.functors.InvokerTransformer\");\n s.add(\"org.apache.commons.collections.functors.InstantiateTransformer\");\n s.add(\"org.apache.commons.collections4.functors.InvokerTransformer\");\n s.add(\"org.apache.commons.collections4.functors.InstantiateTransformer\");\n s.add(\"org.codehaus.groovy.runtime.ConvertedClosure\");\n s.add(\"org.codehaus.groovy.runtime.MethodClosure\");\n s.add(\"org.springframework.beans.factory.ObjectFactory\");\n s.add(\"com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl\");", " // [databind#1737]; JDK provided\n s.add(\"java.util.logging.FileHandler\");\n s.add(\"java.rmi.server.UnicastRemoteObject\");\n // [databind#1737]; 3rd party\n s.add(\"org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor\");\n s.add(\"org.springframework.beans.factory.config.PropertyPathFactoryBean\");\n s.add(\"com.mchange.v2.c3p0.JndiRefForwardingDataSource\");\n s.add(\"com.mchange.v2.c3p0.WrapperConnectionPoolDataSource\");", "", "\n DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s);\n }", " /**\n * Set of class names of types that are never to be deserialized.\n */\n private Set<String> _cfgIllegalClassNames = DEFAULT_NO_DESER_CLASS_NAMES;", " /*\n /**********************************************************\n /* Life-cycle\n /**********************************************************\n */\n \n /**\n * Globally shareable thread-safe instance which has no additional custom deserializers\n * registered\n */\n public final static BeanDeserializerFactory instance = new BeanDeserializerFactory(\n new DeserializerFactoryConfig());", " public BeanDeserializerFactory(DeserializerFactoryConfig config) {\n super(config);\n }\n \n /**\n * Method used by module registration functionality, to construct a new bean\n * deserializer factory\n * with different configuration settings.\n */\n @Override\n public DeserializerFactory withConfig(DeserializerFactoryConfig config)\n {\n if (_factoryConfig == config) {\n return this;\n }\n /* 22-Nov-2010, tatu: Handling of subtypes is tricky if we do immutable-with-copy-ctor;\n * and we pretty much have to here either choose between losing subtype instance\n * when registering additional deserializers, or losing deserializers.\n * Instead, let's actually just throw an error if this method is called when subtype\n * has not properly overridden this method; this to indicate problem as soon as possible.\n */\n if (getClass() != BeanDeserializerFactory.class) {\n throw new IllegalStateException(\"Subtype of BeanDeserializerFactory (\"+getClass().getName()\n +\") has not properly overridden method 'withAdditionalDeserializers': can not instantiate subtype with \"\n +\"additional deserializer definitions\");\n }\n return new BeanDeserializerFactory(config);\n }\n \n /*\n /**********************************************************\n /* DeserializerFactory API implementation\n /**********************************************************\n */", " /**\n * Method that {@link DeserializerCache}s call to create a new\n * deserializer for types other than Collections, Maps, arrays and\n * enums.\n */\n @Override\n public JsonDeserializer<Object> createBeanDeserializer(DeserializationContext ctxt,\n JavaType type, BeanDescription beanDesc)\n throws JsonMappingException\n {\n final DeserializationConfig config = ctxt.getConfig();\n // We may also have custom overrides:\n JsonDeserializer<Object> custom = _findCustomBeanDeserializer(type, config, beanDesc);\n if (custom != null) {\n return custom;\n }\n /* One more thing to check: do we have an exception type\n * (Throwable or its sub-classes)? If so, need slightly\n * different handling.\n */\n if (type.isThrowable()) {\n return buildThrowableDeserializer(ctxt, type, beanDesc);\n }\n /* Or, for abstract types, may have alternate means for resolution\n * (defaulting, materialization)\n */\n if (type.isAbstract()) {\n // [JACKSON-41] (v1.6): Let's make it possible to materialize abstract types.\n JavaType concreteType = materializeAbstractType(ctxt, type, beanDesc);\n if (concreteType != null) {\n /* important: introspect actual implementation (abstract class or\n * interface doesn't have constructors, for one)\n */\n beanDesc = config.introspect(concreteType);\n return buildBeanDeserializer(ctxt, concreteType, beanDesc);\n }\n }", " // Otherwise, may want to check handlers for standard types, from superclass:\n @SuppressWarnings(\"unchecked\")\n JsonDeserializer<Object> deser = (JsonDeserializer<Object>) findStdDeserializer(ctxt, type, beanDesc);\n if (deser != null) {\n return deser;\n }", " // Otherwise: could the class be a Bean class? If not, bail out\n if (!isPotentialBeanType(type.getRawClass())) {\n return null;\n }\n // For checks like [databind#1599]\n checkIllegalTypes(ctxt, type, beanDesc);\n // Use generic bean introspection to build deserializer\n return buildBeanDeserializer(ctxt, type, beanDesc);\n }", " @Override\n public JsonDeserializer<Object> createBuilderBasedDeserializer(\n \t\tDeserializationContext ctxt, JavaType valueType, BeanDescription beanDesc,\n \t\tClass<?> builderClass)\n throws JsonMappingException\n {\n \t// First: need a BeanDescription for builder class\n \tJavaType builderType = ctxt.constructType(builderClass);\n \tBeanDescription builderDesc = ctxt.getConfig().introspectForBuilder(builderType);\n \treturn buildBuilderBasedDeserializer(ctxt, valueType, builderDesc);\n }\n \n /**\n * Method called by {@link BeanDeserializerFactory} to see if there might be a standard\n * deserializer registered for given type.\n */\n protected JsonDeserializer<?> findStdDeserializer(DeserializationContext ctxt,\n JavaType type, BeanDescription beanDesc)\n throws JsonMappingException\n {\n // note: we do NOT check for custom deserializers here, caller has already\n // done that\n JsonDeserializer<?> deser = findDefaultDeserializer(ctxt, type, beanDesc);\n // Also: better ensure these are post-processable?\n if (deser != null) {\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n deser = mod.modifyDeserializer(ctxt.getConfig(), beanDesc, deser);\n }\n }\n }\n return deser;\n }\n \n protected JavaType materializeAbstractType(DeserializationContext ctxt,\n JavaType type, BeanDescription beanDesc)\n throws JsonMappingException\n {\n final JavaType abstractType = beanDesc.getType();\n // [JACKSON-502]: Now it is possible to have multiple resolvers too,\n // as they are registered via module interface.\n for (AbstractTypeResolver r : _factoryConfig.abstractTypeResolvers()) {\n JavaType concrete = r.resolveAbstractType(ctxt.getConfig(), abstractType);\n if (concrete != null) {\n return concrete;\n }\n }\n return null;\n }\n \n /*\n /**********************************************************\n /* Public construction method beyond DeserializerFactory API:\n /* can be called from outside as well as overridden by\n /* sub-classes\n /**********************************************************\n */", " /**\n * Method that is to actually build a bean deserializer instance.\n * All basic sanity checks have been done to know that what we have\n * may be a valid bean type, and that there are no default simple\n * deserializers.\n */\n @SuppressWarnings(\"unchecked\")\n public JsonDeserializer<Object> buildBeanDeserializer(DeserializationContext ctxt,\n JavaType type, BeanDescription beanDesc)\n throws JsonMappingException\n {\n // First: check what creators we can use, if any\n ValueInstantiator valueInstantiator;\n /* 04-Jun-2015, tatu: To work around [databind#636], need to catch the\n * issue, defer; this seems like a reasonable good place for now.\n * Note, however, that for non-Bean types (Collections, Maps) this\n * probably won't work and needs to be added elsewhere.\n */\n try {\n valueInstantiator = findValueInstantiator(ctxt, beanDesc);\n } catch (NoClassDefFoundError error) {\n return new NoClassDefFoundDeserializer<Object>(error);\n }\n BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, beanDesc);\n builder.setValueInstantiator(valueInstantiator);\n // And then setters for deserializing from JSON Object\n addBeanProps(ctxt, beanDesc, builder);\n addObjectIdReader(ctxt, beanDesc, builder);", " // managed/back reference fields/setters need special handling... first part\n addReferenceProperties(ctxt, beanDesc, builder);\n addInjectables(ctxt, beanDesc, builder);\n \n final DeserializationConfig config = ctxt.getConfig();\n // [JACKSON-440]: update builder now that all information is in?\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n builder = mod.updateBuilder(config, beanDesc, builder);\n }\n }\n JsonDeserializer<?> deserializer;", " /* 19-Mar-2012, tatu: This check used to be done earlier; but we have to defer\n * it a bit to collect information on ObjectIdReader, for example.\n */\n if (type.isAbstract() && !valueInstantiator.canInstantiate()) {\n deserializer = builder.buildAbstract();\n } else {\n deserializer = builder.build();\n }", " // [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built:\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n deserializer = mod.modifyDeserializer(config, beanDesc, deserializer);\n }\n }\n return (JsonDeserializer<Object>) deserializer;\n }\n \n /**\n * Method for constructing a bean deserializer that uses specified\n * intermediate Builder for binding data, and construction of the\n * value instance.\n * Note that implementation is mostly copied from the regular\n * BeanDeserializer build method.\n */\n @SuppressWarnings(\"unchecked\")\n protected JsonDeserializer<Object> buildBuilderBasedDeserializer(\n \t\tDeserializationContext ctxt, JavaType valueType, BeanDescription builderDesc)\n throws JsonMappingException\n {\n \t// Creators, anyone? (to create builder itself)\n ValueInstantiator valueInstantiator = findValueInstantiator(ctxt, builderDesc);\n final DeserializationConfig config = ctxt.getConfig();\n BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, builderDesc);\n builder.setValueInstantiator(valueInstantiator);\n // And then \"with methods\" for deserializing from JSON Object\n addBeanProps(ctxt, builderDesc, builder);\n addObjectIdReader(ctxt, builderDesc, builder);\n \n // managed/back reference fields/setters need special handling... first part\n addReferenceProperties(ctxt, builderDesc, builder);\n addInjectables(ctxt, builderDesc, builder);", " JsonPOJOBuilder.Value builderConfig = builderDesc.findPOJOBuilderConfig();\n final String buildMethodName = (builderConfig == null) ?\n \"build\" : builderConfig.buildMethodName;\n \n // and lastly, find build method to use:\n AnnotatedMethod buildMethod = builderDesc.findMethod(buildMethodName, null);\n if (buildMethod != null) { // note: can't yet throw error; may be given build method\n if (config.canOverrideAccessModifiers()) {\n \tClassUtil.checkAndFixAccess(buildMethod.getMember());\n }\n }\n builder.setPOJOBuilder(buildMethod, builderConfig);\n // this may give us more information...\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n builder = mod.updateBuilder(config, builderDesc, builder);\n }\n }\n JsonDeserializer<?> deserializer = builder.buildBuilderBased(\n \t\tvalueType, buildMethodName);", " // [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built:\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n deserializer = mod.modifyDeserializer(config, builderDesc, deserializer);\n }\n }\n return (JsonDeserializer<Object>) deserializer;\n }\n \n protected void addObjectIdReader(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder)\n throws JsonMappingException\n {\n ObjectIdInfo objectIdInfo = beanDesc.getObjectIdInfo();\n if (objectIdInfo == null) {\n return;\n }\n Class<?> implClass = objectIdInfo.getGeneratorType();\n JavaType idType;\n SettableBeanProperty idProp;\n ObjectIdGenerator<?> gen;", " ObjectIdResolver resolver = ctxt.objectIdResolverInstance(beanDesc.getClassInfo(), objectIdInfo);", " // Just one special case: Property-based generator is trickier\n if (implClass == ObjectIdGenerators.PropertyGenerator.class) { // most special one, needs extra work\n PropertyName propName = objectIdInfo.getPropertyName();\n idProp = builder.findProperty(propName);\n if (idProp == null) {\n throw new IllegalArgumentException(\"Invalid Object Id definition for \"\n +beanDesc.getBeanClass().getName()+\": can not find property with name '\"+propName+\"'\");\n }\n idType = idProp.getType();\n gen = new PropertyBasedObjectIdGenerator(objectIdInfo.getScope());\n } else {\n JavaType type = ctxt.constructType(implClass);\n idType = ctxt.getTypeFactory().findTypeParameters(type, ObjectIdGenerator.class)[0];\n idProp = null;\n gen = ctxt.objectIdGeneratorInstance(beanDesc.getClassInfo(), objectIdInfo);\n }\n // also: unlike with value deserializers, let's just resolve one we need here\n JsonDeserializer<?> deser = ctxt.findRootValueDeserializer(idType);\n builder.setObjectIdReader(ObjectIdReader.construct(idType,\n objectIdInfo.getPropertyName(), gen, deser, idProp, resolver));\n }\n \n @SuppressWarnings(\"unchecked\")\n public JsonDeserializer<Object> buildThrowableDeserializer(DeserializationContext ctxt,\n JavaType type, BeanDescription beanDesc)\n throws JsonMappingException\n {\n final DeserializationConfig config = ctxt.getConfig();\n // first: construct like a regular bean deserializer...\n BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, beanDesc);\n builder.setValueInstantiator(findValueInstantiator(ctxt, beanDesc));", " addBeanProps(ctxt, beanDesc, builder);\n // (and assume there won't be any back references)", " // But then let's decorate things a bit\n /* To resolve [JACKSON-95], need to add \"initCause\" as setter\n * for exceptions (sub-classes of Throwable).\n */\n AnnotatedMethod am = beanDesc.findMethod(\"initCause\", INIT_CAUSE_PARAMS);\n if (am != null) { // should never be null\n SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(ctxt.getConfig(), am,\n new PropertyName(\"cause\"));\n SettableBeanProperty prop = constructSettableProperty(ctxt, beanDesc, propDef,\n am.getGenericParameterType(0));\n if (prop != null) {\n /* 21-Aug-2011, tatus: We may actually have found 'cause' property\n * to set (with new 1.9 code)... but let's replace it just in case,\n * otherwise can end up with odd errors.\n */\n builder.addOrReplaceProperty(prop, true);\n }\n }", " // And also need to ignore \"localizedMessage\"\n builder.addIgnorable(\"localizedMessage\");\n // [JACKSON-794]: JDK 7 also added \"getSuppressed\", skip if we have such data:\n builder.addIgnorable(\"suppressed\");\n /* As well as \"message\": it will be passed via constructor,\n * as there's no 'setMessage()' method\n */\n builder.addIgnorable(\"message\");", " // [JACKSON-440]: update builder now that all information is in?\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n builder = mod.updateBuilder(config, beanDesc, builder);\n }\n }\n JsonDeserializer<?> deserializer = builder.build();\n \n /* At this point it ought to be a BeanDeserializer; if not, must assume\n * it's some other thing that can handle deserialization ok...\n */\n if (deserializer instanceof BeanDeserializer) {\n deserializer = new ThrowableDeserializer((BeanDeserializer) deserializer);\n }", " // [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built:\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n deserializer = mod.modifyDeserializer(config, beanDesc, deserializer);\n }\n }\n return (JsonDeserializer<Object>) deserializer;\n }", " /*\n /**********************************************************\n /* Helper methods for Bean deserializer construction,\n /* overridable by sub-classes\n /**********************************************************\n */", " /**\n * Overridable method that constructs a {@link BeanDeserializerBuilder}\n * which is used to accumulate information needed to create deserializer\n * instance.\n */\n protected BeanDeserializerBuilder constructBeanDeserializerBuilder(DeserializationContext ctxt,\n BeanDescription beanDesc) {\n return new BeanDeserializerBuilder(beanDesc, ctxt.getConfig());\n }\n \n /**\n * Method called to figure out settable properties for the\n * bean deserializer to use.\n *<p>\n * Note: designed to be overridable, and effort is made to keep interface\n * similar between versions.\n */\n protected void addBeanProps(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder)\n throws JsonMappingException\n {\n final SettableBeanProperty[] creatorProps =\n builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig());\n final boolean isConcrete = !beanDesc.getType().isAbstract();\n \n // Things specified as \"ok to ignore\"? [JACKSON-77]\n AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();\n boolean ignoreAny = false;\n {\n Boolean B = intr.findIgnoreUnknownProperties(beanDesc.getClassInfo());\n if (B != null) {\n ignoreAny = B.booleanValue();\n builder.setIgnoreUnknownProperties(ignoreAny);\n }\n }\n // Or explicit/implicit definitions?\n Set<String> ignored = ArrayBuilders.arrayToSet(intr.findPropertiesToIgnore(beanDesc.getClassInfo(), false)); \n for (String propName : ignored) {\n builder.addIgnorable(propName);\n }\n // Also, do we have a fallback \"any\" setter?\n AnnotatedMethod anySetter = beanDesc.findAnySetter();\n if (anySetter != null) {\n builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetter));\n }\n // NOTE: we do NOT add @JsonIgnore'd properties into blocked ones if there's any-setter\n // Implicit ones via @JsonIgnore and equivalent?\n if (anySetter == null) {\n Collection<String> ignored2 = beanDesc.getIgnoredPropertyNames();\n if (ignored2 != null) {\n for (String propName : ignored2) {\n // allow ignoral of similarly named JSON property, but do not force;\n // latter means NOT adding this to 'ignored':\n builder.addIgnorable(propName);\n }\n }\n }\n final boolean useGettersAsSetters = (ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)\n && ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));", " // Ok: let's then filter out property definitions\n List<BeanPropertyDefinition> propDefs = filterBeanProps(ctxt,\n beanDesc, builder, beanDesc.findProperties(), ignored);", " // After which we can let custom code change the set\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);\n }\n }\n \n // At which point we still have all kinds of properties; not all with mutators:\n for (BeanPropertyDefinition propDef : propDefs) {\n SettableBeanProperty prop = null;\n /* 18-Oct-2013, tatu: Although constructor parameters have highest precedence,\n * we need to do linkage (as per [Issue#318]), and so need to start with\n * other types, and only then create constructor parameter, if any.\n */\n if (propDef.hasSetter()) {\n Type propertyType = propDef.getSetter().getGenericParameterType(0);\n prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);\n } else if (propDef.hasField()) {\n Type propertyType = propDef.getField().getGenericType();\n prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);\n } else if (useGettersAsSetters && propDef.hasGetter()) {\n /* As per [JACKSON-88], may also need to consider getters\n * for Map/Collection properties; but with lowest precedence\n */\n AnnotatedMethod getter = propDef.getGetter();\n // should only consider Collections and Maps, for now?\n Class<?> rawPropertyType = getter.getRawType();\n if (Collection.class.isAssignableFrom(rawPropertyType)\n || Map.class.isAssignableFrom(rawPropertyType)) {\n prop = constructSetterlessProperty(ctxt, beanDesc, propDef);\n }\n }\n // 25-Sep-2014, tatu: No point in finding constructor parameters for abstract types\n // (since they are never used anyway)\n if (isConcrete && propDef.hasConstructorParameter()) {\n /* [JACKSON-700] If property is passed via constructor parameter, we must\n * handle things in special way. Not sure what is the most optimal way...\n * for now, let's just call a (new) method in builder, which does nothing.\n */\n // but let's call a method just to allow custom builders to be aware...\n final String name = propDef.getName();\n CreatorProperty cprop = null;\n if (creatorProps != null) {\n for (SettableBeanProperty cp : creatorProps) {\n if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {\n cprop = (CreatorProperty) cp;\n break;\n }\n }\n }\n if (cprop == null) {\n throw ctxt.mappingException(\"Could not find creator property with name '%s' (in class %s)\",\n name, beanDesc.getBeanClass().getName());\n }\n if (prop != null) {\n cprop.setFallbackSetter(prop);\n }\n prop = cprop;\n builder.addCreatorProperty(cprop);\n continue;\n }", " if (prop != null) {\n Class<?>[] views = propDef.findViews();\n if (views == null) {\n // one more twist: if default inclusion disabled, need to force empty set of views\n if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) {\n views = NO_VIEWS;\n }\n }\n // one more thing before adding to builder: copy any metadata\n prop.setViews(views);\n builder.addProperty(prop);\n }\n }\n }\n \n /**\n * Helper method called to filter out explicit ignored properties,\n * as well as properties that have \"ignorable types\".\n * Note that this will not remove properties that have no\n * setters.\n */\n protected List<BeanPropertyDefinition> filterBeanProps(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder,\n List<BeanPropertyDefinition> propDefsIn,\n Set<String> ignored)\n throws JsonMappingException\n {\n ArrayList<BeanPropertyDefinition> result = new ArrayList<BeanPropertyDefinition>(\n Math.max(4, propDefsIn.size()));\n HashMap<Class<?>,Boolean> ignoredTypes = new HashMap<Class<?>,Boolean>();\n // These are all valid setters, but we do need to introspect bit more\n for (BeanPropertyDefinition property : propDefsIn) {\n String name = property.getName();\n if (ignored.contains(name)) { // explicit ignoral using @JsonIgnoreProperties needs to block entries\n continue;\n }\n if (!property.hasConstructorParameter()) { // never skip constructor params\n Class<?> rawPropertyType = null;\n if (property.hasSetter()) {\n rawPropertyType = property.getSetter().getRawParameterType(0);\n } else if (property.hasField()) {\n rawPropertyType = property.getField().getRawType();\n }", " // [JACKSON-429] Some types are declared as ignorable as well\n if ((rawPropertyType != null)\n && (isIgnorableType(ctxt.getConfig(), beanDesc, rawPropertyType, ignoredTypes))) {\n // important: make ignorable, to avoid errors if value is actually seen\n builder.addIgnorable(name);\n continue;\n }\n }\n result.add(property);\n }\n return result;\n }\n \n /**\n * Method that will find if bean has any managed- or back-reference properties,\n * and if so add them to bean, to be linked during resolution phase.\n */\n protected void addReferenceProperties(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder)\n throws JsonMappingException\n {\n // and then back references, not necessarily found as regular properties\n Map<String,AnnotatedMember> refs = beanDesc.findBackReferenceProperties();\n if (refs != null) {\n for (Map.Entry<String, AnnotatedMember> en : refs.entrySet()) {\n String name = en.getKey();\n AnnotatedMember m = en.getValue();\n Type genericType;\n if (m instanceof AnnotatedMethod) {\n genericType = ((AnnotatedMethod) m).getGenericParameterType(0);\n } else {\n genericType = m.getRawType();\n }\n SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(\n \t\tctxt.getConfig(), m);\n builder.addBackReferenceProperty(name, constructSettableProperty(\n ctxt, beanDesc, propDef, genericType));\n }\n }\n }\n \n /**\n * Method called locate all members used for value injection (if any),\n * constructor {@link com.fasterxml.jackson.databind.deser.impl.ValueInjector} instances, and add them to builder.\n */\n protected void addInjectables(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder)\n throws JsonMappingException\n {\n Map<Object, AnnotatedMember> raw = beanDesc.findInjectables();\n if (raw != null) {\n boolean fixAccess = ctxt.canOverrideAccessModifiers();\n for (Map.Entry<Object, AnnotatedMember> entry : raw.entrySet()) {\n AnnotatedMember m = entry.getValue();\n if (fixAccess) {\n m.fixAccess(); // to ensure we can call it\n }\n builder.addInjectable(PropertyName.construct(m.getName()),\n beanDesc.resolveType(m.getGenericType()),\n beanDesc.getClassAnnotations(), m, entry.getKey());\n }\n }\n }", " /**\n * Method called to construct fallback {@link SettableAnyProperty}\n * for handling unknown bean properties, given a method that\n * has been designated as such setter.\n */\n protected SettableAnyProperty constructAnySetter(DeserializationContext ctxt,\n BeanDescription beanDesc, AnnotatedMethod setter)\n throws JsonMappingException\n {\n if (ctxt.canOverrideAccessModifiers()) {\n setter.fixAccess(); // to ensure we can call it\n }\n // we know it's a 2-arg method, second arg is the value\n JavaType type = beanDesc.bindingsForBeanType().resolveType(setter.getGenericParameterType(1));\n BeanProperty.Std property = new BeanProperty.Std(PropertyName.construct(setter.getName()),\n type, null, beanDesc.getClassAnnotations(), setter,\n PropertyMetadata.STD_OPTIONAL);\n type = resolveType(ctxt, beanDesc, type, setter);", " /* AnySetter can be annotated with @JsonClass (etc) just like a\n * regular setter... so let's see if those are used.\n * Returns null if no annotations, in which case binding will\n * be done at a later point.\n */\n JsonDeserializer<Object> deser = findDeserializerFromAnnotation(ctxt, setter);\n /* Otherwise, method may specify more specific (sub-)class for\n * value (no need to check if explicit deser was specified):\n */\n type = modifyTypeByAnnotation(ctxt, setter, type);\n if (deser == null) {\n deser = type.getValueHandler();\n }\n TypeDeserializer typeDeser = type.getTypeHandler();\n return new SettableAnyProperty(property, setter, type,\n deser, typeDeser);\n }", " /**\n * Method that will construct a regular bean property setter using\n * the given setter method.\n *\n * @return Property constructed, if any; or null to indicate that\n * there should be no property based on given definitions.\n */\n protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanPropertyDefinition propDef,\n Type jdkType)\n throws JsonMappingException\n {\n // need to ensure method is callable (for non-public)\n AnnotatedMember mutator = propDef.getNonConstructorMutator();\n if (ctxt.canOverrideAccessModifiers()) {\n mutator.fixAccess();\n }\n // note: this works since we know there's exactly one argument for methods\n JavaType t0 = beanDesc.resolveType(jdkType);", " BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(),\n t0, propDef.getWrapperName(),\n beanDesc.getClassAnnotations(), mutator, propDef.getMetadata());\n JavaType type = resolveType(ctxt, beanDesc, t0, mutator);\n // did type change?\n if (type != t0) {\n property = property.withType(type);\n }\n \n /* First: does the Method specify the deserializer to use?\n * If so, let's use it.\n */\n JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, mutator);\n type = modifyTypeByAnnotation(ctxt, mutator, type);\n TypeDeserializer typeDeser = type.getTypeHandler();\n SettableBeanProperty prop;\n if (mutator instanceof AnnotatedMethod) {\n prop = new MethodProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator);\n } else {\n prop = new FieldProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), (AnnotatedField) mutator);\n }\n if (propDeser != null) {\n prop = prop.withValueDeserializer(propDeser);\n }\n // [JACKSON-235]: need to retain name of managed forward references:\n AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType();\n if (ref != null && ref.isManagedReference()) {\n prop.setManagedReferenceName(ref.getName());\n }\n ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo();\n if(objectIdInfo != null){\n prop.setObjectIdInfo(objectIdInfo);\n }\n return prop;\n }", " /**\n * Method that will construct a regular bean property setter using\n * the given setter method.\n */\n protected SettableBeanProperty constructSetterlessProperty(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanPropertyDefinition propDef)\n throws JsonMappingException\n {\n final AnnotatedMethod getter = propDef.getGetter();\n // need to ensure it is callable now:\n if (ctxt.canOverrideAccessModifiers()) {\n getter.fixAccess();\n }", " /* 26-Jan-2012, tatu: Alas, this complication is still needed to handle\n * (or at least work around) local type declarations...\n */\n JavaType type = getter.getType(beanDesc.bindingsForBeanType());\n /* First: does the Method specify the deserializer to use?\n * If so, let's use it.\n */\n JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, getter);\n type = modifyTypeByAnnotation(ctxt, getter, type);\n // As per [Issue#501], need full resolution:\n type = resolveType(ctxt, beanDesc, type, getter);\n TypeDeserializer typeDeser = type.getTypeHandler();\n SettableBeanProperty prop = new SetterlessProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), getter);\n if (propDeser != null) {\n prop = prop.withValueDeserializer(propDeser);\n }\n return prop;\n }", " /*\n /**********************************************************\n /* Helper methods for Bean deserializer, other\n /**********************************************************\n */", " /**\n * Helper method used to skip processing for types that we know\n * can not be (i.e. are never consider to be) beans: \n * things like primitives, Arrays, Enums, and proxy types.\n *<p>\n * Note that usually we shouldn't really be getting these sort of\n * types anyway; but better safe than sorry.\n */\n protected boolean isPotentialBeanType(Class<?> type)\n {\n String typeStr = ClassUtil.canBeABeanType(type);\n if (typeStr != null) {\n throw new IllegalArgumentException(\"Can not deserialize Class \"+type.getName()+\" (of type \"+typeStr+\") as a Bean\");\n }\n if (ClassUtil.isProxyType(type)) {\n throw new IllegalArgumentException(\"Can not deserialize Proxy class \"+type.getName()+\" as a Bean\");\n }\n /* also: can't deserialize some local classes: static are ok; in-method not;\n * and with [JACKSON-594], other non-static inner classes are ok\n */\n typeStr = ClassUtil.isLocalType(type, true);\n if (typeStr != null) {\n throw new IllegalArgumentException(\"Can not deserialize Class \"+type.getName()+\" (of type \"+typeStr+\") as a Bean\");\n }\n return true;\n }", " /**\n * Helper method that will check whether given raw type is marked as always ignorable\n * (for purpose of ignoring properties with type)\n */\n protected boolean isIgnorableType(DeserializationConfig config, BeanDescription beanDesc,\n Class<?> type, Map<Class<?>,Boolean> ignoredTypes)\n {\n Boolean status = ignoredTypes.get(type);\n if (status != null) {\n return status.booleanValue();\n }\n BeanDescription desc = config.introspectClassAnnotations(type);\n status = config.getAnnotationIntrospector().isIgnorableType(desc.getClassInfo());\n // We default to 'false', i.e. not ignorable\n return (status == null) ? false : status.booleanValue(); \n }", " private void checkIllegalTypes(DeserializationContext ctxt, JavaType type,\n BeanDescription beanDesc)\n throws JsonMappingException\n {\n // There are certain nasty classes that could cause problems, mostly\n // via default typing -- catch them here.\n String full = type.getRawClass().getName();", " if (_cfgIllegalClassNames.contains(full)) {\n String message = String.format(\"Illegal type (%s) to deserialize: prevented for security reasons\",\n full);\n throw ctxt.mappingException(\"Invalid type definition for type %s: %s\",\n beanDesc, message);\n }\n }\n}" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [8, 69], "buggy_code_start_loc": [7, 69], "filenames": ["release-notes/VERSION", "src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializerFactory.java"], "fixing_code_end_loc": [12, 76], "fixing_code_start_loc": [8, 70], "message": "FasterXML jackson-databind 2.x before 2.9.7 might allow remote attackers to execute arbitrary code by leveraging failure to block the blaze-ds-opt and blaze-ds-core classes from polymorphic deserialization.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "A1BA8F04-46A7-4804-A997-59080034013F", "versionEndExcluding": "2.6.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.6.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "B99066EB-FF79-4D9D-9466-B04AD4D3A814", "versionEndExcluding": "2.7.9.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4D3858C-DAF3-4522-90EC-EFCD13BD121E", "versionEndExcluding": "2.8.11.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "4DA01839-5250-43A7-AFB7-871DC9B8AB32", "versionEndExcluding": "2.9.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.9.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"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}, {"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:banking_platform:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "35AD0C07-9688-4397-8D45-FBB88C0F0C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.0:*:*:*:*:*:*:*", "matchCriteriaId": "8972497F-6E24-45A9-9A18-EB0E842CB1D4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.1:*:*:*:*:*:*:*", "matchCriteriaId": "400509A8-D6F2-432C-A2F1-AD5B8778D0D9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.2:*:*:*:*:*:*:*", "matchCriteriaId": "132CE62A-FBFC-4001-81EC-35D81F73AF48", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:business_process_management_suite:12.1.3.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "B887E174-57AB-449D-AEE4-82DD1A3E5C84", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:business_process_management_suite:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "E869C417-C0E6-4FC3-B406-45598A1D1906", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:clusterware:12.1.0.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "6C9084DB-329E-403F-8D0A-5B9F53183714", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_billing_and_revenue_management:7.5:*:*:*:*:*:*:*", "matchCriteriaId": "E6039DC7-08F2-4DD9-B5B5-B6B22DD2409F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_billing_and_revenue_management:12.0:*:*:*:*:*:*:*", "matchCriteriaId": "7231AF76-3D46-41C4-83E9-6E9E12940BD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:11.2.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "C1E11A25-C7CE-49DF-99CA-352FD21B8230", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:12.1.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "4F3D40B7-925C-413D-AFF3-60BF330D5BC2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:12.2.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "5C614BA7-7103-4ED7-ADD0-56064FE256A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:18c:*:*:*:*:*:*:*", "matchCriteriaId": "6833701E-5510-4180-9523-9CFD318DEE6A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:19c:*:*:*:*:*:*:*", "matchCriteriaId": "B2204841-585F-40C7-A1D9-C34E612808CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "A9E97F04-00ED-48E9-AB40-7A02B3419641", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "FCCE5A11-39E7-4BBB-9E1A-BA4B754103BB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "A5AEC7F5-C353-4CF5-96CE-8C713A2B0C92", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "BB79BB43-E0AB-4F0D-A6EA-000485757EEC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "F238CB66-886D-47E8-8DC0-7FC2025771EB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "59B7B8AD-1210-4C40-8EF7-E2E8156630A1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "0DE4A291-4358-42A9-A68D-E59D9998A1CC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "0D19CF00-FE20-4690-AAB7-8E9DBC68A94F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "A030A498-3361-46F8-BB99-24A66CAE11CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "F6455EB1-C741-45E8-A53E-E7AD7A5D00EE", "versionEndExcluding": "11.2.0.3.23", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "BFD43191-E67F-4D1B-967B-3C7B20331945", "versionEndExcluding": "12.2.0.1.19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "12.2.0.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "062C588A-CBBA-470F-8D11-2F961922E927", "versionEndExcluding": "13.9.4.2.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "13.9.4.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jdeveloper:12.1.3.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "042C243F-EDFE-4A04-AB0B-26E73CC34837", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jdeveloper:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "228DA523-4D6D-48C5-BDB0-DB1A60F23F8B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A1E1023-2EB9-4334-9B74-CA71480F71C2", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "93A4E178-0082-45C5-BBC0-0A4E51C8B1DE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:15.2:*:*:*:*:*:*:*", "matchCriteriaId": "3F021C23-AB9B-4877-833F-D01359A98762", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:16.1:*:*:*:*:*:*:*", "matchCriteriaId": "2F8ED016-32A1-42EE-844E-3E6B2C116B74", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:16.2:*:*:*:*:*:*:*", "matchCriteriaId": "A046CC2C-445F-4336-8810-930570B4FEC6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "0745445C-EC43-4091-BA7C-5105AFCC6F1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:*:*:*:*:*:*:*:*", "matchCriteriaId": "08FA59A8-6A62-4B33-8952-D6E658F8DAC9", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:16.1:*:*:*:*:*:*:*", "matchCriteriaId": "D55A54FD-7DD1-49CD-BE81-0BE73990943C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:16.2:*:*:*:*:*:*:*", "matchCriteriaId": "82EB08C0-2D46-4635-88DF-E54F6452D3A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "202AD518-2E9B-4062-B063-9858AE1F9CE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_merchandising_system:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "792DF04A-2D1B-40B5-B960-3E7152732EB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_merchandising_system:16.0:*:*:*:*:*:*:*", "matchCriteriaId": "46525CA6-4226-4F6F-B899-D800D4DDE0B5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_workforce_management_software:1.60.9.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "9967AAFD-2199-4668-9105-207D4866B707", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:webcenter_portal:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "D6A4F71A-4269-40FC-8F61-1D1301F2B728", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "3A76E5BF-01E4-46E7-8E3B-5ACE75657360", "versionEndExcluding": "3.11.153", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.11", "vulnerable": true}, {"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "E9A6D103-9674-4B04-8397-86501F1D91CF", "versionEndExcluding": "4.6.26", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.6", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "D2452F48-6A8B-4274-B0CE-F1256F400170", "versionEndExcluding": "4.1.18", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.1", "vulnerable": true}], "negate": false, "operator": "OR"}, {"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": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"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}, {"criteria": "cpe:2.3:a:netapp:snapcenter:-:*:*:*:*:*:*:*", "matchCriteriaId": "BDFB1169-41A0-4A86-8E4F-FDA9730B1E94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:netapp:steelstore_cloud_integrated_storage:*:*:*:*:*:*:*:*", "matchCriteriaId": "09A8C9D2-9FFF-4312-95FB-87D79B3C0339", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "FasterXML jackson-databind 2.x before 2.9.7 might allow remote attackers to execute arbitrary code by leveraging failure to block the blaze-ds-opt and blaze-ds-core classes from polymorphic deserialization."}, {"lang": "es", "value": "Las versiones 2.x de FasterXML jackson-databind anteriores a la 2.9.7 podr\u00edan permitir a los atacantes remotos ejecutar c\u00f3digo arbitrario aprovechando un fallo para bloquear las clases blaze-ds-opt y blaze-ds-core de deserializaci\u00f3n polim\u00f3rfica."}], "evaluatorComment": null, "id": "CVE-2018-14719", "lastModified": "2021-05-21T15:22:43.047", "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": "2019-01-02T18:29:00.387", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHBA-2019:0959"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:0782"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:0877"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1782"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1797"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1822"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1823"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:2804"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:2858"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3002"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3140"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3149"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3892"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:4037"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson-databind/commit/87d29af25e82a249ea15858e2d4ecbf64091db44"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson-databind/issues/2097"}, {"source": "cve@mitre.org", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.9.7"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/519eb0fd45642dcecd9ff74cb3e71c20a4753f7d82e2f07864b5108f@%3Cdev.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/b0656d359c7d40ec9f39c8cc61bca66802ef9a2a12ee199f5b0c1442@%3Cdev.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/f9bc3e55f4e28d1dcd1a69aae6d53e609a758e34d2869b4d798e13cc@%3Cissues.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ff8dcfe29377088ab655fda9d585dccd5b1f07fabd94ae84fd60a7f8@%3Ccommits.pulsar.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf1bbc0ea4a9f014cf94df9a12a6477d24a27f52741dbc87f2fd52ff2@%3Cissues.geode.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/03/msg00005.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Mailing List", "Third Party Advisory"], "url": "https://seclists.org/bugtraq/2019/May/68"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20190530-0003/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2019/dsa-4452"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2020.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpuapr2019-5072813.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpujan2019-5072801.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpujul2019-5072835.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpuoct2019-5072832.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/FasterXML/jackson-databind/commit/87d29af25e82a249ea15858e2d4ecbf64091db44"}, "type": "CWE-502"}
245
Determine whether the {function_name} code is vulnerable or not.
[ "package com.fasterxml.jackson.databind.deser;", "import java.lang.reflect.Type;\nimport java.util.*;", "import com.fasterxml.jackson.annotation.ObjectIdGenerator;\nimport com.fasterxml.jackson.annotation.ObjectIdGenerators;\nimport com.fasterxml.jackson.annotation.ObjectIdResolver;\nimport com.fasterxml.jackson.databind.*;\nimport com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;\nimport com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig;\nimport com.fasterxml.jackson.databind.deser.impl.*;\nimport com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer;\nimport com.fasterxml.jackson.databind.introspect.*;\nimport com.fasterxml.jackson.databind.jsontype.TypeDeserializer;\nimport com.fasterxml.jackson.databind.util.ArrayBuilders;\nimport com.fasterxml.jackson.databind.util.ClassUtil;\nimport com.fasterxml.jackson.databind.util.SimpleBeanPropertyDefinition;", "/**\n * Concrete deserializer factory class that adds full Bean deserializer\n * construction logic using class introspection.\n * Note that factories specifically do not implement any form of caching:\n * aside from configuration they are stateless; caching is implemented\n * by other components.\n *<p>\n * Instances of this class are fully immutable as all configuration is\n * done by using \"fluent factories\" (methods that construct new factory\n * instances with different configuration, instead of modifying instance).\n */\npublic class BeanDeserializerFactory\n extends BasicDeserializerFactory\n implements java.io.Serializable // since 2.1\n{\n private static final long serialVersionUID = 1;", " /**\n * Signature of <b>Throwable.initCause</b> method.\n */\n private final static Class<?>[] INIT_CAUSE_PARAMS = new Class<?>[] { Throwable.class };", " private final static Class<?>[] NO_VIEWS = new Class<?>[0];", " /**\n * Set of well-known \"nasty classes\", deserialization of which is considered dangerous\n * and should (and is) prevented by default.\n */\n private final static Set<String> DEFAULT_NO_DESER_CLASS_NAMES;\n static {\n Set<String> s = new HashSet<String>();\n // Courtesy of [https://github.com/kantega/notsoserial]:\n // (and wrt [databind#1599])\n s.add(\"org.apache.commons.collections.functors.InvokerTransformer\");\n s.add(\"org.apache.commons.collections.functors.InstantiateTransformer\");\n s.add(\"org.apache.commons.collections4.functors.InvokerTransformer\");\n s.add(\"org.apache.commons.collections4.functors.InstantiateTransformer\");\n s.add(\"org.codehaus.groovy.runtime.ConvertedClosure\");\n s.add(\"org.codehaus.groovy.runtime.MethodClosure\");\n s.add(\"org.springframework.beans.factory.ObjectFactory\");\n s.add(\"com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl\");", " // [databind#1737]; JDK provided\n s.add(\"java.util.logging.FileHandler\");\n s.add(\"java.rmi.server.UnicastRemoteObject\");\n // [databind#1737]; 3rd party\n s.add(\"org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor\");\n s.add(\"org.springframework.beans.factory.config.PropertyPathFactoryBean\");\n s.add(\"com.mchange.v2.c3p0.JndiRefForwardingDataSource\");\n s.add(\"com.mchange.v2.c3p0.WrapperConnectionPoolDataSource\");", "\n // [databind#2097]: some 3rd party, one JDK-bundled\n s.add(\"org.slf4j.ext.EventData\");\n s.add(\"flex.messaging.util.concurrent.AsynchBeansWorkManagerExecutor\");\n s.add(\"com.sun.deploy.security.ruleset.DRSHelper\");\n s.add(\"org.apache.axis2.jaxws.spi.handler.HandlerResolverImpl\");", "\n DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s);\n }", " /**\n * Set of class names of types that are never to be deserialized.\n */\n private Set<String> _cfgIllegalClassNames = DEFAULT_NO_DESER_CLASS_NAMES;", " /*\n /**********************************************************\n /* Life-cycle\n /**********************************************************\n */\n \n /**\n * Globally shareable thread-safe instance which has no additional custom deserializers\n * registered\n */\n public final static BeanDeserializerFactory instance = new BeanDeserializerFactory(\n new DeserializerFactoryConfig());", " public BeanDeserializerFactory(DeserializerFactoryConfig config) {\n super(config);\n }\n \n /**\n * Method used by module registration functionality, to construct a new bean\n * deserializer factory\n * with different configuration settings.\n */\n @Override\n public DeserializerFactory withConfig(DeserializerFactoryConfig config)\n {\n if (_factoryConfig == config) {\n return this;\n }\n /* 22-Nov-2010, tatu: Handling of subtypes is tricky if we do immutable-with-copy-ctor;\n * and we pretty much have to here either choose between losing subtype instance\n * when registering additional deserializers, or losing deserializers.\n * Instead, let's actually just throw an error if this method is called when subtype\n * has not properly overridden this method; this to indicate problem as soon as possible.\n */\n if (getClass() != BeanDeserializerFactory.class) {\n throw new IllegalStateException(\"Subtype of BeanDeserializerFactory (\"+getClass().getName()\n +\") has not properly overridden method 'withAdditionalDeserializers': can not instantiate subtype with \"\n +\"additional deserializer definitions\");\n }\n return new BeanDeserializerFactory(config);\n }\n \n /*\n /**********************************************************\n /* DeserializerFactory API implementation\n /**********************************************************\n */", " /**\n * Method that {@link DeserializerCache}s call to create a new\n * deserializer for types other than Collections, Maps, arrays and\n * enums.\n */\n @Override\n public JsonDeserializer<Object> createBeanDeserializer(DeserializationContext ctxt,\n JavaType type, BeanDescription beanDesc)\n throws JsonMappingException\n {\n final DeserializationConfig config = ctxt.getConfig();\n // We may also have custom overrides:\n JsonDeserializer<Object> custom = _findCustomBeanDeserializer(type, config, beanDesc);\n if (custom != null) {\n return custom;\n }\n /* One more thing to check: do we have an exception type\n * (Throwable or its sub-classes)? If so, need slightly\n * different handling.\n */\n if (type.isThrowable()) {\n return buildThrowableDeserializer(ctxt, type, beanDesc);\n }\n /* Or, for abstract types, may have alternate means for resolution\n * (defaulting, materialization)\n */\n if (type.isAbstract()) {\n // [JACKSON-41] (v1.6): Let's make it possible to materialize abstract types.\n JavaType concreteType = materializeAbstractType(ctxt, type, beanDesc);\n if (concreteType != null) {\n /* important: introspect actual implementation (abstract class or\n * interface doesn't have constructors, for one)\n */\n beanDesc = config.introspect(concreteType);\n return buildBeanDeserializer(ctxt, concreteType, beanDesc);\n }\n }", " // Otherwise, may want to check handlers for standard types, from superclass:\n @SuppressWarnings(\"unchecked\")\n JsonDeserializer<Object> deser = (JsonDeserializer<Object>) findStdDeserializer(ctxt, type, beanDesc);\n if (deser != null) {\n return deser;\n }", " // Otherwise: could the class be a Bean class? If not, bail out\n if (!isPotentialBeanType(type.getRawClass())) {\n return null;\n }\n // For checks like [databind#1599]\n checkIllegalTypes(ctxt, type, beanDesc);\n // Use generic bean introspection to build deserializer\n return buildBeanDeserializer(ctxt, type, beanDesc);\n }", " @Override\n public JsonDeserializer<Object> createBuilderBasedDeserializer(\n \t\tDeserializationContext ctxt, JavaType valueType, BeanDescription beanDesc,\n \t\tClass<?> builderClass)\n throws JsonMappingException\n {\n \t// First: need a BeanDescription for builder class\n \tJavaType builderType = ctxt.constructType(builderClass);\n \tBeanDescription builderDesc = ctxt.getConfig().introspectForBuilder(builderType);\n \treturn buildBuilderBasedDeserializer(ctxt, valueType, builderDesc);\n }\n \n /**\n * Method called by {@link BeanDeserializerFactory} to see if there might be a standard\n * deserializer registered for given type.\n */\n protected JsonDeserializer<?> findStdDeserializer(DeserializationContext ctxt,\n JavaType type, BeanDescription beanDesc)\n throws JsonMappingException\n {\n // note: we do NOT check for custom deserializers here, caller has already\n // done that\n JsonDeserializer<?> deser = findDefaultDeserializer(ctxt, type, beanDesc);\n // Also: better ensure these are post-processable?\n if (deser != null) {\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n deser = mod.modifyDeserializer(ctxt.getConfig(), beanDesc, deser);\n }\n }\n }\n return deser;\n }\n \n protected JavaType materializeAbstractType(DeserializationContext ctxt,\n JavaType type, BeanDescription beanDesc)\n throws JsonMappingException\n {\n final JavaType abstractType = beanDesc.getType();\n // [JACKSON-502]: Now it is possible to have multiple resolvers too,\n // as they are registered via module interface.\n for (AbstractTypeResolver r : _factoryConfig.abstractTypeResolvers()) {\n JavaType concrete = r.resolveAbstractType(ctxt.getConfig(), abstractType);\n if (concrete != null) {\n return concrete;\n }\n }\n return null;\n }\n \n /*\n /**********************************************************\n /* Public construction method beyond DeserializerFactory API:\n /* can be called from outside as well as overridden by\n /* sub-classes\n /**********************************************************\n */", " /**\n * Method that is to actually build a bean deserializer instance.\n * All basic sanity checks have been done to know that what we have\n * may be a valid bean type, and that there are no default simple\n * deserializers.\n */\n @SuppressWarnings(\"unchecked\")\n public JsonDeserializer<Object> buildBeanDeserializer(DeserializationContext ctxt,\n JavaType type, BeanDescription beanDesc)\n throws JsonMappingException\n {\n // First: check what creators we can use, if any\n ValueInstantiator valueInstantiator;\n /* 04-Jun-2015, tatu: To work around [databind#636], need to catch the\n * issue, defer; this seems like a reasonable good place for now.\n * Note, however, that for non-Bean types (Collections, Maps) this\n * probably won't work and needs to be added elsewhere.\n */\n try {\n valueInstantiator = findValueInstantiator(ctxt, beanDesc);\n } catch (NoClassDefFoundError error) {\n return new NoClassDefFoundDeserializer<Object>(error);\n }\n BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, beanDesc);\n builder.setValueInstantiator(valueInstantiator);\n // And then setters for deserializing from JSON Object\n addBeanProps(ctxt, beanDesc, builder);\n addObjectIdReader(ctxt, beanDesc, builder);", " // managed/back reference fields/setters need special handling... first part\n addReferenceProperties(ctxt, beanDesc, builder);\n addInjectables(ctxt, beanDesc, builder);\n \n final DeserializationConfig config = ctxt.getConfig();\n // [JACKSON-440]: update builder now that all information is in?\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n builder = mod.updateBuilder(config, beanDesc, builder);\n }\n }\n JsonDeserializer<?> deserializer;", " /* 19-Mar-2012, tatu: This check used to be done earlier; but we have to defer\n * it a bit to collect information on ObjectIdReader, for example.\n */\n if (type.isAbstract() && !valueInstantiator.canInstantiate()) {\n deserializer = builder.buildAbstract();\n } else {\n deserializer = builder.build();\n }", " // [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built:\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n deserializer = mod.modifyDeserializer(config, beanDesc, deserializer);\n }\n }\n return (JsonDeserializer<Object>) deserializer;\n }\n \n /**\n * Method for constructing a bean deserializer that uses specified\n * intermediate Builder for binding data, and construction of the\n * value instance.\n * Note that implementation is mostly copied from the regular\n * BeanDeserializer build method.\n */\n @SuppressWarnings(\"unchecked\")\n protected JsonDeserializer<Object> buildBuilderBasedDeserializer(\n \t\tDeserializationContext ctxt, JavaType valueType, BeanDescription builderDesc)\n throws JsonMappingException\n {\n \t// Creators, anyone? (to create builder itself)\n ValueInstantiator valueInstantiator = findValueInstantiator(ctxt, builderDesc);\n final DeserializationConfig config = ctxt.getConfig();\n BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, builderDesc);\n builder.setValueInstantiator(valueInstantiator);\n // And then \"with methods\" for deserializing from JSON Object\n addBeanProps(ctxt, builderDesc, builder);\n addObjectIdReader(ctxt, builderDesc, builder);\n \n // managed/back reference fields/setters need special handling... first part\n addReferenceProperties(ctxt, builderDesc, builder);\n addInjectables(ctxt, builderDesc, builder);", " JsonPOJOBuilder.Value builderConfig = builderDesc.findPOJOBuilderConfig();\n final String buildMethodName = (builderConfig == null) ?\n \"build\" : builderConfig.buildMethodName;\n \n // and lastly, find build method to use:\n AnnotatedMethod buildMethod = builderDesc.findMethod(buildMethodName, null);\n if (buildMethod != null) { // note: can't yet throw error; may be given build method\n if (config.canOverrideAccessModifiers()) {\n \tClassUtil.checkAndFixAccess(buildMethod.getMember());\n }\n }\n builder.setPOJOBuilder(buildMethod, builderConfig);\n // this may give us more information...\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n builder = mod.updateBuilder(config, builderDesc, builder);\n }\n }\n JsonDeserializer<?> deserializer = builder.buildBuilderBased(\n \t\tvalueType, buildMethodName);", " // [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built:\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n deserializer = mod.modifyDeserializer(config, builderDesc, deserializer);\n }\n }\n return (JsonDeserializer<Object>) deserializer;\n }\n \n protected void addObjectIdReader(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder)\n throws JsonMappingException\n {\n ObjectIdInfo objectIdInfo = beanDesc.getObjectIdInfo();\n if (objectIdInfo == null) {\n return;\n }\n Class<?> implClass = objectIdInfo.getGeneratorType();\n JavaType idType;\n SettableBeanProperty idProp;\n ObjectIdGenerator<?> gen;", " ObjectIdResolver resolver = ctxt.objectIdResolverInstance(beanDesc.getClassInfo(), objectIdInfo);", " // Just one special case: Property-based generator is trickier\n if (implClass == ObjectIdGenerators.PropertyGenerator.class) { // most special one, needs extra work\n PropertyName propName = objectIdInfo.getPropertyName();\n idProp = builder.findProperty(propName);\n if (idProp == null) {\n throw new IllegalArgumentException(\"Invalid Object Id definition for \"\n +beanDesc.getBeanClass().getName()+\": can not find property with name '\"+propName+\"'\");\n }\n idType = idProp.getType();\n gen = new PropertyBasedObjectIdGenerator(objectIdInfo.getScope());\n } else {\n JavaType type = ctxt.constructType(implClass);\n idType = ctxt.getTypeFactory().findTypeParameters(type, ObjectIdGenerator.class)[0];\n idProp = null;\n gen = ctxt.objectIdGeneratorInstance(beanDesc.getClassInfo(), objectIdInfo);\n }\n // also: unlike with value deserializers, let's just resolve one we need here\n JsonDeserializer<?> deser = ctxt.findRootValueDeserializer(idType);\n builder.setObjectIdReader(ObjectIdReader.construct(idType,\n objectIdInfo.getPropertyName(), gen, deser, idProp, resolver));\n }\n \n @SuppressWarnings(\"unchecked\")\n public JsonDeserializer<Object> buildThrowableDeserializer(DeserializationContext ctxt,\n JavaType type, BeanDescription beanDesc)\n throws JsonMappingException\n {\n final DeserializationConfig config = ctxt.getConfig();\n // first: construct like a regular bean deserializer...\n BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, beanDesc);\n builder.setValueInstantiator(findValueInstantiator(ctxt, beanDesc));", " addBeanProps(ctxt, beanDesc, builder);\n // (and assume there won't be any back references)", " // But then let's decorate things a bit\n /* To resolve [JACKSON-95], need to add \"initCause\" as setter\n * for exceptions (sub-classes of Throwable).\n */\n AnnotatedMethod am = beanDesc.findMethod(\"initCause\", INIT_CAUSE_PARAMS);\n if (am != null) { // should never be null\n SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(ctxt.getConfig(), am,\n new PropertyName(\"cause\"));\n SettableBeanProperty prop = constructSettableProperty(ctxt, beanDesc, propDef,\n am.getGenericParameterType(0));\n if (prop != null) {\n /* 21-Aug-2011, tatus: We may actually have found 'cause' property\n * to set (with new 1.9 code)... but let's replace it just in case,\n * otherwise can end up with odd errors.\n */\n builder.addOrReplaceProperty(prop, true);\n }\n }", " // And also need to ignore \"localizedMessage\"\n builder.addIgnorable(\"localizedMessage\");\n // [JACKSON-794]: JDK 7 also added \"getSuppressed\", skip if we have such data:\n builder.addIgnorable(\"suppressed\");\n /* As well as \"message\": it will be passed via constructor,\n * as there's no 'setMessage()' method\n */\n builder.addIgnorable(\"message\");", " // [JACKSON-440]: update builder now that all information is in?\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n builder = mod.updateBuilder(config, beanDesc, builder);\n }\n }\n JsonDeserializer<?> deserializer = builder.build();\n \n /* At this point it ought to be a BeanDeserializer; if not, must assume\n * it's some other thing that can handle deserialization ok...\n */\n if (deserializer instanceof BeanDeserializer) {\n deserializer = new ThrowableDeserializer((BeanDeserializer) deserializer);\n }", " // [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built:\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n deserializer = mod.modifyDeserializer(config, beanDesc, deserializer);\n }\n }\n return (JsonDeserializer<Object>) deserializer;\n }", " /*\n /**********************************************************\n /* Helper methods for Bean deserializer construction,\n /* overridable by sub-classes\n /**********************************************************\n */", " /**\n * Overridable method that constructs a {@link BeanDeserializerBuilder}\n * which is used to accumulate information needed to create deserializer\n * instance.\n */\n protected BeanDeserializerBuilder constructBeanDeserializerBuilder(DeserializationContext ctxt,\n BeanDescription beanDesc) {\n return new BeanDeserializerBuilder(beanDesc, ctxt.getConfig());\n }\n \n /**\n * Method called to figure out settable properties for the\n * bean deserializer to use.\n *<p>\n * Note: designed to be overridable, and effort is made to keep interface\n * similar between versions.\n */\n protected void addBeanProps(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder)\n throws JsonMappingException\n {\n final SettableBeanProperty[] creatorProps =\n builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig());\n final boolean isConcrete = !beanDesc.getType().isAbstract();\n \n // Things specified as \"ok to ignore\"? [JACKSON-77]\n AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();\n boolean ignoreAny = false;\n {\n Boolean B = intr.findIgnoreUnknownProperties(beanDesc.getClassInfo());\n if (B != null) {\n ignoreAny = B.booleanValue();\n builder.setIgnoreUnknownProperties(ignoreAny);\n }\n }\n // Or explicit/implicit definitions?\n Set<String> ignored = ArrayBuilders.arrayToSet(intr.findPropertiesToIgnore(beanDesc.getClassInfo(), false)); \n for (String propName : ignored) {\n builder.addIgnorable(propName);\n }\n // Also, do we have a fallback \"any\" setter?\n AnnotatedMethod anySetter = beanDesc.findAnySetter();\n if (anySetter != null) {\n builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetter));\n }\n // NOTE: we do NOT add @JsonIgnore'd properties into blocked ones if there's any-setter\n // Implicit ones via @JsonIgnore and equivalent?\n if (anySetter == null) {\n Collection<String> ignored2 = beanDesc.getIgnoredPropertyNames();\n if (ignored2 != null) {\n for (String propName : ignored2) {\n // allow ignoral of similarly named JSON property, but do not force;\n // latter means NOT adding this to 'ignored':\n builder.addIgnorable(propName);\n }\n }\n }\n final boolean useGettersAsSetters = (ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)\n && ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));", " // Ok: let's then filter out property definitions\n List<BeanPropertyDefinition> propDefs = filterBeanProps(ctxt,\n beanDesc, builder, beanDesc.findProperties(), ignored);", " // After which we can let custom code change the set\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);\n }\n }\n \n // At which point we still have all kinds of properties; not all with mutators:\n for (BeanPropertyDefinition propDef : propDefs) {\n SettableBeanProperty prop = null;\n /* 18-Oct-2013, tatu: Although constructor parameters have highest precedence,\n * we need to do linkage (as per [Issue#318]), and so need to start with\n * other types, and only then create constructor parameter, if any.\n */\n if (propDef.hasSetter()) {\n Type propertyType = propDef.getSetter().getGenericParameterType(0);\n prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);\n } else if (propDef.hasField()) {\n Type propertyType = propDef.getField().getGenericType();\n prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);\n } else if (useGettersAsSetters && propDef.hasGetter()) {\n /* As per [JACKSON-88], may also need to consider getters\n * for Map/Collection properties; but with lowest precedence\n */\n AnnotatedMethod getter = propDef.getGetter();\n // should only consider Collections and Maps, for now?\n Class<?> rawPropertyType = getter.getRawType();\n if (Collection.class.isAssignableFrom(rawPropertyType)\n || Map.class.isAssignableFrom(rawPropertyType)) {\n prop = constructSetterlessProperty(ctxt, beanDesc, propDef);\n }\n }\n // 25-Sep-2014, tatu: No point in finding constructor parameters for abstract types\n // (since they are never used anyway)\n if (isConcrete && propDef.hasConstructorParameter()) {\n /* [JACKSON-700] If property is passed via constructor parameter, we must\n * handle things in special way. Not sure what is the most optimal way...\n * for now, let's just call a (new) method in builder, which does nothing.\n */\n // but let's call a method just to allow custom builders to be aware...\n final String name = propDef.getName();\n CreatorProperty cprop = null;\n if (creatorProps != null) {\n for (SettableBeanProperty cp : creatorProps) {\n if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {\n cprop = (CreatorProperty) cp;\n break;\n }\n }\n }\n if (cprop == null) {\n throw ctxt.mappingException(\"Could not find creator property with name '%s' (in class %s)\",\n name, beanDesc.getBeanClass().getName());\n }\n if (prop != null) {\n cprop.setFallbackSetter(prop);\n }\n prop = cprop;\n builder.addCreatorProperty(cprop);\n continue;\n }", " if (prop != null) {\n Class<?>[] views = propDef.findViews();\n if (views == null) {\n // one more twist: if default inclusion disabled, need to force empty set of views\n if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) {\n views = NO_VIEWS;\n }\n }\n // one more thing before adding to builder: copy any metadata\n prop.setViews(views);\n builder.addProperty(prop);\n }\n }\n }\n \n /**\n * Helper method called to filter out explicit ignored properties,\n * as well as properties that have \"ignorable types\".\n * Note that this will not remove properties that have no\n * setters.\n */\n protected List<BeanPropertyDefinition> filterBeanProps(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder,\n List<BeanPropertyDefinition> propDefsIn,\n Set<String> ignored)\n throws JsonMappingException\n {\n ArrayList<BeanPropertyDefinition> result = new ArrayList<BeanPropertyDefinition>(\n Math.max(4, propDefsIn.size()));\n HashMap<Class<?>,Boolean> ignoredTypes = new HashMap<Class<?>,Boolean>();\n // These are all valid setters, but we do need to introspect bit more\n for (BeanPropertyDefinition property : propDefsIn) {\n String name = property.getName();\n if (ignored.contains(name)) { // explicit ignoral using @JsonIgnoreProperties needs to block entries\n continue;\n }\n if (!property.hasConstructorParameter()) { // never skip constructor params\n Class<?> rawPropertyType = null;\n if (property.hasSetter()) {\n rawPropertyType = property.getSetter().getRawParameterType(0);\n } else if (property.hasField()) {\n rawPropertyType = property.getField().getRawType();\n }", " // [JACKSON-429] Some types are declared as ignorable as well\n if ((rawPropertyType != null)\n && (isIgnorableType(ctxt.getConfig(), beanDesc, rawPropertyType, ignoredTypes))) {\n // important: make ignorable, to avoid errors if value is actually seen\n builder.addIgnorable(name);\n continue;\n }\n }\n result.add(property);\n }\n return result;\n }\n \n /**\n * Method that will find if bean has any managed- or back-reference properties,\n * and if so add them to bean, to be linked during resolution phase.\n */\n protected void addReferenceProperties(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder)\n throws JsonMappingException\n {\n // and then back references, not necessarily found as regular properties\n Map<String,AnnotatedMember> refs = beanDesc.findBackReferenceProperties();\n if (refs != null) {\n for (Map.Entry<String, AnnotatedMember> en : refs.entrySet()) {\n String name = en.getKey();\n AnnotatedMember m = en.getValue();\n Type genericType;\n if (m instanceof AnnotatedMethod) {\n genericType = ((AnnotatedMethod) m).getGenericParameterType(0);\n } else {\n genericType = m.getRawType();\n }\n SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(\n \t\tctxt.getConfig(), m);\n builder.addBackReferenceProperty(name, constructSettableProperty(\n ctxt, beanDesc, propDef, genericType));\n }\n }\n }\n \n /**\n * Method called locate all members used for value injection (if any),\n * constructor {@link com.fasterxml.jackson.databind.deser.impl.ValueInjector} instances, and add them to builder.\n */\n protected void addInjectables(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder)\n throws JsonMappingException\n {\n Map<Object, AnnotatedMember> raw = beanDesc.findInjectables();\n if (raw != null) {\n boolean fixAccess = ctxt.canOverrideAccessModifiers();\n for (Map.Entry<Object, AnnotatedMember> entry : raw.entrySet()) {\n AnnotatedMember m = entry.getValue();\n if (fixAccess) {\n m.fixAccess(); // to ensure we can call it\n }\n builder.addInjectable(PropertyName.construct(m.getName()),\n beanDesc.resolveType(m.getGenericType()),\n beanDesc.getClassAnnotations(), m, entry.getKey());\n }\n }\n }", " /**\n * Method called to construct fallback {@link SettableAnyProperty}\n * for handling unknown bean properties, given a method that\n * has been designated as such setter.\n */\n protected SettableAnyProperty constructAnySetter(DeserializationContext ctxt,\n BeanDescription beanDesc, AnnotatedMethod setter)\n throws JsonMappingException\n {\n if (ctxt.canOverrideAccessModifiers()) {\n setter.fixAccess(); // to ensure we can call it\n }\n // we know it's a 2-arg method, second arg is the value\n JavaType type = beanDesc.bindingsForBeanType().resolveType(setter.getGenericParameterType(1));\n BeanProperty.Std property = new BeanProperty.Std(PropertyName.construct(setter.getName()),\n type, null, beanDesc.getClassAnnotations(), setter,\n PropertyMetadata.STD_OPTIONAL);\n type = resolveType(ctxt, beanDesc, type, setter);", " /* AnySetter can be annotated with @JsonClass (etc) just like a\n * regular setter... so let's see if those are used.\n * Returns null if no annotations, in which case binding will\n * be done at a later point.\n */\n JsonDeserializer<Object> deser = findDeserializerFromAnnotation(ctxt, setter);\n /* Otherwise, method may specify more specific (sub-)class for\n * value (no need to check if explicit deser was specified):\n */\n type = modifyTypeByAnnotation(ctxt, setter, type);\n if (deser == null) {\n deser = type.getValueHandler();\n }\n TypeDeserializer typeDeser = type.getTypeHandler();\n return new SettableAnyProperty(property, setter, type,\n deser, typeDeser);\n }", " /**\n * Method that will construct a regular bean property setter using\n * the given setter method.\n *\n * @return Property constructed, if any; or null to indicate that\n * there should be no property based on given definitions.\n */\n protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanPropertyDefinition propDef,\n Type jdkType)\n throws JsonMappingException\n {\n // need to ensure method is callable (for non-public)\n AnnotatedMember mutator = propDef.getNonConstructorMutator();\n if (ctxt.canOverrideAccessModifiers()) {\n mutator.fixAccess();\n }\n // note: this works since we know there's exactly one argument for methods\n JavaType t0 = beanDesc.resolveType(jdkType);", " BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(),\n t0, propDef.getWrapperName(),\n beanDesc.getClassAnnotations(), mutator, propDef.getMetadata());\n JavaType type = resolveType(ctxt, beanDesc, t0, mutator);\n // did type change?\n if (type != t0) {\n property = property.withType(type);\n }\n \n /* First: does the Method specify the deserializer to use?\n * If so, let's use it.\n */\n JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, mutator);\n type = modifyTypeByAnnotation(ctxt, mutator, type);\n TypeDeserializer typeDeser = type.getTypeHandler();\n SettableBeanProperty prop;\n if (mutator instanceof AnnotatedMethod) {\n prop = new MethodProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator);\n } else {\n prop = new FieldProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), (AnnotatedField) mutator);\n }\n if (propDeser != null) {\n prop = prop.withValueDeserializer(propDeser);\n }\n // [JACKSON-235]: need to retain name of managed forward references:\n AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType();\n if (ref != null && ref.isManagedReference()) {\n prop.setManagedReferenceName(ref.getName());\n }\n ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo();\n if(objectIdInfo != null){\n prop.setObjectIdInfo(objectIdInfo);\n }\n return prop;\n }", " /**\n * Method that will construct a regular bean property setter using\n * the given setter method.\n */\n protected SettableBeanProperty constructSetterlessProperty(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanPropertyDefinition propDef)\n throws JsonMappingException\n {\n final AnnotatedMethod getter = propDef.getGetter();\n // need to ensure it is callable now:\n if (ctxt.canOverrideAccessModifiers()) {\n getter.fixAccess();\n }", " /* 26-Jan-2012, tatu: Alas, this complication is still needed to handle\n * (or at least work around) local type declarations...\n */\n JavaType type = getter.getType(beanDesc.bindingsForBeanType());\n /* First: does the Method specify the deserializer to use?\n * If so, let's use it.\n */\n JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, getter);\n type = modifyTypeByAnnotation(ctxt, getter, type);\n // As per [Issue#501], need full resolution:\n type = resolveType(ctxt, beanDesc, type, getter);\n TypeDeserializer typeDeser = type.getTypeHandler();\n SettableBeanProperty prop = new SetterlessProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), getter);\n if (propDeser != null) {\n prop = prop.withValueDeserializer(propDeser);\n }\n return prop;\n }", " /*\n /**********************************************************\n /* Helper methods for Bean deserializer, other\n /**********************************************************\n */", " /**\n * Helper method used to skip processing for types that we know\n * can not be (i.e. are never consider to be) beans: \n * things like primitives, Arrays, Enums, and proxy types.\n *<p>\n * Note that usually we shouldn't really be getting these sort of\n * types anyway; but better safe than sorry.\n */\n protected boolean isPotentialBeanType(Class<?> type)\n {\n String typeStr = ClassUtil.canBeABeanType(type);\n if (typeStr != null) {\n throw new IllegalArgumentException(\"Can not deserialize Class \"+type.getName()+\" (of type \"+typeStr+\") as a Bean\");\n }\n if (ClassUtil.isProxyType(type)) {\n throw new IllegalArgumentException(\"Can not deserialize Proxy class \"+type.getName()+\" as a Bean\");\n }\n /* also: can't deserialize some local classes: static are ok; in-method not;\n * and with [JACKSON-594], other non-static inner classes are ok\n */\n typeStr = ClassUtil.isLocalType(type, true);\n if (typeStr != null) {\n throw new IllegalArgumentException(\"Can not deserialize Class \"+type.getName()+\" (of type \"+typeStr+\") as a Bean\");\n }\n return true;\n }", " /**\n * Helper method that will check whether given raw type is marked as always ignorable\n * (for purpose of ignoring properties with type)\n */\n protected boolean isIgnorableType(DeserializationConfig config, BeanDescription beanDesc,\n Class<?> type, Map<Class<?>,Boolean> ignoredTypes)\n {\n Boolean status = ignoredTypes.get(type);\n if (status != null) {\n return status.booleanValue();\n }\n BeanDescription desc = config.introspectClassAnnotations(type);\n status = config.getAnnotationIntrospector().isIgnorableType(desc.getClassInfo());\n // We default to 'false', i.e. not ignorable\n return (status == null) ? false : status.booleanValue(); \n }", " private void checkIllegalTypes(DeserializationContext ctxt, JavaType type,\n BeanDescription beanDesc)\n throws JsonMappingException\n {\n // There are certain nasty classes that could cause problems, mostly\n // via default typing -- catch them here.\n String full = type.getRawClass().getName();", " if (_cfgIllegalClassNames.contains(full)) {\n String message = String.format(\"Illegal type (%s) to deserialize: prevented for security reasons\",\n full);\n throw ctxt.mappingException(\"Invalid type definition for type %s: %s\",\n beanDesc, message);\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 ]
PreciseBugs
{"buggy_code_end_loc": [8, 69], "buggy_code_start_loc": [7, 69], "filenames": ["release-notes/VERSION", "src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializerFactory.java"], "fixing_code_end_loc": [12, 76], "fixing_code_start_loc": [8, 70], "message": "FasterXML jackson-databind 2.x before 2.9.7 might allow remote attackers to execute arbitrary code by leveraging failure to block the blaze-ds-opt and blaze-ds-core classes from polymorphic deserialization.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "A1BA8F04-46A7-4804-A997-59080034013F", "versionEndExcluding": "2.6.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.6.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "B99066EB-FF79-4D9D-9466-B04AD4D3A814", "versionEndExcluding": "2.7.9.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "F4D3858C-DAF3-4522-90EC-EFCD13BD121E", "versionEndExcluding": "2.8.11.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:fasterxml:jackson-databind:*:*:*:*:*:*:*:*", "matchCriteriaId": "4DA01839-5250-43A7-AFB7-871DC9B8AB32", "versionEndExcluding": "2.9.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.9.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"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}, {"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:banking_platform:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "35AD0C07-9688-4397-8D45-FBB88C0F0C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.0:*:*:*:*:*:*:*", "matchCriteriaId": "8972497F-6E24-45A9-9A18-EB0E842CB1D4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.1:*:*:*:*:*:*:*", "matchCriteriaId": "400509A8-D6F2-432C-A2F1-AD5B8778D0D9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.6.2:*:*:*:*:*:*:*", "matchCriteriaId": "132CE62A-FBFC-4001-81EC-35D81F73AF48", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:business_process_management_suite:12.1.3.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "B887E174-57AB-449D-AEE4-82DD1A3E5C84", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:business_process_management_suite:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "E869C417-C0E6-4FC3-B406-45598A1D1906", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:clusterware:12.1.0.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "6C9084DB-329E-403F-8D0A-5B9F53183714", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_billing_and_revenue_management:7.5:*:*:*:*:*:*:*", "matchCriteriaId": "E6039DC7-08F2-4DD9-B5B5-B6B22DD2409F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_billing_and_revenue_management:12.0:*:*:*:*:*:*:*", "matchCriteriaId": "7231AF76-3D46-41C4-83E9-6E9E12940BD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:11.2.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "C1E11A25-C7CE-49DF-99CA-352FD21B8230", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:12.1.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "4F3D40B7-925C-413D-AFF3-60BF330D5BC2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:12.2.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "5C614BA7-7103-4ED7-ADD0-56064FE256A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:18c:*:*:*:*:*:*:*", "matchCriteriaId": "6833701E-5510-4180-9523-9CFD318DEE6A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:database_server:19c:*:*:*:*:*:*:*", "matchCriteriaId": "B2204841-585F-40C7-A1D9-C34E612808CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "A9E97F04-00ED-48E9-AB40-7A02B3419641", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "FCCE5A11-39E7-4BBB-9E1A-BA4B754103BB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_for_virtualization:13.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "A5AEC7F5-C353-4CF5-96CE-8C713A2B0C92", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "BB79BB43-E0AB-4F0D-A6EA-000485757EEC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "F238CB66-886D-47E8-8DC0-7FC2025771EB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "59B7B8AD-1210-4C40-8EF7-E2E8156630A1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "0DE4A291-4358-42A9-A68D-E59D9998A1CC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "0D19CF00-FE20-4690-AAB7-8E9DBC68A94F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:financial_services_analytical_applications_infrastructure:8.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "A030A498-3361-46F8-BB99-24A66CAE11CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "F6455EB1-C741-45E8-A53E-E7AD7A5D00EE", "versionEndExcluding": "11.2.0.3.23", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "BFD43191-E67F-4D1B-967B-3C7B20331945", "versionEndExcluding": "12.2.0.1.19", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "12.2.0.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:global_lifecycle_management_opatch:*:*:*:*:*:*:*:*", "matchCriteriaId": "062C588A-CBBA-470F-8D11-2F961922E927", "versionEndExcluding": "13.9.4.2.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "13.9.4.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jdeveloper:12.1.3.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "042C243F-EDFE-4A04-AB0B-26E73CC34837", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jdeveloper:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "228DA523-4D6D-48C5-BDB0-DB1A60F23F8B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A1E1023-2EB9-4334-9B74-CA71480F71C2", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "93A4E178-0082-45C5-BBC0-0A4E51C8B1DE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:15.2:*:*:*:*:*:*:*", "matchCriteriaId": "3F021C23-AB9B-4877-833F-D01359A98762", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:16.1:*:*:*:*:*:*:*", "matchCriteriaId": "2F8ED016-32A1-42EE-844E-3E6B2C116B74", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:16.2:*:*:*:*:*:*:*", "matchCriteriaId": "A046CC2C-445F-4336-8810-930570B4FEC6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_p6_enterprise_project_portfolio_management:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "0745445C-EC43-4091-BA7C-5105AFCC6F1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:*:*:*:*:*:*:*:*", "matchCriteriaId": "08FA59A8-6A62-4B33-8952-D6E658F8DAC9", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:16.1:*:*:*:*:*:*:*", "matchCriteriaId": "D55A54FD-7DD1-49CD-BE81-0BE73990943C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:16.2:*:*:*:*:*:*:*", "matchCriteriaId": "82EB08C0-2D46-4635-88DF-E54F6452D3A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "202AD518-2E9B-4062-B063-9858AE1F9CE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_merchandising_system:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "792DF04A-2D1B-40B5-B960-3E7152732EB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_merchandising_system:16.0:*:*:*:*:*:*:*", "matchCriteriaId": "46525CA6-4226-4F6F-B899-D800D4DDE0B5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:retail_workforce_management_software:1.60.9.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "9967AAFD-2199-4668-9105-207D4866B707", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:webcenter_portal:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "D6A4F71A-4269-40FC-8F61-1D1301F2B728", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "3A76E5BF-01E4-46E7-8E3B-5ACE75657360", "versionEndExcluding": "3.11.153", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.11", "vulnerable": true}, {"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "E9A6D103-9674-4B04-8397-86501F1D91CF", "versionEndExcluding": "4.6.26", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.6", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openshift_container_platform:*:*:*:*:*:*:*:*", "matchCriteriaId": "D2452F48-6A8B-4274-B0CE-F1256F400170", "versionEndExcluding": "4.1.18", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.1", "vulnerable": true}], "negate": false, "operator": "OR"}, {"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": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"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}, {"criteria": "cpe:2.3:a:netapp:snapcenter:-:*:*:*:*:*:*:*", "matchCriteriaId": "BDFB1169-41A0-4A86-8E4F-FDA9730B1E94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:netapp:steelstore_cloud_integrated_storage:*:*:*:*:*:*:*:*", "matchCriteriaId": "09A8C9D2-9FFF-4312-95FB-87D79B3C0339", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "FasterXML jackson-databind 2.x before 2.9.7 might allow remote attackers to execute arbitrary code by leveraging failure to block the blaze-ds-opt and blaze-ds-core classes from polymorphic deserialization."}, {"lang": "es", "value": "Las versiones 2.x de FasterXML jackson-databind anteriores a la 2.9.7 podr\u00edan permitir a los atacantes remotos ejecutar c\u00f3digo arbitrario aprovechando un fallo para bloquear las clases blaze-ds-opt y blaze-ds-core de deserializaci\u00f3n polim\u00f3rfica."}], "evaluatorComment": null, "id": "CVE-2018-14719", "lastModified": "2021-05-21T15:22:43.047", "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": "2019-01-02T18:29:00.387", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHBA-2019:0959"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:0782"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:0877"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1782"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1797"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1822"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:1823"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:2804"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:2858"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3002"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3140"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3149"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:3892"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2019:4037"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson-databind/commit/87d29af25e82a249ea15858e2d4ecbf64091db44"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson-databind/issues/2097"}, {"source": "cve@mitre.org", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.9.7"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/519eb0fd45642dcecd9ff74cb3e71c20a4753f7d82e2f07864b5108f@%3Cdev.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/b0656d359c7d40ec9f39c8cc61bca66802ef9a2a12ee199f5b0c1442@%3Cdev.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/f9bc3e55f4e28d1dcd1a69aae6d53e609a758e34d2869b4d798e13cc@%3Cissues.drill.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/ff8dcfe29377088ab655fda9d585dccd5b1f07fabd94ae84fd60a7f8@%3Ccommits.pulsar.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.apache.org/thread.html/rf1bbc0ea4a9f014cf94df9a12a6477d24a27f52741dbc87f2fd52ff2@%3Cissues.geode.apache.org%3E"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/03/msg00005.html"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Mailing List", "Third Party Advisory"], "url": "https://seclists.org/bugtraq/2019/May/68"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20190530-0003/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2019/dsa-4452"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2020.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpuapr2019-5072813.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpujan2019-5072801.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpujul2019-5072835.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/technetwork/security-advisory/cpuoct2019-5072832.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/FasterXML/jackson-databind/commit/87d29af25e82a249ea15858e2d4ecbf64091db44"}, "type": "CWE-502"}
245